Programs & Examples On #Lcid

LCID's are locale ID's that represent a language and country in the form of a numeric ID.

Running an Excel macro via Python?

For Python 3.7 or later,(2018-10-10), I have to combine both @Alejandro BR and SMNALLY's answer, coz @Alejandro forget to define wincl.

import os, os.path
import win32com.client
if os.path.exists('C:/Users/jz/Desktop/test.xlsm'):
    excel_macro = win32com.client.DispatchEx("Excel.Application") # DispatchEx is required in the newest versions of Python.
    excel_path = os.path.expanduser('C:/Users/jz/Desktop/test.xlsm')
    workbook = excel_macro.Workbooks.Open(Filename = excel_path, ReadOnly =1)
    excel_macro.Application.Run("test.xlsm!Module1.Macro1") # update Module1 with your module, Macro1 with your macro
    workbook.Save()
    excel_macro.Application.Quit()  
    del excel_macro

How to Install Windows Phone 8 SDK on Windows 7

Here is a link from developer.nokia.com wiki pages, which explains how to install Windows Phone 8 SDK on a Virtual Machine with Working Emulator

And another link here

AFAIK, it is not possible to directly install WP8 SDK in Windows 7, because WP8 sdk is VS 2012 supported and also its emulator works on a Hyper-V (which is integrated into the Windows 8).

Windows Application has stopped working :: Event Name CLR20r3

This is just because the application is built in non unicode language fonts and you are running the system on unicode fonts. change your default non unicode fonts to arabic by going in regional settings advanced tab in control panel. That will solve your problem.

Logging POST data from $request_body

Try echo_read_request_body.

"echo_read_request_body ... Explicitly reads request body so that the $request_body variable will always have non-empty values (unless the body is so big that it has been saved by Nginx to a local temporary file)."

location /log {
  log_format postdata $request_body;
  access_log /mnt/logs/nginx/my_tracking.access.log postdata;
  echo_read_request_body;
}

How do I get the serial key for Visual Studio Express?

I believe that if you download the offline ISO image file, and use that to install Visual Studio Express, you won't have to register.

Go here and find the link that says "All - Offline Install ISO image file". Click on it to expand it, select your language, and then click "Download".

Otherwise, it's possible that online registration is simply down for a while, as the error message indicates. You have 30 days before it expires, so give it a few days before starting to panic.

pySerial write() won't take my string

I had the same "TypeError: an integer is required" error message when attempting to write. Thanks, the .encode() solved it for me. I'm running python 3.4 on a Dell D530 running 32 bit Windows XP Pro.

I'm omitting the com port settings here:

>>>import serial

>>>ser = serial.Serial(5)

>>>ser.close()

>>>ser.open()

>>>ser.write("1".encode())

1

>>>

width:auto for <input> fields

The only option I can think of is using width:100%. If you want to have a padding on the input field too, than just place a container label around it, move the formatting to that label instead, while also specify the padding to the label. Input fields are rigid.

Reversing an Array in Java

This code would help:

int [] a={1,2,3,4,5,6,7};
for(int i=a.length-1;i>=0;i--)
  System.out.println(a[i]);

How can I initialize an array without knowing it size?

Use LinkedList instead. Than, you can create an array if necessary.

How do I base64 encode (decode) in C?

I needed C++ implementation working on std::string. None of answers satisfied my needs, I needed simple two-function solution for encoding and decoding, but I was too lazy to write my own code, so I found this:

http://www.adp-gmbh.ch/cpp/common/base64.html

Credits for code go to René Nyffenegger.

Putting the code below in case the site goes down:

base64.cpp

/* 
   base64.cpp and base64.h

   Copyright (C) 2004-2008 René Nyffenegger

   This source code is provided 'as-is', without any express or implied
   warranty. In no event will the author be held liable for any damages
   arising from the use of this software.

   Permission is granted to anyone to use this software for any purpose,
   including commercial applications, and to alter it and redistribute it
   freely, subject to the following restrictions:

   1. The origin of this source code must not be misrepresented; you must not
      claim that you wrote the original source code. If you use this source code
      in a product, an acknowledgment in the product documentation would be
      appreciated but is not required.

   2. Altered source versions must be plainly marked as such, and must not be
      misrepresented as being the original source code.

   3. This notice may not be removed or altered from any source distribution.

   René Nyffenegger [email protected]

*/

#include "base64.h"
#include <iostream>

static const std::string base64_chars = 
             "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
             "abcdefghijklmnopqrstuvwxyz"
             "0123456789+/";


static inline bool is_base64(unsigned char c) {
  return (isalnum(c) || (c == '+') || (c == '/'));
}

std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
  std::string ret;
  int i = 0;
  int j = 0;
  unsigned char char_array_3[3];
  unsigned char char_array_4[4];

  while (in_len--) {
    char_array_3[i++] = *(bytes_to_encode++);
    if (i == 3) {
      char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
      char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
      char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
      char_array_4[3] = char_array_3[2] & 0x3f;

      for(i = 0; (i <4) ; i++)
        ret += base64_chars[char_array_4[i]];
      i = 0;
    }
  }

  if (i)
  {
    for(j = i; j < 3; j++)
      char_array_3[j] = '\0';

    char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
    char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
    char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
    char_array_4[3] = char_array_3[2] & 0x3f;

    for (j = 0; (j < i + 1); j++)
      ret += base64_chars[char_array_4[j]];

    while((i++ < 3))
      ret += '=';

  }

  return ret;

}

std::string base64_decode(std::string const& encoded_string) {
  int in_len = encoded_string.size();
  int i = 0;
  int j = 0;
  int in_ = 0;
  unsigned char char_array_4[4], char_array_3[3];
  std::string ret;

  while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
    char_array_4[i++] = encoded_string[in_]; in_++;
    if (i ==4) {
      for (i = 0; i <4; i++)
        char_array_4[i] = base64_chars.find(char_array_4[i]);

      char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
      char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
      char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

      for (i = 0; (i < 3); i++)
        ret += char_array_3[i];
      i = 0;
    }
  }

  if (i) {
    for (j = i; j <4; j++)
      char_array_4[j] = 0;

    for (j = 0; j <4; j++)
      char_array_4[j] = base64_chars.find(char_array_4[j]);

    char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
    char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
    char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

    for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
  }

  return ret;
}

base64.h

#include <string>

std::string base64_encode(unsigned char const* , unsigned int len);
std::string base64_decode(std::string const& s);

Usage

const std::string s = "test";
std::string encoded = base64_encode(reinterpret_cast<const unsigned char*>(s.c_str()), s.length());
  std::string decoded = base64_decode(encoded);

What is RSS and VSZ in Linux memory management

Minimal runnable example

For this to make sense, you have to understand the basics of paging: How does x86 paging work? and in particular that the OS can allocate virtual memory via page tables / its internal memory book keeping (VSZ virtual memory) before it actually has a backing storage on RAM or disk (RSS resident memory).

Now to observe this in action, let's create a program that:

  • allocates more RAM than our physical memory with mmap
  • writes one byte on each page to ensure that each of those pages goes from virtual only memory (VSZ) to actually used memory (RSS)
  • checks the memory usage of the process with one of the methods mentioned at: Memory usage of current process in C

main.c

#define _GNU_SOURCE
#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>

typedef struct {
    unsigned long size,resident,share,text,lib,data,dt;
} ProcStatm;

/* https://stackoverflow.com/questions/1558402/memory-usage-of-current-process-in-c/7212248#7212248 */
void ProcStat_init(ProcStatm *result) {
    const char* statm_path = "/proc/self/statm";
    FILE *f = fopen(statm_path, "r");
    if(!f) {
        perror(statm_path);
        abort();
    }
    if(7 != fscanf(
        f,
        "%lu %lu %lu %lu %lu %lu %lu",
        &(result->size),
        &(result->resident),
        &(result->share),
        &(result->text),
        &(result->lib),
        &(result->data),
        &(result->dt)
    )) {
        perror(statm_path);
        abort();
    }
    fclose(f);
}

int main(int argc, char **argv) {
    ProcStatm proc_statm;
    char *base, *p;
    char system_cmd[1024];
    long page_size;
    size_t i, nbytes, print_interval, bytes_since_last_print;
    int snprintf_return;

    /* Decide how many ints to allocate. */
    if (argc < 2) {
        nbytes = 0x10000;
    } else {
        nbytes = strtoull(argv[1], NULL, 0);
    }
    if (argc < 3) {
        print_interval = 0x1000;
    } else {
        print_interval = strtoull(argv[2], NULL, 0);
    }
    page_size = sysconf(_SC_PAGESIZE);

    /* Allocate the memory. */
    base = mmap(
        NULL,
        nbytes,
        PROT_READ | PROT_WRITE,
        MAP_SHARED | MAP_ANONYMOUS,
        -1,
        0
    );
    if (base == MAP_FAILED) {
        perror("mmap");
        exit(EXIT_FAILURE);
    }

    /* Write to all the allocated pages. */
    i = 0;
    p = base;
    bytes_since_last_print = 0;
    /* Produce the ps command that lists only our VSZ and RSS. */
    snprintf_return = snprintf(
        system_cmd,
        sizeof(system_cmd),
        "ps -o pid,vsz,rss | awk '{if (NR == 1 || $1 == \"%ju\") print}'",
        (uintmax_t)getpid()
    );
    assert(snprintf_return >= 0);
    assert((size_t)snprintf_return < sizeof(system_cmd));
    bytes_since_last_print = print_interval;
    do {
        /* Modify a byte in the page. */
        *p = i;
        p += page_size;
        bytes_since_last_print += page_size;
        /* Print process memory usage every print_interval bytes.
         * We count memory using a few techniques from:
         * https://stackoverflow.com/questions/1558402/memory-usage-of-current-process-in-c */
        if (bytes_since_last_print > print_interval) {
            bytes_since_last_print -= print_interval;
            printf("extra_memory_committed %lu KiB\n", (i * page_size) / 1024);
            ProcStat_init(&proc_statm);
            /* Check /proc/self/statm */
            printf(
                "/proc/self/statm size resident %lu %lu KiB\n",
                (proc_statm.size * page_size) / 1024,
                (proc_statm.resident * page_size) / 1024
            );
            /* Check ps. */
            puts(system_cmd);
            system(system_cmd);
            puts("");
        }
        i++;
    } while (p < base + nbytes);

    /* Cleanup. */
    munmap(base, nbytes);
    return EXIT_SUCCESS;
}

GitHub upstream.

Compile and run:

gcc -ggdb3 -O0 -std=c99 -Wall -Wextra -pedantic -o main.out main.c
echo 1 | sudo tee /proc/sys/vm/overcommit_memory
sudo dmesg -c
./main.out 0x1000000000 0x200000000
echo $?
sudo dmesg

where:

  • 0x1000000000 == 64GiB: 2x my computer's physical RAM of 32GiB
  • 0x200000000 == 8GiB: print the memory every 8GiB, so we should get 4 prints before the crash at around 32GiB
  • echo 1 | sudo tee /proc/sys/vm/overcommit_memory: required for Linux to allow us to make a mmap call larger than physical RAM: maximum memory which malloc can allocate

Program output:

extra_memory_committed 0 KiB
/proc/self/statm size resident 67111332 768 KiB
ps -o pid,vsz,rss | awk '{if (NR == 1 || $1 == "29827") print}'
  PID    VSZ   RSS
29827 67111332 1648

extra_memory_committed 8388608 KiB
/proc/self/statm size resident 67111332 8390244 KiB
ps -o pid,vsz,rss | awk '{if (NR == 1 || $1 == "29827") print}'
  PID    VSZ   RSS
29827 67111332 8390256

extra_memory_committed 16777216 KiB
/proc/self/statm size resident 67111332 16778852 KiB
ps -o pid,vsz,rss | awk '{if (NR == 1 || $1 == "29827") print}'
  PID    VSZ   RSS
29827 67111332 16778864

extra_memory_committed 25165824 KiB
/proc/self/statm size resident 67111332 25167460 KiB
ps -o pid,vsz,rss | awk '{if (NR == 1 || $1 == "29827") print}'
  PID    VSZ   RSS
29827 67111332 25167472

Killed

Exit status:

137

which by the 128 + signal number rule means we got signal number 9, which man 7 signal says is SIGKILL, which is sent by the Linux out-of-memory killer.

Output interpretation:

  • VSZ virtual memory remains constant at printf '0x%X\n' 0x40009A4 KiB ~= 64GiB (ps values are in KiB) after the mmap.
  • RSS "real memory usage" increases lazily only as we touch the pages. For example:
    • on the first print, we have extra_memory_committed 0, which means we haven't yet touched any pages. RSS is a small 1648 KiB which has been allocated for normal program startup like text area, globals, etc.
    • on the second print, we have written to 8388608 KiB == 8GiB worth of pages. As a result, RSS increased by exactly 8GIB to 8390256 KiB == 8388608 KiB + 1648 KiB
    • RSS continues to increase in 8GiB increments. The last print shows about 24 GiB of memory, and before 32 GiB could be printed, the OOM killer killed the process

See also: https://unix.stackexchange.com/questions/35129/need-explanation-on-resident-set-size-virtual-size

OOM killer logs

Our dmesg commands have shown the OOM killer logs.

An exact interpretation of those has been asked at:

The very first line of the log was:

[ 7283.479087] mongod invoked oom-killer: gfp_mask=0x6200ca(GFP_HIGHUSER_MOVABLE), order=0, oom_score_adj=0

So we see that interestingly it was the MongoDB daemon that always runs in my laptop on the background that first triggered the OOM killer, presumably when the poor thing was trying to allocate some memory.

However, the OOM killer does not necessarily kill the one who awoke it.

After the invocation, the kernel prints a table or processes including the oom_score:

[ 7283.479292] [  pid  ]   uid  tgid total_vm      rss pgtables_bytes swapents oom_score_adj name
[ 7283.479303] [    496]     0   496    16126        6   172032      484             0 systemd-journal
[ 7283.479306] [    505]     0   505     1309        0    45056       52             0 blkmapd
[ 7283.479309] [    513]     0   513    19757        0    57344       55             0 lvmetad
[ 7283.479312] [    516]     0   516     4681        1    61440      444         -1000 systemd-udevd

and further ahead we see that our own little main.out actually got killed on the previous invocation:

[ 7283.479871] Out of memory: Kill process 15665 (main.out) score 865 or sacrifice child
[ 7283.479879] Killed process 15665 (main.out) total-vm:67111332kB, anon-rss:92kB, file-rss:4kB, shmem-rss:30080832kB
[ 7283.479951] oom_reaper: reaped process 15665 (main.out), now anon-rss:0kB, file-rss:0kB, shmem-rss:30080832kB

This log mentions the score 865 which that process had, presumably the highest (worst) OOM killer score as mentioned at: https://unix.stackexchange.com/questions/153585/how-does-the-oom-killer-decide-which-process-to-kill-first

Also interestingly, everything apparently happened so fast that before the freed memory was accounted, the oom was awoken again by the DeadlineMonitor process:

[ 7283.481043] DeadlineMonitor invoked oom-killer: gfp_mask=0x6200ca(GFP_HIGHUSER_MOVABLE), order=0, oom_score_adj=0

and this time that killed some Chromium process, which is usually my computers normal memory hog:

[ 7283.481773] Out of memory: Kill process 11786 (chromium-browse) score 306 or sacrifice child
[ 7283.481833] Killed process 11786 (chromium-browse) total-vm:1813576kB, anon-rss:208804kB, file-rss:0kB, shmem-rss:8380kB
[ 7283.497847] oom_reaper: reaped process 11786 (chromium-browse), now anon-rss:0kB, file-rss:0kB, shmem-rss:8044kB

Tested in Ubuntu 19.04, Linux kernel 5.0.0.

Use mysql_fetch_array() with foreach() instead of while()

You could just do it like this

$query_select = "SELECT * FROM shouts ORDER BY id DESC LIMIT 8;"; 

$result_select = mysql_query($query_select) or die(mysql_error());

 foreach($result_select as $row){
    $ename = stripslashes($row['name']);
    $eemail = stripcslashes($row['email']);
    $epost = stripslashes($row['post']);
    $eid = $row['id'];

    $grav_url = "http://www.gravatar.com/avatar.php?gravatar_id=".md5(strtolower($eemail))."&size=70";

    echo ('<img src = "' . $grav_url . '" alt="Gravatar">'.'<br/>');

    echo $eid . '<br/>';

    echo $ename . '<br/>';

    echo $eemail . '<br/>';

    echo $epost . '<br/><br/><br/><br/>';
 }

Looping through all the properties of object php

Here is another way to express the object property.

foreach ($obj as $key=>$value) {
    echo "$key => $obj[$key]\n";
}

How to convert HTML file to word?

When doing this I found it easiest to:

  1. Visit the page in a web browser
  2. Save the page using the web browser with .htm extension (and maybe a folder with support files)
  3. Start Word and open the saved htmfile (Word will open it correctly)
  4. Make any edits if needed
  5. Select Save As and then choose the extension you would like doc, docx, etc.

How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds?

In a specific case where your epoch seconds timestamp comes from SQL or is related to SQL somehow, you can obtain it like this:

long startDateLong = <...>

LocalDate theDate = new java.sql.Date(startDateLong).toLocalDate();

SignalR - Sending a message to a specific user using (IUserIdProvider) *NEW 2.0.0*

Look at SignalR Tests for the feature.

Test "SendToUser" takes automatically the user identity passed by using a regular owin authentication library.

The scenario is you have a user who has connected from multiple devices/browsers and you want to push a message to all his active connections.

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

Adding <validation validateIntegratedModeConfiguration="false"/> addresses the symptom, but is not appropriate for all circumstances. Having ran around this issue a few times, I hope to help others not only overcome the problem but understand it. (Which becomes more and more important as IIS 6 fades into myth and rumor.)

Background:

This issue and the confusion surrounding it started with the introduction of ASP.NET 2.0 and IIS 7. IIS 6 had and continues to have only one pipeline mode, and it is equivalent to what IIS 7+ calls "Classic" mode. The second, newer, and recommended pipeline mode for all applications running on IIS 7+ is called "Integrated" mode.

So, what's the difference? The key difference is how ASP.NET interacts with IIS.

  • Classic mode is limited to an ASP.NET pipeline that cannot interact with the IIS pipeline. Essentially a request comes in and if IIS 6/Classic has been told, through server configuration, that ASP.NET can handle it then IIS hands off the request to ASP.NET and moves on. The significance of this can be gleaned from an example. If I were to authorize access to static image files, I would not be able to do it with an ASP.NET module because the IIS 6 pipeline will handle those requests itself and ASP.NET will never see those requests because they were never handed off.* On the other hand, authorizing which users can access a .ASPX page such as a request for Foo.aspx is trivial even in IIS 6/Classic because IIS always hands those requests off to the ASP.NET pipeline. In Classic mode ASP.NET does not know what it hasn't been told and there is a lot that IIS 6/Classic may not be telling it.

  • Integrated mode is recommended because ASP.NET handlers and modules can interact directly with the IIS pipeline. No longer does the IIS pipeline simply hand off the request to the ASP.NET pipeline, now it allows ASP.NET code to hook directly into the IIS pipeline and all the requests that hit it. This means that an ASP.NET module can not only observe requests to static image files, but can intercept those requests and take action by denying access, logging the request, etc.

Overcoming the error:

  1. If you are running an older application that was originally built for IIS 6, perhaps you moved it to a new server, there may be absolutely nothing wrong with running the application pool of that application in Classic mode. Go ahead you don't have to feel bad.
  2. Then again maybe you are giving your application a face-lift or it was chugging along just fine until you installed a 3rd party library via NuGet, manually, or by some other means. In that case it is entirely possible httpHandlers or httpModules have been added to system.web. The outcome is the error that you are seeing because validateIntegratedModeConfiguration defaults true. Now you have two choices:

    1. Remove the httpHandlers and httpModules elements from system.web. There are a couple possible outcomes from this:
      • Everything works fine, a common outcome;
      • Your application continues to complain, there may be a web.config in a parent folder you are inheriting from, consider cleaning up that web.config too;
      • You grow tired of removing the httpHandlers and httpModules that NuGet packages keep adding to system.web, hey do what you need to.
  3. If those options do not work or are more trouble than it is worth then I'm not going to tell you that you can't set validateIntegratedModeConfiguration to false, but at least you know what you're doing and why it matters.

Good reads:

*Of course there are ways to get all kind of strange things into the ASP.NET pipeline from IIS 6/Classic via incantations like wildcard mappings, if you like that sort of thing.

mysqli or PDO - what are the pros and cons?

In my benchmark script, each method is tested 10000 times and the difference of the total time for each method is printed. You should this on your own configuration, I'm sure results will vary!

These are my results:

  • "SELECT NULL" -> PGO() faster by ~ 0.35 seconds
  • "SHOW TABLE STATUS" -> mysqli() faster by ~ 2.3 seconds
  • "SELECT * FROM users" -> mysqli() faster by ~ 33 seconds

Note: by using ->fetch_row() for mysqli, the column names are not added to the array, I didn't find a way to do that in PGO. But even if I use ->fetch_array() , mysqli is slightly slower but still faster than PGO (except for SELECT NULL).

Initialize Array of Objects using NSArray

NSMutableArray *persons = [NSMutableArray array];
for (int i = 0; i < myPersonsCount; i++) {
   [persons addObject:[[Person alloc] init]];
}
NSArray *arrayOfPersons = [NSArray arrayWithArray:persons]; // if you want immutable array

also you can reach this without using NSMutableArray:

NSArray *persons = [NSArray array];
for (int i = 0; i < myPersonsCount; i++) {
   persons = [persons arrayByAddingObject:[[Person alloc] init]];
}

One more thing - it's valid for ARC enabled environment, if you going to use it without ARC don't forget to add autoreleased objects into array!

[persons addObject:[[[Person alloc] init] autorelease];

How to order citations by appearance using BibTeX?

There are three good answers to this question.

  • Use the unsrt bibliography style, if you're happy with its formatting otherwise
  • Use the makebst (link) tool to design your own bibliography style

And my personal recommendation:

  • Use the biblatex package (link). It's the most complete and flexible bibliography tool in the LaTeX world.

Using biblatex, you'd write something like

\documentclass[12pt]{article}
\usepackage[sorting=none]{biblatex}
\bibliography{journals,phd-references} % Where journals.bib and phd-references.bib are BibTeX databases
\begin{document}
\cite{robertson2007}
\cite{earnshaw1842}
\printbibliography
\end{document}

Progress during large file copy (Copy-Item & Write-Progress?)

I amended the code from stej (which was great, just what i needed!) to use larger buffer, [long] for larger files and used System.Diagnostics.Stopwatch class to track elapsed time and estimate time remaining.

Also added reporting of transfer rate during transfer and outputting overall elapsed time and overall transfer rate.

Using 4MB (4096*1024 bytes) buffer to get better than Win7 native throughput copying from NAS to USB stick on laptop over wifi.

On To-Do list:

  • add error handling (catch)
  • handle get-childitem file list as input
  • nested progress bars when copying multiple files (file x of y, % if total data copied etc)
  • input parameter for buffer size

Feel free to use/improve :-)

function Copy-File {
param( [string]$from, [string]$to)
$ffile = [io.file]::OpenRead($from)
$tofile = [io.file]::OpenWrite($to)
Write-Progress `
    -Activity "Copying file" `
    -status ($from.Split("\")|select -last 1) `
    -PercentComplete 0
try {
    $sw = [System.Diagnostics.Stopwatch]::StartNew();
    [byte[]]$buff = new-object byte[] (4096*1024)
    [long]$total = [long]$count = 0
    do {
        $count = $ffile.Read($buff, 0, $buff.Length)
        $tofile.Write($buff, 0, $count)
        $total += $count
        [int]$pctcomp = ([int]($total/$ffile.Length* 100));
        [int]$secselapsed = [int]($sw.elapsedmilliseconds.ToString())/1000;
        if ( $secselapsed -ne 0 ) {
            [single]$xferrate = (($total/$secselapsed)/1mb);
        } else {
            [single]$xferrate = 0.0
        }
        if ($total % 1mb -eq 0) {
            if($pctcomp -gt 0)`
                {[int]$secsleft = ((($secselapsed/$pctcomp)* 100)-$secselapsed);
                } else {
                [int]$secsleft = 0};
            Write-Progress `
                -Activity ($pctcomp.ToString() + "% Copying file @ " + "{0:n2}" -f $xferrate + " MB/s")`
                -status ($from.Split("\")|select -last 1) `
                -PercentComplete $pctcomp `
                -SecondsRemaining $secsleft;
        }
    } while ($count -gt 0)
$sw.Stop();
$sw.Reset();
}
finally {
    write-host (($from.Split("\")|select -last 1) + `
     " copied in " + $secselapsed + " seconds at " + `
     "{0:n2}" -f [int](($ffile.length/$secselapsed)/1mb) + " MB/s.");
     $ffile.Close();
     $tofile.Close();
    }
}

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

go to http://dev.mysql.com/downloads/connector/c/ and download MySQL Connector/C. after getting the package, make a new directory 'mysql', uncompress the Mysql Connector file under directory mysql, then under mysql, make another empty directory 'build'.we will use 'build' to build MySQL Connector/C. cd build && cmake ../your-MySQL-Connector-source-dir make && make install after make install, you will get a directory named mysql under /usr/local. it contains all the headers and libs you need.go to this dirctory, and copy the headers and libs to corresponding locations.

How to make a Java thread wait for another thread's output?

Try CountDownLatch class out of the java.util.concurrent package, which provides higher level synchronization mechanisms, that are far less error prone than any of the low level stuff.

Get cookie by name

You can use js-cookie library to get and set JavaScript cookies.

Include to your HTML:

<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>

To create a Cookie:

Cookies.set('name', 'value');

To read a Cookie:

Cookies.get('name'); // => 'value'

How to access cookies in AngularJS?

Angular deprecated $cookieStore in version 1.4.x, so use $cookies instead if you are using latest version of angular. Syntax remain same for $cookieStore & $cookies:

$cookies.put("key", "value"); 
var value = $cookies.get("key");

See the Docs for an API overview. Mind also that the cookie service has been enhanced with some new important features like setting expiration (see this answer) and domain (see CookiesProvider Docs).

Note that, in version 1.3.x or below, $cookies has a different syntax than above:

$cookies.key = "value";
var value = $cookies.value; 

Also if you are using bower, make sure to type your package name correctly:

bower install [email protected] 

where X.Y.Z is the AngularJS version you are running. There's another package in bower "angular-cookie"(without the 's') which is not the official angular package.

How do you use MySQL's source command to import large files in windows

C:\xampp\mysql\bin\mysql -u root -p testdatabase < C:\Users\Juan\Desktop\databasebackup.sql

That worked for me to import 400MB file into my database.

Create parameterized VIEW in SQL Server 2008

As astander has mentioned, you can do that with a UDF. However, for large sets using a scalar function (as oppoosed to a inline-table function) the performance will stink as the function is evaluated row-by-row. As an alternative, you could expose the same results via a stored procedure executing a fixed query with placeholders which substitutes in your parameter values.

(Here's a somewhat dated but still relevant article on row-by-row processing for scalar UDFs.)

Edit: comments re. degrading performance adjusted to make it clear this applies to scalar UDFs.

Converting Epoch time into the datetime

If you have epoch in milliseconds a possible solution is convert to seconds:

import time
time.ctime(milliseconds/1000)

For more time functions: https://docs.python.org/3/library/time.html#functions

How to copy a dictionary and only edit the copy

The best and the easiest ways to create a copy of a dict in both Python 2.7 and 3 are...

To create a copy of simple(single-level) dictionary:

1. Using dict() method, instead of generating a reference that points to the existing dict.

my_dict1 = dict()
my_dict1["message"] = "Hello Python"
print(my_dict1)  # {'message':'Hello Python'}

my_dict2 = dict(my_dict1)
print(my_dict2)  # {'message':'Hello Python'}

# Made changes in my_dict1 
my_dict1["name"] = "Emrit"
print(my_dict1)  # {'message':'Hello Python', 'name' : 'Emrit'}
print(my_dict2)  # {'message':'Hello Python'}

2. Using the built-in update() method of python dictionary.

my_dict2 = dict()
my_dict2.update(my_dict1)
print(my_dict2)  # {'message':'Hello Python'}

# Made changes in my_dict1 
my_dict1["name"] = "Emrit"
print(my_dict1)  # {'message':'Hello Python', 'name' : 'Emrit'}
print(my_dict2)  # {'message':'Hello Python'}

To create a copy of nested or complex dictionary:

Use the built-in copy module, which provides a generic shallow and deep copy operations. This module is present in both Python 2.7 and 3.*

import copy

my_dict2 = copy.deepcopy(my_dict1)

OperationalError, no such column. Django

Deleting all your migrations in the migration folder of your django app, then run makemigrations followed by migrate commands. You should be able to get out of the woods.

Collection that allows only unique items in .NET?

From the HashSet<T> page on MSDN:

The HashSet(Of T) class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.

(emphasis mine)

How to retrieve SQL result column value using column name in Python?

Of course there is. In Python 2.7.2+...

import MySQLdb as mdb
con =  mdb.connect('localhost', 'user', 'password', 'db');
cur = con.cursor()
cur.execute('SELECT Foo, Bar FROM Table')
for i in range(int(cur.numrows)):
    foo, bar = cur.fetchone()
    print 'foo = %s' % foo
    print 'bar = %s' % bar

close vs shutdown socket?

I've also had success under linux using shutdown() from one pthread to force another pthread currently blocked in connect() to abort early.

Under other OSes (OSX at least), I found calling close() was enough to get connect() fail.

Is there a way to pass optional parameters to a function?

If you want give some default value to a parameter assign value in (). like (x =10). But important is first should compulsory argument then default value.

eg.

(y, x =10)

but

(x=10, y) is wrong

VBA setting the formula for a cell

Not sure what isn't working in your case, but the following code will put a formula into cell A1 that will retrieve the value in the cell G2.

strProjectName = "Sheet1"
Cells(1, 1).Formula = "=" & strProjectName & "!" & Cells(2, 7).Address

The workbook and worksheet that strProjectName references must exist at the time that this formula is placed. Excel will immediately try to evaluate the formula. You might be able to stop that from happening by turning off automatic recalculation until the workbook does exist.

How to play YouTube video in my Android application?

Google has a YouTube Android Player API that enables you to incorporate video playback functionality into your Android applications. The API itself is very easy to use and works well. For example, here is how to create a new activity to play a video using the API.

Intent intent = YouTubeStandalonePlayer.createVideoIntent(this, "<<YOUTUBE_API_KEY>>", "<<Youtube Video ID>>", 0, true, false);   
startActivity(intent);

See this for more details.

Passing an array using an HTML form hidden element

You can do it like this:

<input type="hidden" name="result" value="<?php foreach($postvalue as $value) echo $postvalue.","; ?>">

How to validate IP address in Python?

import socket

def is_valid_ipv4_address(address):
    try:
        socket.inet_pton(socket.AF_INET, address)
    except AttributeError:  # no inet_pton here, sorry
        try:
            socket.inet_aton(address)
        except socket.error:
            return False
        return address.count('.') == 3
    except socket.error:  # not a valid address
        return False

    return True

def is_valid_ipv6_address(address):
    try:
        socket.inet_pton(socket.AF_INET6, address)
    except socket.error:  # not a valid address
        return False
    return True

Where to find "Microsoft.VisualStudio.TestTools.UnitTesting" missing dll?

I.e. for Visual Studio 2013 I would reference this assembly:

Microsoft.VisualStudio.Shell.14.0.dll

You can find it i.e. here:

C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\BugAid Software\BugAid\1.0

and don't forget to implement:

using Microsoft.VisualStudio;

Why there is this "clear" class before footer?

A class in HTML means that in order to set attributes to it in CSS, you simply need to add a period in front of it.
For example, the CSS code of that html code may be:

.clear {     height: 50px;     width: 25px; } 

Also, if you, as suggested by abiessu, are attempting to add the CSS clear: both; attribute to the div to prevent anything from floating to the left or right of this div, you can use this CSS code:

.clear {     clear: both; } 

pip: no module named _internal

An answer from askUbuntu works.

For pip2.7, you can at first curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py, then python2.7 get-pip.py --force-reinstall to reinstall pip.

Problem solved. Also works for python3.

<modules runAllManagedModulesForAllRequests="true" /> Meaning

Modules Preconditions:

The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (precondition="managedHandler") only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:

<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />

If you remove the attribute precondition="managedHandler", Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.

You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "managedHandler" precondition.

To enable all managed modules to run for all requests without configuring each module entry to remove the "managedHandler" precondition, use the runAllManagedModulesForAllRequests property in the <modules> section:

<modules runAllManagedModulesForAllRequests="true" />    

When you use this property, the "managedHandler" precondition has no effect and all managed modules run for all requests.

Copied from IIS Modules Overview: Preconditions

Check synchronously if file/directory exists in Node.js

Here is a simple wrapper solution for this:

var fs = require('fs')
function getFileRealPath(s){
    try {return fs.realpathSync(s);} catch(e){return false;}
}

Usage:

  • Works for both directories and files
  • If item exists, it returns the path to the file or directory
  • If item does not exist, it returns false

Example:

var realPath,pathToCheck='<your_dir_or_file>'
if( (realPath=getFileRealPath(pathToCheck)) === false){
    console.log('file/dir not found: '+pathToCheck);
} else {
    console.log('file/dir exists: '+realPath);
}

Make sure you use === operator to test if return equals false. There is no logical reason that fs.realpathSync() would return false under proper working conditions so I think this should work 100%.

I would prefer to see a solution that does not does not generate an Error and resulting performance hit. From an API perspective, fs.exists() seems like the most elegant solution.

Converting array to list in Java

So it depends on which Java version you are trying-

Java 7

 Arrays.asList(1, 2, 3);

OR

       final String arr[] = new String[] { "G", "E", "E", "K" };
       final List<String> initialList = new ArrayList<String>() {{
           add("C");
           add("O");
           add("D");
           add("I");
           add("N");
       }};

       // Elements of the array are appended at the end
       Collections.addAll(initialList, arr);

OR

Integer[] arr = new Integer[] { 1, 2, 3 };
Arrays.asList(arr);

In Java 8

int[] num = new int[] {1, 2, 3};
List<Integer> list = Arrays.stream(num)
                        .boxed().collect(Collectors.<Integer>toList())

Reference - http://www.codingeek.com/java/how-to-convert-array-to-list-in-java/

In Python, how to display current time in readable format

First the quick and dirty way, and second the precise way (recognizing daylight's savings or not).

import time
time.ctime() # 'Mon Oct 18 13:35:29 2010'
time.strftime('%l:%M%p %Z on %b %d, %Y') # ' 1:36PM EDT on Oct 18, 2010'
time.strftime('%l:%M%p %z on %b %d, %Y') # ' 1:36PM EST on Oct 18, 2010'

C library function to perform sort

While not in the standard library exactly, https://github.com/swenson/sort has just two header files you can include to get access to a wide range of incredibly fast sorting routings, like so:

#define SORT_NAME int64
#define SORT_TYPE int64_t
#define SORT_CMP(x, y) ((x) - (y))
#include "sort.h"
/* You now have access to int64_quick_sort, int64_tim_sort, etc., e.g., */
int64_quick_sort(arr, 128); /* Assumes you have some int *arr or int arr[128]; */

This should be at least twice as fast as the standard library qsort, since it doesn't use function pointers, and has many other sorting algorithm options to choose from.

It's in C89, so should work in basically every C compiler.

Enabling error display in PHP via htaccess only

I feel like adding more details to the existing answer:

# PHP error handling for development servers
php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag log_errors on
php_flag ignore_repeated_errors off
php_flag ignore_repeated_source off
php_flag report_memleaks on
php_flag track_errors on
php_value docref_root 0
php_value docref_ext 0
php_value error_log /full/path/to/file/php_errors.log
php_value error_reporting -1
php_value log_errors_max_len 0

Give 777 or 755 permission to the log file and then add the code

<Files php_errors.log>
     Order allow,deny
     Deny from all
     Satisfy All
</Files>

at the end of .htaccess. This will protect your log file.

These options are suited for a development server. For a production server you should not display any error to the end user. So change the display flags to off.

For more information, follow this link: Advanced PHP Error Handling via htaccess

jQuery textbox change event doesn't fire until textbox loses focus?

On modern browsers, you can use the input event:

DEMO

$("#textbox").on('input',function() {alert("Change detected!");});

Spark DataFrame groupBy and sort in the descending order (pyspark)

By far the most convenient way is using this:

df.orderBy(df.column_name.desc())

Doesn't require special imports.

What does "Could not find or load main class" mean?

Right click the project.

  1. Select "Open module settings"
  2. Mark the src folder as "sources"
  3. Go to edit configurations, and then select your main class
  4. Click OK or the Apply button

This worked for me.

Retrieve specific commit from a remote Git repository

This works best:

git fetch origin specific_commit
git checkout -b temp FETCH_HEAD

name "temp" whatever you want...this branch might be orphaned though

How do I embed a mp4 movie into my html?

Most likely the TinyMce editor is adding its own formatting to the post. You'll need to see how you can escape TinyMce's editing abilities. The code works fine for me. Is it a wordpress blog?

getDate with Jquery Datepicker

I think you would want to add an 'onSelect' event handler to the initialization of your datepicker so your code gets triggered when the user selects a date. Try it out on jsFiddle

$(document).ready(function(){
    // Datepicker
    $('#datepicker').datepicker({
        dateFormat: 'yy-mm-dd',
        inline: true,
        minDate: new Date(2010, 1 - 1, 1),
        maxDate:new Date(2010, 12 - 1, 31),
        altField: '#datepicker_value',
        onSelect: function(){
            var day1 = $("#datepicker").datepicker('getDate').getDate();                 
            var month1 = $("#datepicker").datepicker('getDate').getMonth() + 1;             
            var year1 = $("#datepicker").datepicker('getDate').getFullYear();
            var fullDate = year1 + "-" + month1 + "-" + day1;
            var str_output = "<h1><center><img src=\"/images/a" + fullDate +".png\"></center></h1><br/><br>";
            $('#page_output').html(str_output);
        }
    });
});

How to resize an image with OpenCV2.0 and Python2.6

If you wish to use CV2, you need to use the resize function.

For example, this will resize both axes by half:

small = cv2.resize(image, (0,0), fx=0.5, fy=0.5) 

and this will resize the image to have 100 cols (width) and 50 rows (height):

resized_image = cv2.resize(image, (100, 50)) 

Another option is to use scipy module, by using:

small = scipy.misc.imresize(image, 0.5)

There are obviously more options you can read in the documentation of those functions (cv2.resize, scipy.misc.imresize).


Update:
According to the SciPy documentation:

imresize is deprecated in SciPy 1.0.0, and will be removed in 1.2.0.
Use skimage.transform.resize instead.

Note that if you're looking to resize by a factor, you may actually want skimage.transform.rescale.

Could not commit JPA transaction: Transaction marked as rollbackOnly

As explained @Yaroslav Stavnichiy if a service is marked as transactional spring tries to handle transaction itself. If any exception occurs then a rollback operation performed. If in your scenario ServiceUser.method() is not performing any transactional operation you can use @Transactional.TxType annotation. 'NEVER' option is used to manage that method outside transactional context.

Transactional.TxType reference doc is here.

Developing C# on Linux

This is an old question but it has a high view count, so I think some new information should be added: In the mean time a lot has changed, and you can now also use Microsoft's own .NET Core on linux. It's also available in ARM builds, 32 and 64 bit.

How to apply CSS to iframe?

Other answers here seem to use jQuery and CSS links.

This code uses vanilla JavaScript. It creates a new <style> element. It sets the text content of that element to be a string containing the new CSS. And it appends that element directly to the iframe document's head.

var iframe = document.getElementById('the-iframe');
var style = document.createElement('style');
style.textContent =
  '.some-class-name {' +
  '  some-style-name: some-value;' +
  '}' 
;
iframe.contentDocument.head.appendChild(style);

ng is not recognized as an internal or external command

If you get the error even after following the above step. then try below.

Since it is a node script. I am using the below option to create as of now.

node C:\Users\Administrator\AppData\Roaming\npm\node_modules\angular-cli\bin\ng version

May be symbolic links are required. Not researched further.

On Further Research: Set Path as : %PATH%;C:\Users\Administrator\AppData\Roaming\npm;

In Windows, npm.cmd file is in the above path. If the above Environment variable is set, you can execute as ng version ng init

How to run a PowerShell script

  • Give the path of the script, that is, path setting by cmd:

    $> . c:\program file\prog.ps1

  • Run the entry point function of PowerShell:

    For example, $> add or entry_func or main

How do I specify the JDK for a GlassFish domain?

Here you can find how to set path to JDK for Glassfish: http://www.devdaily.com/blog/post/java/fixing-glassfish-jdk-path-problem-solved

Check

glassfish\config\asenv.bat

where java path is configured

REM set AS_JAVA=C:\Program Files\Java\jdk1.6.0_04\jre/..
set AS_JAVA=C:\Program Files\Java\jdk1.5.0_16

php var_dump() vs print_r()

If you're asking when you should use what, I generally use print_r() for displaying values and var_dump() for when having issues with variable types.

The EXECUTE permission was denied on the object 'xxxxxxx', database 'zzzzzzz', schema 'dbo'

The general answer is to grant execute permission as explained above. But that doesn't work if the schema owner of SP is different to underlying objects.

Check schema owners by:

select name, USER_NAME(s.principal_id) AS Schema_Owner from sys.schemas s

To change the owner of an schema you can:

ALTER AUTHORIZATION ON SCHEMA::YOUR_SCHEMA TO YOUR_USER;

Examples:

ALTER AUTHORIZATION ON SCHEMA::Claim TO dbo
ALTER AUTHORIZATION ON SCHEMA::datix TO user1;

Finally if within your SP you are truncating a table or changing structure you may want to add WITH EXECUTE AS OWNER in your SP:

ALTER procedure [myProcedure] 
WITH EXECUTE AS OWNER

as

truncate table etl.temp

PHP validation/regex for URL

Here's a simple class for URL Validation using RegEx and then cross-references the domain against popular RBL (Realtime Blackhole Lists) servers:

Install:

require 'URLValidation.php';

Usage:

require 'URLValidation.php';
$urlVal = new UrlValidation(); //Create Object Instance

Add a URL as the parameter of the domain() method and check the the return.

$urlArray = ['http://www.bokranzr.com/test.php?test=foo&test=dfdf', 'https://en-gb.facebook.com', 'https://www.google.com'];
foreach ($urlArray as $k=>$v) {

    echo var_dump($urlVal->domain($v)) . ' URL: ' . $v . '<br>';

}

Output:

bool(false) URL: http://www.bokranzr.com/test.php?test=foo&test=dfdf
bool(true) URL: https://en-gb.facebook.com
bool(true) URL: https://www.google.com

As you can see above, www.bokranzr.com is listed as malicious website via an RBL so the domain was returned as false.

database attached is read only

First make sure that the folder in which your .mdf file resides is not read only. If it is, un-check that option and make sure it reflects to folders and files within that folder.

Once that is done, Open Management Studio, in the Object Explorer right click on the Database which is read only and select Properties. In the Options Menu, check that the Read-Only property is false.

enter image description here

jQuery hasAttr checking to see if there is an attribute on an element

I wrote a hasAttr() plugin for jquery that will do all of this very simply, exactly as the OP has requested. More information here

EDIT: My plugin was deleted in the great plugins.jquery.com database deletion disaster of 2010. You can look here for some info on adding it yourself, and why it hasn't been added.

Command line: search and replace in all filenames matched by grep

Do you mean search and replace a string in all files matched by grep?

perl -p -i -e 's/oldstring/newstring/g' `grep -ril searchpattern *`

Edit

Since this seems to be a fairly popular question thought I'd update.

Nowadays I mostly use ack-grep as it's more user-friendly. So the above command would be:

perl -p -i -e 's/old/new/g' `ack -l searchpattern`

To handle whitespace in file names you can run:

ack --print0 -l searchpattern | xargs -0 perl -p -i -e 's/old/new/g'

you can do more with ack-grep. Say you want to restrict the search to HTML files only:

ack --print0 --html -l searchpattern | xargs -0 perl -p -i -e 's/old/new/g'

And if white space is not an issue it's even shorter:

perl -p -i -e 's/old/new/g' `ack -l --html searchpattern`
perl -p -i -e 's/old/new/g' `ack -f --html` # will match all html files

Reading file using relative path in python project

For Python 3.4+:

import csv
from pathlib import Path

base_path = Path(__file__).parent
file_path = (base_path / "../data/test.csv").resolve()

with open(file_path) as f:
    test = [line for line in csv.reader(f)]

How to fire a change event on a HTMLSelectElement if the new value is the same as the old?

I'd do it like this:

<select onchange="jsFunction()">
  <option value="" disabled selected style="display:none;">Label</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

If you want you could have the same label as the first option, which in this case is 1. Even better: put a label in there for the choices in the box.

Connecting to a network folder with username/password in Powershell

At first glance one really wants to use New-PSDrive supplying it credentials.

> New-PSDrive -Name P -PSProvider FileSystem -Root \\server\share -Credential domain\user

Fails!

New-PSDrive : Cannot retrieve the dynamic parameters for the cmdlet. Dynamic parameters for NewDrive cannot be retrieved for the 'FileSystem' provider. The provider does not support the use of credentials. Please perform the operation again without specifying credentials.

The documentation states that you can provide a PSCredential object but if you look closer the cmdlet does not support this yet. Maybe in the next version I guess.

Therefore you can either use net use or the WScript.Network object, calling the MapNetworkDrive function:

$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive("u:", "\\server\share", $false, "domain\user", "password")

Edit for New-PSDrive in PowerShell 3.0

Apparently with newer versions of PowerShell, the New-PSDrive cmdlet works to map network shares with credentials!

New-PSDrive -Name P -PSProvider FileSystem -Root \\Server01\Public -Credential user\domain -Persist

Using OR & AND in COUNTIFS

You could just add a few COUNTIF statements together:

=COUNTIF(A1:A196,"yes")+COUNTIF(A1:A196,"no")+COUNTIF(J1:J196,"agree")

This will give you the result you need.

EDIT

Sorry, misread the question. Nicholas is right that the above will double count. I wasn't thinking of the AND condition the right way. Here's an alternative that should give you the correct results, which you were pretty close to in the first place:

=SUM(COUNTIFS(A1:A196,{"yes","no"},J1:J196,"agree"))

How do I call an Angular 2 pipe with multiple arguments?

Extended from : user3777549

Multi-value filter on one set of data(reference to title key only)

HTML

<div *ngFor='let item of items | filtermulti: [{title:["mr","ms"]},{first:["john"]}]' >
 Hello {{item.first}} !
</div>

filterMultiple

args.forEach(function (filterobj) {
    console.log(filterobj)
    let filterkey = Object.keys(filterobj)[0];
    let filtervalue = filterobj[filterkey];
    myobjects.forEach(function (objectToFilter) {

      if (!filtervalue.some(x=>x==objectToFilter[filterkey]) && filtervalue != "") {
        // object didn't match a filter value so remove it from array via filter
        returnobjects = returnobjects.filter(obj => obj !== objectToFilter);
      }
    })
  });

IIS - 401.3 - Unauthorized

TL;DR;

In most cases, granting access to the following account(s) (one|both) will be enough:

  1. IIS AppPool\DefaultAppPool
  2. IUSR

with Access Rights:

  1. Read & Execute
  2. List folder contents
  3. Read

That's it!

Read on for a more detailed explanation...


  1. Open IIS and select your application.
  2. On the right side click on Authentication.
  3. Select "Anonymous authentication" here.
  4. The following dialog pops up.

enter image description here

Grant access to the web application folder's ACL depending what is selected in the pic above:

  • Specific user: grant access for both IUSR (in my case) + IIS AppPool\DefaultAppPool
  • Application pool identity: grant access for IIS AppPool\DefaultAppPool only

IIS AppPool\DefaultAppPool account is the default AppPool account for new IIS web applications, if you have set a custom account, use the custom one.


Give the following permissions to the account(s):

  1. Read & Execute
  2. List folder contents
  3. Read

enter image description here

Setting up enviromental variables in Windows 10 to use java and javac

if you have any version problems (javac -version=15.0.1, java -version=1.8.0)
windows search : edit environment variables for your account
then delete these in your windows Environment variable: system variable: Path
C:\Program Files (x86)\Common Files\Oracle\Java\javapath
C:\Program Files\Common Files\Oracle\Java\javapath

then if you're using java 15
environment variable: system variable : Path
add path C:\Program Files\Java\jdk-15.0.1\bin
is enough

if you're using java 8

  • create JAVA_HOME
  • environment variable: system variable : JAVA_HOME
    JAVA_HOME = C:\Program Files\Java\jdk1.8.0_271
  • environment variable: system variable : Path
    add path = %JAVA_HOME%\bin
  • Copy files from one directory into an existing directory

    Assuming t1 is the folder with files in it, and t2 is the empty directory. What you want is something like this:

    sudo cp -R t1/* t2/
    

    Bear in mind, for the first example, t1 and t2 have to be the full paths, or relative paths (based on where you are). If you want, you can navigate to the empty folder (t2) and do this:

    sudo cp -R t1/* ./
    

    Or you can navigate to the folder with files (t1) and do this:

    sudo cp -R ./* t2/
    

    Note: The * sign (or wildcard) stands for all files and folders. The -R flag means recursively (everything inside everything).

    What is the regex for "Any positive integer, excluding 0"

    ^[1-9]*$ is the simplest I can think of

    Comparing two strings in C?

    The name of the array indicates the starting address. Starting address of both namet2 and nameIt2 are different. So the equal to (==) operator checks whether the addresses are the same or not. For comparing two strings, a better way is to use strcmp(), or we can compare character by character using a loop.

    How do I serialize a Python dictionary into a string, and then back to a dictionary?

    Use Python's json module, or simplejson if you don't have python 2.6 or higher.

    Add A Year To Today's Date

    One liner as suggested here

    How to determine one year from now in Javascript by JP DeVries

    new Date(new Date().setFullYear(new Date().getFullYear() + 1))
    

    Or you can get the number of years from somewhere in a variable:

    const nr_years = 3;
    new Date(new Date().setFullYear(new Date().getFullYear() + nr_years))
    

    How to concatenate variables into SQL strings

    You could make use of Prepared Stements like this.

    set @query = concat( "select name from " );
    set @query = concat( "table_name"," [where condition] " );
    
    prepare stmt from @like_q;
    execute stmt;
    

    How to set custom location for local installation of npm package?

    TL;DR

    You can do this by using the --prefix flag and the --global* flag.

    pje@friendbear:~/foo $ npm install bower -g --prefix ./vendor/node_modules
    [email protected] /Users/pje/foo/vendor/node_modules/bower
    

    *Even though this is a "global" installation, installed bins won't be accessible through the command line unless ~/foo/vendor/node_modules exists in PATH.

    TL;DR

    Every configurable attribute of npm can be set in any of six different places. In order of priority:

    • Command-Line Flags: --prefix ./vendor/node_modules
    • Environment Variables: NPM_CONFIG_PREFIX=./vendor/node_modules
    • User Config File: $HOME/.npmrc or userconfig param
    • Global Config File: $PREFIX/etc/npmrc or userconfig param
    • Built-In Config File: path/to/npm/itself/npmrc
    • Default Config: node_modules/npmconf/config-defs.js

    By default, locally-installed packages go into ./node_modules. global ones go into the prefix config variable (/usr/local by default).

    You can run npm config list to see your current config and npm config edit to change it.

    PS

    In general, npm's documentation is really helpful. The folders section is a good structural overview of npm and the config section answers this question.

    How does Facebook disable the browser's integrated Developer Tools?

    Internally devtools injects an IIFE named getCompletions into the page, called when a key is pressed inside the Devtools console.

    Looking at the source of that function, it uses a few global functions which can be overwritten.

    By using the Error constructor it's possible to get the call stack, which will include getCompletions when called by Devtools.


    Example:

    _x000D_
    _x000D_
    const disableDevtools = callback => {_x000D_
      const original = Object.getPrototypeOf;_x000D_
    _x000D_
      Object.getPrototypeOf = (...args) => {_x000D_
        if (Error().stack.includes("getCompletions")) callback();_x000D_
        return original(...args);_x000D_
      };_x000D_
    };_x000D_
    _x000D_
    disableDevtools(() => {_x000D_
      console.error("devtools has been disabled");_x000D_
    _x000D_
      while (1);_x000D_
    });
    _x000D_
    _x000D_
    _x000D_

    Pandas: ValueError: cannot convert float NaN to integer

    For identifying NaN values use boolean indexing:

    print(df[df['x'].isnull()])
    

    Then for removing all non-numeric values use to_numeric with parameter errors='coerce' - to replace non-numeric values to NaNs:

    df['x'] = pd.to_numeric(df['x'], errors='coerce')
    

    And for remove all rows with NaNs in column x use dropna:

    df = df.dropna(subset=['x'])
    

    Last convert values to ints:

    df['x'] = df['x'].astype(int)
    

    How do SETLOCAL and ENABLEDELAYEDEXPANSION work?

    A real problem often exists because any variables set inside will not be exported when that batch file finishes. So its not possible to export, which caused us issues. As a result, I just set the registry to ALWAYS used delayed expansion (I don't know why it's not the default, could be speed or legacy compatibility issue.)

    Google Maps API v3 marker with label

    I can't guarantee it's the simplest, but I like MarkerWithLabel. As shown in the basic example, CSS styles define the label's appearance and options in the JavaScript define the content and placement.

     .labels {
       color: red;
       background-color: white;
       font-family: "Lucida Grande", "Arial", sans-serif;
       font-size: 10px;
       font-weight: bold;
       text-align: center;
       width: 60px;     
       border: 2px solid black;
       white-space: nowrap;
     }
    

    JavaScript:

     var marker = new MarkerWithLabel({
       position: homeLatLng,
       draggable: true,
       map: map,
       labelContent: "$425K",
       labelAnchor: new google.maps.Point(22, 0),
       labelClass: "labels", // the CSS class for the label
       labelStyle: {opacity: 0.75}
     });
    

    The only part that may be confusing is the labelAnchor. By default, the label's top left corner will line up to the marker pushpin's endpoint. Setting the labelAnchor's x-value to half the width defined in the CSS width property will center the label. You can make the label float above the marker pushpin with an anchor point like new google.maps.Point(22, 50).

    In case access to the links above are blocked, I copied and pasted the packed source of MarkerWithLabel into this JSFiddle demo. I hope JSFiddle is allowed in China :|

    CSS: auto height on containing div, 100% height on background div inside containing div

    Make #container to display:inline-block

    #container {
      height: auto;
      width: 100%;
      display: inline-block;
    }
    
    #content {
      height: auto;
      width: 500px;
      margin-left: auto;
      margin-right: auto;
    }
    
    #backgroundContainer {
      height: 200px; /*200px is example, change to what you want*/
      width: 100%;
    }
    

    Also see: W3Schools

    Get column index from label in a data frame

    Use t function:

    t(colnames(df))
    
         [,1]   [,2]   [,3]   [,4]   [,5]   [,6]  
    [1,] "var1" "var2" "var3" "var4" "var5" "var6"
    

    How to read line by line of a text area HTML tag

    A simple regex should be efficent to check your textarea:

    /\s*\d+\s*\n/g.test(text) ? "OK" : "KO"
    

    Checking for #N/A in Excel cell from VBA code

    First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.

    If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
      If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
        'do something
      End If
    End If
    

    Linq select objects in list where exists IN (A,B,C)

    Try with Contains function;

    Determines whether a sequence contains a specified element.

    var allowedStatus = new[]{ "A", "B", "C" };
    var filteredOrders = orders.Order.Where(o => allowedStatus.Contains(o.StatusCode));
    

    Accessing post variables using Java Servlets

    For getting all post parameters there is Map which contains request param name as key and param value as key.

    Map params = servReq.getParameterMap();
    

    And to get parameters with known name normal

    String userId=servReq.getParameter("user_id");
    

    How to define Singleton in TypeScript

    Another option is to use Symbols in your module. This way you can protect your class, also if the final user of your API is using normal Javascript:

    let _instance = Symbol();
    export default class Singleton {
    
        constructor(singletonToken) {
            if (singletonToken !== _instance) {
                throw new Error("Cannot instantiate directly.");
            }
            //Init your class
        }
    
        static get instance() {
            return this[_instance] || (this[_instance] = new Singleton(_singleton))
        }
    
        public myMethod():string {
            return "foo";
        }
    }
    

    Usage:

    var str:string = Singleton.instance.myFoo();
    

    If the user is using your compiled API js file, also will get an error if he try to instantiate manually your class:

    // PLAIN JAVASCRIPT: 
    var instance = new Singleton(); //Error the argument singletonToken !== _instance symbol
    

    GitHub - error: failed to push some refs to '[email protected]:myrepo.git'

    In my case Github was down.

    Maybe also check https://www.githubstatus.com/

    You can subscribe to notifications per email and text to know when you can push your changes again.

    How to link to a <div> on another page?

    You can add hash info in next page url to move browser at specific position(any html element), after page is loaded.

    This is can done in this way:

    add hash in the url of next_page : example.com#hashkey

    $( document ).ready(function() {
    
      ##get hash code at next page
      var hashcode = window.location.hash;
    
      ## move page to any specific position of next page(let that is div with id "hashcode")
      $('html,body').animate({scrollTop: $('div#'+hascode).offset().top},'slow');
    
    });
    

    jQuery bind to Paste Event, how to get the content of the paste

    I recently needed to accomplish something similar to this. I used the following design to access the paste element and value. jsFiddle demo

    $('body').on('paste', 'input, textarea', function (e)
    {
        setTimeout(function ()
        {
            //currentTarget added in jQuery 1.3
            alert($(e.currentTarget).val());
            //do stuff
        },0);
    });
    

    Kill some processes by .exe file name

    Quick Answer:

    foreach (var process in Process.GetProcessesByName("whatever"))
    {
        process.Kill();
    }
    

    (leave off .exe from process name)

    How SQL query result insert in temp table?

    Suppose your existing reporting query is

    Select EmployeeId,EmployeeName 
    from Employee 
    Where EmployeeId>101 order by EmployeeName
    

    and you have to save this data into temparory table then you query goes to

    Select EmployeeId,EmployeeName 
    into #MyTempTable 
    from Employee 
    Where EmployeeId>101 order by EmployeeName  
    

    How to delete multiple files at once in Bash on Linux?

    Bash supports all sorts of wildcards and expansions.

    Your exact case would be handled by brace expansion, like so:

    $ rm -rf abc.log.2012-03-{14,27,28}
    

    The above would expand to a single command with all three arguments, and be equivalent to typing:

    $ rm -rf abc.log.2012-03-14 abc.log.2012-03-27 abc.log.2012-03-28
    

    It's important to note that this expansion is done by the shell, before rm is even loaded.

    Pass Additional ViewData to a Strongly-Typed Partial View

    You can use the dynamic variable ViewBag

    ViewBag.AnotherValue = valueToView;
    

    Border for an Image view in Android?

    For those who are searching custom border and shape of ImageView. You can use android-shape-imageview

    image

    Just add compile 'com.github.siyamed:android-shape-imageview:0.9.+@aar' to your build.gradle.

    And use in your layout.

    <com.github.siyamed.shapeimageview.BubbleImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/neo"
        app:siArrowPosition="right"
        app:siSquare="true"/>
    

    Bitbucket fails to authenticate on git pull

    I needed to do this and run a git pull in order to set my password from the command line in order to get this working.

    Note this method saves your password in a plain text file on your disk:

    git config --global credential.helper store
    git pull
    

    Other solutions here: Is there a way to skip password typing when using https:// on GitHub?

    Get installed applications in a system

    Iterating through the registry key "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" seems to give a comprehensive list of installed applications.

    Aside from the example below, you can find a similar version to what I've done here.

    This is a rough example, you'll probaby want to do something to strip out blank rows like in the 2nd link provided.

    string registry_key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
    using(Microsoft.Win32.RegistryKey key = Registry.LocalMachine.OpenSubKey(registry_key))
    {
        foreach(string subkey_name in key.GetSubKeyNames())
        {
            using(RegistryKey subkey = key.OpenSubKey(subkey_name))
            {
                Console.WriteLine(subkey.GetValue("DisplayName"));
            }
        }
    }
    

    Alternatively, you can use WMI as has been mentioned:

    ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_Product");
    foreach(ManagementObject mo in mos.Get())
    {
        Console.WriteLine(mo["Name"]);
    }
    

    But this is rather slower to execute, and I've heard it may only list programs installed under "ALLUSERS", though that may be incorrect. It also ignores the Windows components & updates, which may be handy for you.

    GoTo Next Iteration in For Loop in java

    If you want to skip current iteration, use continue;.

    for(int i = 0; i < 5; i++){
        if (i == 2){
            continue;
        }
     }
    

    Need to break out of the whole loop? Use break;

    for(int i = 0; i < 5; i++){
        if (i == 2){
            break;
        }
    }
    

    If you need to break out of more than one loop use break someLabel;

    outerLoop:                                           // Label the loop
    for(int j = 0; j < 5; j++){
         for(int i = 0; i < 5; i++){
            if (i==2){
              break outerLoop;
            }
         }
      }
    

    *Note that in this case you are not marking a point in code to jump to, you are labeling the loop! So after the break the code will continue right after the loop!

    When you need to skip one iteration in nested loops use continue someLabel;, but you can also combine them all.

    outerLoop:
    for(int j = 0; j < 10; j++){
         innerLoop:
         for(int i = 0; i < 10; i++){
            if (i + j == 2){
              continue innerLoop;
            }
            if (i + j == 4){
              continue outerLoop;
            }
            if (i + j == 6){
              break innerLoop;
            }
            if (i + j == 8){
              break outerLoop;
            }
         }
      }
    

    How do I perform query filtering in django templates

    For anyone looking for an answer in 2020. This worked for me.

    In Views:

     class InstancesView(generic.ListView):
            model = AlarmInstance
            context_object_name = 'settings_context'
            queryset = Group.objects.all()
            template_name = 'insta_list.html'
    
            @register.filter
            def filter_unknown(self, aVal):
                result = aVal.filter(is_known=False)
                return result
    
            @register.filter
            def filter_known(self, aVal):
                result = aVal.filter(is_known=True)
                return result
    

    In template:

    {% for instance in alarm.qar_alarm_instances|filter_unknown:alarm.qar_alarm_instances %}
    

    In pseudocode:

    For each in model.child_object|view_filter:filter_arg
    

    Hope that helps.

    How to remove old Docker containers

    To simply remove everything that is not currently used by a running container the following alias, that I usually put into the .bash_profile on my Mac, will help:

    alias dockerclean="docker ps -q -a | xargs docker rm -v && docker images -q | xargs docker rmi"
    

    Whenever dockerclean is invoked from the command line it will remove stopped containers as well as unused image layers. For running containers and used images it will print a warning message and skip over it.

    How do I create a foreign key in SQL Server?

    create table question_bank
    (
        question_id uniqueidentifier primary key,
        question_exam_id uniqueidentifier not null,
        question_text varchar(1024) not null,
        question_point_value decimal,
        constraint fk_questionbank_exams foreign key (question_exam_id) references exams (exam_id)
    );
    

    How to search for string in an array

    You could use the following without the wrapper function, but it provides a nicer API:

    Function IsInArray(ByVal findString as String, ByVal arrayToSearch as Variant) as Boolean
      IsInArray = UBound(Filter(arrayToSearch,findString)) >= 0
    End Function
    

    The Filter function has the following signature:

    Filter(sourceArray, stringToMatch, [Include As Boolean = True], [Compare as VbCompareMethod = vbBinaryCompare])

    Merge trunk to branch in Subversion

    Is there something that prevents you from merging all revisions on trunk since the last merge?

    svn merge -rLastRevisionMergedFromTrunkToBranch:HEAD url/of/trunk path/to/branch/wc
    

    should work just fine. At least if you want to merge all changes on trunk to your branch.

    Trigger Change event when the Input value changed programmatically?

    If someone is using react, following will be useful:

    https://stackoverflow.com/a/62111884/1015678

    const valueSetter = Object.getOwnPropertyDescriptor(this.textInputRef, 'value').set;
    const prototype = Object.getPrototypeOf(this.textInputRef);
    const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
    if (valueSetter && valueSetter !== prototypeValueSetter) {
        prototypeValueSetter.call(this.textInputRef, 'new value');
    } else {
        valueSetter.call(this.textInputRef, 'new value');
    }
    this.textInputRef.dispatchEvent(new Event('input', { bubbles: true }));
    

    Oracle PL/SQL : remove "space characters" from a string

    To remove any whitespaces you could use:

    myValue := replace(replace(replace(replace(replace(replace(myValue, chr(32)), chr(9)),  chr(10)), chr(11)), chr(12)), chr(13));
    

    Example: remove all whitespaces in a table:

    update myTable t
        set t.myValue = replace(replace(replace(replace(replace(replace(t.myValue, chr(32)), chr(9)), chr(10)), chr(11)), chr(12)), chr(13))
    where
        length(t.myValue) > length(replace(replace(replace(replace(replace(replace(t.myValue, chr(32)), chr(9)), chr(10)), chr(11)), chr(12)), chr(13)));
    

    or

    update myTable t
        set t.myValue = replace(replace(replace(replace(replace(replace(t.myValue, chr(32)), chr(9)), chr(10)), chr(11)), chr(12)), chr(13))
    where
        t.myValue like '% %'
    

    Selenium and xPath - locating a link by containing text

    @FindBy(xpath = "//button[@class='btn btn-primary' and contains(text(), 'Submit')]") private WebElementFacade submitButton;
    
    public void clickOnSubmitButton() {
        submitButton.click();
    }   
    

    How to configure Chrome's Java plugin so it uses an existing JDK in the machine

    I'm on Windows 7 64 bit and couldn't understand if I can manually enable JRE8 64 bit for Chrome. Turned out that my problem was that Java plugin DLL is 64 bit which wouldn't work in 32 bit Chrome. Therefore you need to install x86 version of JRE. Below are Windows registry settings you need to create

    Windows Registry Editor Version 5.00
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2]
    "Description"="Oracle® Next Generation Java™ Plug-In"
    "GeckoVersion"="1.9"
    "Path"="C:\\Program Files (x86)\\Java\\jre8\\bin\\plugin2\\npjp2.dll"
    "ProductName"="Oracle® Java™ Plug-In"
    "Vendor"="Oracle Corp."
    "Version"="1.8.0"
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes]
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet]
    "Description"="Java™ Applet"
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;jpi-version=1.8.0]
    "Description"="Java™ Applet"
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.1]
    "Description"="Java™ Applet"
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.1.1]
    "Description"="Java™ Applet"
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.1.2]
    "Description"="Java™ Applet"
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.1.3]
    "Description"="Java™ Applet"
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.2]
    "Description"="Java™ Applet"
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.2.1]
    "Description"="Java™ Applet"
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.3]
    "Description"="Java™ Applet"
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.3.1]
    "Description"="Java™ Applet"
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.4]
    "Description"="Java™ Applet"
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.4.1]
    "Description"="Java™ Applet"
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.4.2]
    "Description"="Java™ Applet"
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.5]
    "Description"="Java™ Applet"
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.6]
    "Description"="Java™ Applet"
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.7]
    "Description"="Java™ Applet"
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.8]
    "Description"="Java™ Applet"
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-vm]
    "Description"="Java™ Virtual Machine"
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-vm-npruntime]
    "Description"="Java™ Applet"
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin]
    "Description"="Oracle® Next Generation Java™ Plug-In"
    "GeckoVersion"="1.9"
    "ProductName"="Oracle® Java™ Plug-In"
    "Vendor"="Oracle Corp."
    "Version"="160_29"
    "Path"="C:\\Program Files\\Java\\jre8\\bin\\plugin2\\npjp2.dll"
    

    How to disable javax.swing.JButton in java?

    For that I have written the following code in the "ActionPeformed(...)" method of the "Start" button

    You need that code to be in the actionPerformed(...) of the ActionListener registered with the Start button, not for the Start button itself.

    You can add a simple ActionListener like this:

    JButton startButton = new JButton("Start");
    startButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            startButton.setEnabled(false);
            stopButton.setEnabled(true);
         }
       }
     );
    

    note that your startButton above will need to be final in the above example if you want to create the anonymous listener in local scope.

    How to enable scrolling of content inside a modal?

    After using all these mentioned solution, i was still not able to scroll using mouse scroll, keyboard up/down button were working for scrolling content.

    So i have added below css fixes to make it working

    .modal-open {
        overflow: hidden;
    }
    
    .modal-open .modal {
        overflow-x: hidden;
        overflow-y: auto;
        **pointer-events: auto;**
    }
    

    Added pointer-events: auto; to make it mouse scrollable.

    Cannot assign requested address - possible causes?

    It turns out that the problem really was that the address was busy - the busyness was caused by some other problems in how we are handling network communications. Your inputs have helped me figure this out. Thank you.

    EDIT: to be specific, the problems in handling our network communications were that these status updates would be constantly re-sent if the first failed. It was only a matter of time until we had every distributed slave trying to send its status update at the same time, which was over-saturating our network.

    Logging request/response messages when using HttpClient

    Network tracing also available for next objects (see article on msdn)

    • System.Net.Sockets Some public methods of the Socket, TcpListener, TcpClient, and Dns classes
    • System.Net Some public methods of the HttpWebRequest, HttpWebResponse, FtpWebRequest, and FtpWebResponse classes, and SSL debug information (invalid certificates, missing issuers list, and client certificate errors.)
    • System.Net.HttpListener Some public methods of the HttpListener, HttpListenerRequest, and HttpListenerResponse classes.
    • System.Net.Cache Some private and internal methods in System.Net.Cache.
    • System.Net.Http Some public methods of the HttpClient, DelegatingHandler, HttpClientHandler, HttpMessageHandler, MessageProcessingHandler, and WebRequestHandler classes.
    • System.Net.WebSockets.WebSocket Some public methods of the ClientWebSocket and WebSocket classes.

    Put next lines of code to the configuration file

    <configuration>  
      <system.diagnostics>  
        <sources>  
          <source name="System.Net" tracemode="includehex" maxdatasize="1024">  
            <listeners>  
              <add name="System.Net"/>  
            </listeners>  
          </source>  
          <source name="System.Net.Cache">  
            <listeners>  
              <add name="System.Net"/>  
            </listeners>  
          </source>  
          <source name="System.Net.Http">  
            <listeners>  
              <add name="System.Net"/>  
            </listeners>  
          </source>  
          <source name="System.Net.Sockets">  
            <listeners>  
              <add name="System.Net"/>  
            </listeners>  
          </source>  
          <source name="System.Net.WebSockets">  
            <listeners>  
              <add name="System.Net"/>  
            </listeners>  
          </source>  
        </sources>  
        <switches>  
          <add name="System.Net" value="Verbose"/>  
          <add name="System.Net.Cache" value="Verbose"/>  
          <add name="System.Net.Http" value="Verbose"/>  
          <add name="System.Net.Sockets" value="Verbose"/>  
          <add name="System.Net.WebSockets" value="Verbose"/>  
        </switches>  
        <sharedListeners>  
          <add name="System.Net"  
            type="System.Diagnostics.TextWriterTraceListener"  
            initializeData="network.log"  
          />  
        </sharedListeners>  
        <trace autoflush="true"/>  
      </system.diagnostics>  
    </configuration>  
    

    VMWare Player vs VMWare Workstation

    One main reason we went with Workstation over Player at my job is because we need to run VMs that use a physical disk as their hard drive instead of a virtual disk. Workstation supports using physical disks while Player does not.

    How to make an Android device vibrate? with different frequency?

    Above answer is very correct but I'm giving an easy step to do it:

     private static final long[] THREE_CYCLES = new long[] { 100, 1000, 1000,  1000, 1000, 1000 };
    
      public void longVibrate(View v) 
      {
         vibrateMulti(THREE_CYCLES);
      }
    
      private void vibrateMulti(long[] cycles) {
          NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
          Notification notification = new Notification();
    
          notification.vibrate = cycles; 
          notificationManager.notify(0, notification);
      }
    

    And then in your xml file:

    <button android:layout_height="wrap_content" 
            android:layout_width ="wrap_content" 
            android:onclick      ="longVibrate" 
            android:text         ="VibrateThrice">
    </button>
    

    That's the easiest way.

    document.getElementById replacement in angular4 / typescript?

    Try this:

    TypeScript file code:

    (<HTMLInputElement>document.getElementById("name")).value

    HTML code:

     <input id="name" type="text" #name /> 

    Use of contains in Java ArrayList<String>

    You are right. ArrayList.contains() tests equals(), not object identity:

    returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e))

    If you got a NullPointerException, verify that you initialized your list, either in a constructor or the declaration. For example:

    private List<String> rssFeedURLs = new ArrayList<String>();
    

    How to copy selected lines to clipboard in vim

    If you are using vim in MAC OSX, unfortunately it comes with older verion, and not complied with clipboard options. Luckily, homebrew can easily solve this problem.

    install vim:

    brew install vim --with-lua --with-override-system-vim

    install gui verion of vim:

    brew install macvim --with-lua --with-override-system-vim

    restart the terminal to take effect.

    append the following line to ~/.vimrc

    set clipboard=unnamed

    now you can copy the line in vim withyy and paste it system-wide.

    Is there any way to specify a suggested filename when using data: URI?

    The following Javascript snippet works in Chrome by using the new 'download' attribute of links and simulating a click.

    function downloadWithName(uri, name) {
      var link = document.createElement("a");
      link.download = name;
      link.href = uri;
      link.click();
    }
    

    And the following example shows it's use:

    downloadWithName("data:,Hello%2C%20World!", "helloWorld.txt")
    

    *ngIf and *ngFor on same element causing error

    On other solution might be to put an empty array in your for loop in the case where you don't want to display it

    <div *ngFor="let thing of show ? stuff : []">
    

    Where "stuff" is an array of "thing" and "show" the boolean to display or not the content

    Eclipse fonts and background color

    On Windows or Mac, you can find this setting under the General ? Editors ? Text Editors menu.

    Are there any HTTP/HTTPS interception tools like Fiddler for mac OS X?

    Cocoa Packet Analyzer is similar to WireShark but with a much better interface. http://www.tastycocoabytes.com/cpa/

    Check which element has been clicked with jQuery

    So you are doing this a bit backwards. Typically you'd do something like this:

    ?<div class='article'>
      Article 1
    </div>
    <div class='article'>
      Article 2
    </div>
    <div class='article'>
      Article 3
    </div>?
    

    And then in your jQuery:

    $('.article').click(function(){
        article = $(this).text(); //$(this) is what you clicked!
        });?
    

    When I see things like #search-item .search-article, #search-item .search-article, and #search-item .search-article I sense you are overspecifying your CSS which makes writing concise jQuery very difficult. This should be avoided if at all possible.

    How to prevent a jQuery Ajax request from caching in Internet Explorer?

    Cache-Control: no-cache, no-store
    

    These two header values can be combined to get the required effect on both IE and Firefox

    Calling Objective-C method from C++ member function?

    Also, you can call into Objective-C runtime to call the method.

    TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

    What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:

    x = ["0", "1", "2"] 
    y = int(x[0]) #accessing the zeroth element
    

    If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:

    x = ["0", "1", "2"]
    y = ''.join(x) # converting list into string
    z = int(y)
    

    If your list elements are not strings, you'll have to convert them to strings before using str.join:

    x = [0, 1, 2]
    y = ''.join(map(str, x))
    z = int(y)
    

    Also, as stated above, make sure that you're not returning a nested list.

    How can I access each element of a pair in a pair list?

    If you want to use names, try a namedtuple:

    from collections import namedtuple
    
    Pair = namedtuple("Pair", ["first", "second"])
    
    pairs = [Pair("a", 1), Pair("b", 2), Pair("c", 3)]
    
    for pair in pairs:
        print("First = {}, second = {}".format(pair.first, pair.second))
    

    Convert string to Boolean in javascript

    See this question for reference:

    How can I convert a string to boolean in JavaScript?

    There are a few ways:

    // Watch case sensitivity!
    var boolVal = (string == "true");
    

    or

    var boolVal = Boolean("false");
    

    or

    String.prototype.bool = function() {
        return (/^true$/i).test(this);
    };
    alert("true".bool());
    

    Convert integer value to matching Java Enum

    I know this question is a few years old, but as Java 8 has, in the meantime, brought us Optional, I thought I'd offer up a solution using it (and Stream and Collectors):

    public enum PcapLinkType {
      DLT_NULL(0),
      DLT_EN3MB(2),
      DLT_AX25(3),
      /*snip, 200 more enums, not always consecutive.*/
      // DLT_UNKNOWN(-1); // <--- NO LONGER NEEDED
    
      private final int value;
      private PcapLinkType(int value) { this.value = value; }
    
      private static final Map<Integer, PcapLinkType> map;
      static {
        map = Arrays.stream(values())
            .collect(Collectors.toMap(e -> e.value, e -> e));
      }
    
      public static Optional<PcapLinkType> fromInt(int value) {
        return Optional.ofNullable(map.get(value));
      }
    }
    

    Optional is like null: it represents a case when there is no (valid) value. But it is a more type-safe alternative to null or a default value such as DLT_UNKNOWN because you could forget to check for the null or DLT_UNKNOWN cases. They are both valid PcapLinkType values! In contrast, you cannot assign an Optional<PcapLinkType> value to a variable of type PcapLinkType. Optional makes you check for a valid value first.

    Of course, if you want to retain DLT_UNKNOWN for backward compatibility or whatever other reason, you can still use Optional even in that case, using orElse() to specify it as the default value:

    public enum PcapLinkType {
      DLT_NULL(0),
      DLT_EN3MB(2),
      DLT_AX25(3),
      /*snip, 200 more enums, not always consecutive.*/
      DLT_UNKNOWN(-1);
    
      private final int value;
      private PcapLinkType(int value) { this.value = value; }
    
      private static final Map<Integer, PcapLinkType> map;
      static {
        map = Arrays.stream(values())
            .collect(Collectors.toMap(e -> e.value, e -> e));
      }
    
      public static PcapLinkType fromInt(int value) {
        return Optional.ofNullable(map.get(value)).orElse(DLT_UNKNOWN);
      }
    }
    

    Is there a minlength validation attribute in HTML5?

    See http://caniuse.com/#search=minlength. Some browsers may not support this attribute.


    If the value of the "type" is one of them:

    text, email, search, password, tel, or URL (warning: not include number | no browser support "tel" now - 2017.10)

    Use the minlength(/ maxlength) attribute. It specifies the minimum number of characters.

    For example,

    <input type="text" minlength="11" maxlength="11" pattern="[0-9]*" placeholder="input your phone number">
    

    Or use the "pattern" attribute:

    <input type="text" pattern="[0-9]{11}" placeholder="input your phone number">
    

    If the "type" is number, although minlength(/ maxlength) is not be supported, you can use the min(/ max) attribute instead of it.

    For example,

    <input type="number" min="100" max="999" placeholder="input a three-digit number">
    

    Fiddler not capturing traffic from browsers

    I had the same problem, but it turned out to be a chrome extension called hola (or Proxy SwitchySharp), that messed with the proxy settings. Removing Hola fixed the problem

    Map and filter an array at the same time

    At some point, isn't it easier(or just as easy) to use a forEach

    _x000D_
    _x000D_
    var options = [_x000D_
      { name: 'One', assigned: true }, _x000D_
      { name: 'Two', assigned: false }, _x000D_
      { name: 'Three', assigned: true }, _x000D_
    ];_x000D_
    _x000D_
    var reduced = []_x000D_
    options.forEach(function(option) {_x000D_
      if (option.assigned) {_x000D_
         var someNewValue = { name: option.name, newProperty: 'Foo' }_x000D_
         reduced.push(someNewValue);_x000D_
      }_x000D_
    });_x000D_
    _x000D_
    document.getElementById('output').innerHTML = JSON.stringify(reduced);
    _x000D_
    <h1>Only assigned options</h1>_x000D_
    <pre id="output"> </pre>
    _x000D_
    _x000D_
    _x000D_

    However it would be nice if there was a malter() or fap() function that combines the map and filter functions. It would work like a filter, except instead of returning true or false, it would return any object or a null/undefined.

    How to list all properties of a PowerShell object

    You can also use:

    Get-WmiObject -Class "Win32_computersystem" | Select *
    

    This will show the same result as Format-List * used in the other answers here.

    Can dplyr join on multiple columns or composite key?

    Updating to use tibble()

    You can pass a named vector of length greater than 1 to the by argument of left_join():

    library(dplyr)
    
    d1 <- tibble(
      x = letters[1:3],
      y = LETTERS[1:3],
      a = rnorm(3)
      )
    
    d2 <- tibble(
      x2 = letters[3:1],
      y2 = LETTERS[3:1],
      b = rnorm(3)
      )
    
    left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))
    

    How to convert an array into an object using stdClass()

    To convert array to object using stdClass just add (object) to array u declare.

    EX:

    echo $array['value'];
    echo $object->value;
    

    to convert object to array

    $obj = (object)$array;
    

    to convert array to object

    $arr = (array)$object
    

    with these methods you can swap between array and object very easily.


    Another method is to use json

    $object = json_decode(json_encode($array), FALSE);
    

    But this is a much more memory intensive way to do and is not supported by versions of PHP <= 5.1

    Maven: How to run a .java file from command line passing arguments

    You could run: mvn exec:exec -Dexec.args="arg1".

    This will pass the argument arg1 to your program.

    You should specify the main class fully qualified, for example, a Main.java that is in a package test would need

    mvn exec:java  -Dexec.mainClass=test.Main
    

    By using the -f parameter, as decribed here, you can also run it from other directories.

    mvn exec:java -Dexec.mainClass=test.Main -f folder/pom.xm
    

    For multiple arguments, simply separate them with a space as you would at the command line.

    mvn exec:java -Dexec.mainClass=test.Main -Dexec.args="arg1 arg2 arg3"
    

    For arguments separated with a space, you can group using 'argument separated with space' inside the quotation marks.

    mvn exec:java -Dexec.mainClass=test.Main -Dexec.args="'argument separated with space' 'another one'"
    

    How to reload or re-render the entire page using AngularJS

    $route.reload() will reinitialise the controllers but not the services. If you want to reset the whole state of your application you can use:

    $window.location.reload();
    

    This is a standard DOM method which you can access injecting the $window service.

    If you want to be sure to reload the page from the server, for example when you are using Django or another web framework and you want a fresh server side render, pass true as a parameter to reload, as explained in the docs. Since that requires interaction with the server, it will be slower so do it only if necessary

    Angular 2

    The above applies to Angular 1. I am not using Angular 2, looks like the services are different there, there is Router, Location, and the DOCUMENT. I did not test different behaviors there

    finding the type of an element using jQuery

    The following will return true if the element is an input:

    $("#elementId").is("input") 
    

    or you can use the following to get the name of the tag:

    $("#elementId").get(0).tagName
    

    Using varchar(MAX) vs TEXT on SQL Server

    You can't search a text field without converting it from text to varchar.

    declare @table table (a text)
    insert into @table values ('a')
    insert into @table values ('a')
    insert into @table values ('b')
    insert into @table values ('c')
    insert into @table values ('d')
    
    
    select *
    from @table
    where a ='a'
    

    This give an error:

    The data types text and varchar are incompatible in the equal to operator.
    

    Wheras this does not:

    declare @table table (a varchar(max))
    

    Interestingly, LIKE still works, i.e.

    where a like '%a%'
    

    The type or namespace name could not be found

    The compiled dll should have public Class.

    make an ID in a mysql table auto_increment (after the fact)

    I'm guessing that you don't need to re-increment the existing data so, why can't you just run a simple ALTER TABLE command to change the PK's attributes?

    Something like:

    ALTER TABLE `content` CHANGE `id` `id` SMALLINT( 5 ) UNSIGNED NOT NULL AUTO_INCREMENT 
    

    I've tested this code on my own MySQL database and it works but I have not tried it with any meaningful number of records. Once you've altered the row then you need to reset the increment to a number guaranteed not to interfere with any other records.

    ALTER TABLE `content` auto_increment = MAX(`id`) + 1
    

    Again, untested but I believe it will work.

    Create a new database with MySQL Workbench

    1. Launch MySQL Workbench.
    2. On the left pane of the welcome window, choose a database to connect to under "Open Connection to Start Querying".
    3. The query window will open. On its left pane, there is a section titled "Object Browser", which shows the list of databases. (Side note: The terms "schema" and "database" are synonymous in this program.)
    4. Right-click on one of the existing databases and click "Create Schema...". This will launch a wizard that will help you create a database.

    If you'd prefer to do it in SQL, enter this query into the query window:

    CREATE SCHEMA Test
    

    Press CTRL + Enter to submit it, and you should see confirmation in the output pane underneath the query window. You'll have to right-click on an existing schema in the Object panel and click "Refresh All" to see it show up, though.

    EPPlus - Read Excel Table

    I have got an error on the first answer so I have changed some code line.

    Please try my new code, it's working for me.

    using OfficeOpenXml;
    using OfficeOpenXml.Table;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    
    public static class ImportExcelReader
    {
        public static List<T> ImportExcelToList<T>(this ExcelWorksheet worksheet) where T : new()
        {
            //DateTime Conversion
            Func<double, DateTime> convertDateTime = new Func<double, DateTime>(excelDate =>
            {
                if (excelDate < 1)
                {
                    throw new ArgumentException("Excel dates cannot be smaller than 0.");
                }
    
                DateTime dateOfReference = new DateTime(1900, 1, 1);
    
                if (excelDate > 60d)
                {
                    excelDate = excelDate - 2;
                }
                else
                {
                    excelDate = excelDate - 1;
                }
    
                return dateOfReference.AddDays(excelDate);
            });
    
            ExcelTable table = null;
    
            if (worksheet.Tables.Any())
            {
                table = worksheet.Tables.FirstOrDefault();
            }
            else
            {
                table = worksheet.Tables.Add(worksheet.Dimension, "tbl" + ShortGuid.NewGuid().ToString());
    
                ExcelAddressBase newaddy = new ExcelAddressBase(table.Address.Start.Row, table.Address.Start.Column, table.Address.End.Row + 1, table.Address.End.Column);
    
                //Edit the raw XML by searching for all references to the old address
                table.TableXml.InnerXml = table.TableXml.InnerXml.Replace(table.Address.ToString(), newaddy.ToString());
            }
    
            //Get the cells based on the table address
            List<IGrouping<int, ExcelRangeBase>> groups = table.WorkSheet.Cells[table.Address.Start.Row, table.Address.Start.Column, table.Address.End.Row, table.Address.End.Column]
                .GroupBy(cell => cell.Start.Row)
                .ToList();
    
            //Assume the second row represents column data types (big assumption!)
            List<Type> types = groups.Skip(1).FirstOrDefault().Select(rcell => rcell.Value.GetType()).ToList();
    
            //Get the properties of T
            List<PropertyInfo> modelProperties = new T().GetType().GetProperties().ToList();
    
            //Assume first row has the column names
            var colnames = groups.FirstOrDefault()
                .Select((hcell, idx) => new
                {
                    Name = hcell.Value.ToString(),
                    index = idx
                })
                .Where(o => modelProperties.Select(p => p.Name).Contains(o.Name))
                .ToList();
    
            //Everything after the header is data
            List<List<object>> rowvalues = groups
                .Skip(1) //Exclude header
                .Select(cg => cg.Select(c => c.Value).ToList()).ToList();
    
            //Create the collection container
            List<T> collection = new List<T>();
            foreach (List<object> row in rowvalues)
            {
                T tnew = new T();
                foreach (var colname in colnames)
                {
                    //This is the real wrinkle to using reflection - Excel stores all numbers as double including int
                    object val = row[colname.index];
                    Type type = types[colname.index];
                    PropertyInfo prop = modelProperties.FirstOrDefault(p => p.Name == colname.Name);
    
                    //If it is numeric it is a double since that is how excel stores all numbers
                    if (type == typeof(double))
                    {
                        //Unbox it
                        double unboxedVal = (double)val;
    
                        //FAR FROM A COMPLETE LIST!!!
                        if (prop.PropertyType == typeof(int))
                        {
                            prop.SetValue(tnew, (int)unboxedVal);
                        }
                        else if (prop.PropertyType == typeof(double))
                        {
                            prop.SetValue(tnew, unboxedVal);
                        }
                        else if (prop.PropertyType == typeof(DateTime))
                        {
                            prop.SetValue(tnew, convertDateTime(unboxedVal));
                        }
                        else if (prop.PropertyType == typeof(string))
                        {
                            prop.SetValue(tnew, val.ToString());
                        }
                        else
                        {
                            throw new NotImplementedException(string.Format("Type '{0}' not implemented yet!", prop.PropertyType.Name));
                        }
                    }
                    else
                    {
                        //Its a string
                        prop.SetValue(tnew, val);
                    }
                }
                collection.Add(tnew);
            }
    
            return collection;
        }
    }
    

    How to call this function? please view below code;

    private List<FundraiserStudentListModel> GetStudentsFromExcel(HttpPostedFileBase file)
        {
            List<FundraiserStudentListModel> list = new List<FundraiserStudentListModel>();
            if (file != null)
            {
                try
                {
                    using (ExcelPackage package = new ExcelPackage(file.InputStream))
                    {
                        ExcelWorkbook workbook = package.Workbook;
                        if (workbook != null)
                        {
                            ExcelWorksheet worksheet = workbook.Worksheets.FirstOrDefault();
                            if (worksheet != null)
                            {
                                list = worksheet.ImportExcelToList<FundraiserStudentListModel>();
                            }
                        }
                    }
                }
                catch (Exception err)
                {
                    //save error log
                }
            }
            return list;
        }
    

    FundraiserStudentListModel here:

     public class FundraiserStudentListModel
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
    }
    

    Add two numbers and display result in textbox with Javascript

    Here a working fiddle: http://jsfiddle.net/sjh36otu/

            function add_number() {
    
                var first_number = parseInt(document.getElementById("Text1").value);
                var second_number = parseInt(document.getElementById("Text2").value);
                var result = first_number + second_number;
    
                document.getElementById("txtresult").value = result;
            }
    

    Unzipping files

    I wrote an unzipper in Javascript. It works.

    It relies on Andy G.P. Na's binary file reader and some RFC1951 inflate logic from notmasteryet. I added the ZipFile class.

    working example:
    http://cheeso.members.winisp.net/Unzip-Example.htm (dead link)

    The source:
    http://cheeso.members.winisp.net/srcview.aspx?dir=js-unzip (dead link)

    NB: the links are dead; I'll find a new host soon.

    Included in the source is a ZipFile.htm demonstration page, and 3 distinct scripts, one for the zipfile class, one for the inflate class, and one for a binary file reader class. The demo also depends on jQuery and jQuery UI. If you just download the js-zip.zip file, all of the necessary source is there.


    Here's what the application code looks like in Javascript:

    // In my demo, this gets attached to a click event.
    // it instantiates a ZipFile, and provides a callback that is
    // invoked when the zip is read.  This can take a few seconds on a
    // large zip file, so it's asynchronous. 
    var readFile = function(){
        $("#status").html("<br/>");
        var url= $("#urlToLoad").val();
        var doneReading = function(zip){
            extractEntries(zip);
        };
    
        var zipFile = new ZipFile(url, doneReading);
    };
    
    
    // this function extracts the entries from an instantiated zip
    function extractEntries(zip){
        $('#report').accordion('destroy');
    
        // clear
        $("#report").html('');
    
        var extractCb = function(id) {
            // this callback is invoked with the entry name, and entry text
            // in my demo, the text is just injected into an accordion panel.
            return (function(entryName, entryText){
                var content = entryText.replace(new RegExp( "\\n", "g" ), "<br/>");
                $("#"+id).html(content);
                $("#status").append("extract cb, entry(" + entryName + ")  id(" + id + ")<br/>");
                $('#report').accordion('destroy');
                $('#report').accordion({collapsible:true, active:false});
            });
        }
    
        // for each entry in the zip, extract it. 
        for (var i=0; i<zip.entries.length;  i++) {
            var entry = zip.entries[i];
    
            var entryInfo = "<h4><a>" + entry.name + "</a></h4>\n<div>";
    
            // contrive an id for the entry, make it unique
            var randomId = "id-"+ Math.floor((Math.random() * 1000000000));
    
            entryInfo += "<span class='inputDiv'><h4>Content:</h4><span id='" + randomId +
                "'></span></span></div>\n";
    
            // insert the info for one entry as the last child within the report div
            $("#report").append(entryInfo);
    
            // extract asynchronously
            entry.extract(extractCb(randomId));
        }
    }
    

    The demo works in a couple of steps: The readFile fn is triggered by a click, and instantiates a ZipFile object, which reads the zip file. There's an asynchronous callback for when the read completes (usually happens in less than a second for reasonably sized zips) - in this demo the callback is held in the doneReading local variable, which simply calls extractEntries, which just blindly unzips all the content of the provided zip file. In a real app you would probably choose some of the entries to extract (allow the user to select, or choose one or more entries programmatically, etc).

    The extractEntries fn iterates over all entries, and calls extract() on each one, passing a callback. Decompression of an entry takes time, maybe 1s or more for each entry in the zipfile, which means asynchrony is appropriate. The extract callback simply adds the extracted content to an jQuery accordion on the page. If the content is binary, then it gets formatted as such (not shown).


    It works, but I think that the utility is somewhat limited.

    For one thing: It's very slow. Takes ~4 seconds to unzip the 140k AppNote.txt file from PKWare. The same uncompress can be done in less than .5s in a .NET program. EDIT: The Javascript ZipFile unpacks considerably faster than this now, in IE9 and in Chrome. It is still slower than a compiled program, but it is plenty fast for normal browser usage.

    For another: it does not do streaming. It basically slurps in the entire contents of the zipfile into memory. In a "real" programming environment you could read in only the metadata of a zip file (say, 64 bytes per entry) and then read and decompress the other data as desired. There's no way to do IO like that in javascript, as far as I know, therefore the only option is to read the entire zip into memory and do random access in it. This means it will place unreasonable demands on system memory for large zip files. Not so much a problem for a smaller zip file.

    Also: It doesn't handle the "general case" zip file - there are lots of zip options that I didn't bother to implement in the unzipper - like ZIP encryption, WinZip encryption, zip64, UTF-8 encoded filenames, and so on. (EDIT - it handles UTF-8 encoded filenames now). The ZipFile class handles the basics, though. Some of these things would not be hard to implement. I have an AES encryption class in Javascript; that could be integrated to support encryption. Supporting Zip64 would probably useless for most users of Javascript, as it is intended to support >4gb zipfiles - don't need to extract those in a browser.

    I also did not test the case for unzipping binary content. Right now it unzips text. If you have a zipped binary file, you'd need to edit the ZipFile class to handle it properly. I didn't figure out how to do that cleanly. It does binary files now, too.


    EDIT - I updated the JS unzip library and demo. It now does binary files, in addition to text. I've made it more resilient and more general - you can now specify the encoding to use when reading text files. Also the demo is expanded - it shows unzipping an XLSX file in the browser, among other things.

    So, while I think it is of limited utility and interest, it works. I guess it would work in Node.js.

    how to open .mat file without using MATLAB?

    I didn't use it myself but heard of a simple tool (not a text editor) for this so it is definitely possible without setting up a programming environment (by installing octave or python).

    A quick search hints that it was possible with total commander. (A lightweight tool with an easy point and click interface)

    I would not be surprised if this still works, but I can't guarantee it.

    JavaScript unit test tools for TDD

    You might also be interested in the unit testing framework that is part of qooxdoo, an open source RIA framework similar to Dojo, ExtJS, etc. but with quite a comprehensive tool chain.

    Try the online version of the testrunner. Hint: hit the gray arrow at the top left (should be made more obvious). It's a "play" button that runs the selected tests.

    To find out more about the JS classes that let you define your unit tests, see the online API viewer.

    For automated UI testing (based on Selenium RC), check out the Simulator project.

    How To Pass GET Parameters To Laravel From With GET Method ?

    Router

    Route::get('search/{id}', ['as' => 'search', 'uses' => 'SearchController@search']);
    

    Controller

    class SearchController extends BaseController {
    
        public function search(Request $request){
    
            $id= $request->id ; // or any params
    
            ...
        }
    }
    

    Difference between logical addresses, and physical addresses?

    logical address is address relative to program. It tells how much memory a particular process will take, not tell what will the exact location of the process and this exact location will we generated by using some mapping, and is known as physical address.

    What are the undocumented features and limitations of the Windows FINDSTR command?

    FINDSTR has a color bug that I described and solved at https://superuser.com/questions/1535810/is-there-a-better-way-to-mitigate-this-obscure-color-bug-when-piping-to-findstr/1538802?noredirect=1#comment2339443_1538802

    To summarize that thread, the bug is that if input is piped to FINDSTR within a parenthesized block of code, inline ANSI escape colorcodes stop working in commands executed later. An example of inline colorcodes is: echo %magenta%Alert: Something bad happened%yellow% (where magenta and yellow are vars defined earlier in the .bat file as the corresponding ANSI escape colorcodes).

    My initial solution was to call a do-nothing subroutine after the FINDSTR. Somehow the call or the return "resets" whatever needs to be reset.

    Later I discovered another solution that presumably is more efficient: place the FINDSTR phrase within parentheses, as in the following example: echo success | ( FINDSTR /R success ) Placing the FINDSTR phrase within a nested block of code appears to isolate FINDSTR's colorcode bug so it won't affect what's outside the nested block. Perhaps this technique will solve some other undesired FINDSTR side effects too.

    Android how to use Environment.getExternalStorageDirectory()

    Have in mind though, that getExternalStorageDirectory() is not going to work properly on some phones e.g. my Motorola razr maxx, as it has 2 cards /mnt/sdcard and /mnt/sdcard-ext - for internal and external SD cards respectfully. You will be getting the /mnt/sdcard only reply every time. Google must provide a way to deal with such a situation. As it renders many SD card aware apps (i.e card backup) failing miserably on these phones.

    MySQL - Replace Character in Columns

    Just running the SELECT statement will have no effect on the data. You have to use an UPDATE statement with the REPLACE to make the change occur:

    UPDATE photos
       SET caption = REPLACE(caption,'"','\'')
    

    Here is a working sample: http://sqlize.com/7FjtEyeLAh

    Displaying unicode symbols in HTML

    I think this is a file problem, you simple saved your file in 1-byte encoding like latin-1. Google up your editor and how to set files to utf-8.

    I wonder why there are editors that don't default to utf-8.

    Printing Mongo query output to a file while in the mongo shell

    We can do it this way -

    mongo db_name --quiet --eval 'DBQuery.shellBatchSize = 2000; db.users.find({}).limit(2000).toArray()' > users.json
    

    The shellBatchSize argument is used to determine how many rows is the mongo client allowed to print. Its default value is 20.

    Oracle - Best SELECT statement for getting the difference in minutes between two DateTime columns?

    SELECT date1 - date2
      FROM some_table
    

    returns a difference in days. Multiply by 24 to get a difference in hours and 24*60 to get minutes. So

    SELECT (date1 - date2) * 24 * 60 difference_in_minutes
      FROM some_table
    

    should be what you're looking for

    Escape Character in SQL Server

    If you want to escape user input in a variable you can do like below within SQL

      Set @userinput = replace(@userinput,'''','''''')
    

    The @userinput will be now escaped with an extra single quote for every occurance of a quote

    How do you execute an arbitrary native command from a string?

    Please also see this Microsoft Connect report on essentially, how blummin' difficult it is to use PowerShell to run shell commands (oh, the irony).

    http://connect.microsoft.com/PowerShell/feedback/details/376207/

    They suggest using --% as a way to force PowerShell to stop trying to interpret the text to the right.

    For example:

    MSBuild /t:Publish --% /p:TargetDatabaseName="MyDatabase";TargetConnectionString="Data Source=.\;Integrated Security=True" /p:SqlPublishProfilePath="Deploy.publish.xml" Database.sqlproj
    

    Git will not init/sync/update new submodules

    The problem for me is that the repo's previous developer had committed the submodules/thing folder as just a regular folder, meaning when I tried to run git submodule add ..., it would fail with: 'submodules/thing' already exists in the index, yet trying to update the submodule would also fail because it saw that the path did not contain a submodule.

    To fix, I had to delete the submodules/thing folder, commit the deletion, then run the git submodule add command to add it back correctly:

    git submodule add --force --name thing https://github.com/person/thing.git submodules/thing
    

    Call php function from JavaScript

    This is, in essence, what AJAX is for. Your page loads, and you add an event to an element. When the user causes the event to be triggered, say by clicking something, your Javascript uses the XMLHttpRequest object to send a request to a server.

    After the server responds (presumably with output), another Javascript function/event gives you a place to work with that output, including simply sticking it into the page like any other piece of HTML.

    You can do it "by hand" with plain Javascript , or you can use jQuery. Depending on the size of your project and particular situation, it may be more simple to just use plain Javascript .

    Plain Javascript

    In this very basic example, we send a request to myAjax.php when the user clicks a link. The server will generate some content, in this case "hello world!". We will put into the HTML element with the id output.

    The javascript

    // handles the click event for link 1, sends the query
    function getOutput() {
      getRequest(
          'myAjax.php', // URL for the PHP file
           drawOutput,  // handle successful request
           drawError    // handle error
      );
      return false;
    }  
    // handles drawing an error message
    function drawError() {
        var container = document.getElementById('output');
        container.innerHTML = 'Bummer: there was an error!';
    }
    // handles the response, adds the html
    function drawOutput(responseText) {
        var container = document.getElementById('output');
        container.innerHTML = responseText;
    }
    // helper function for cross-browser request object
    function getRequest(url, success, error) {
        var req = false;
        try{
            // most browsers
            req = new XMLHttpRequest();
        } catch (e){
            // IE
            try{
                req = new ActiveXObject("Msxml2.XMLHTTP");
            } catch(e) {
                // try an older version
                try{
                    req = new ActiveXObject("Microsoft.XMLHTTP");
                } catch(e) {
                    return false;
                }
            }
        }
        if (!req) return false;
        if (typeof success != 'function') success = function () {};
        if (typeof error!= 'function') error = function () {};
        req.onreadystatechange = function(){
            if(req.readyState == 4) {
                return req.status === 200 ? 
                    success(req.responseText) : error(req.status);
            }
        }
        req.open("GET", url, true);
        req.send(null);
        return req;
    }
    

    The HTML

    <a href="#" onclick="return getOutput();"> test </a>
    <div id="output">waiting for action</div>
    

    The PHP

    // file myAjax.php
    <?php
      echo 'hello world!';
    ?>
    

    Try it out: http://jsfiddle.net/GRMule/m8CTk/


    With a javascript library (jQuery et al)

    Arguably, that is a lot of Javascript code. You can shorten that up by tightening the blocks or using more terse logic operators, of course, but there's still a lot going on there. If you plan on doing a lot of this type of thing on your project, you might be better off with a javascript library.

    Using the same HTML and PHP from above, this is your entire script (with jQuery included on the page). I've tightened up the code a little to be more consistent with jQuery's general style, but you get the idea:

    // handles the click event, sends the query
    function getOutput() {
       $.ajax({
          url:'myAjax.php',
          complete: function (response) {
              $('#output').html(response.responseText);
          },
          error: function () {
              $('#output').html('Bummer: there was an error!');
          }
      });
      return false;
    }
    

    Try it out: http://jsfiddle.net/GRMule/WQXXT/

    Don't rush out for jQuery just yet: adding any library is still adding hundreds or thousands of lines of code to your project just as surely as if you had written them. Inside the jQuery library file, you'll find similar code to that in the first example, plus a whole lot more. That may be a good thing, it may not. Plan, and consider your project's current size and future possibility for expansion and the target environment or platform.

    If this is all you need to do, write the plain javascript once and you're done.

    Documentation

    Count lines in large files

    If your data resides on HDFS, perhaps the fastest approach is to use hadoop streaming. Apache Pig's COUNT UDF, operates on a bag, and therefore uses a single reducer to compute the number of rows. Instead you can manually set the number of reducers in a simple hadoop streaming script as follows:

    $HADOOP_HOME/bin/hadoop jar $HADOOP_HOME/hadoop-streaming.jar -Dmapred.reduce.tasks=100 -input <input_path> -output <output_path> -mapper /bin/cat -reducer "wc -l"
    

    Note that I manually set the number of reducers to 100, but you can tune this parameter. Once the map-reduce job is done, the result from each reducer is stored in a separate file. The final count of rows is the sum of numbers returned by all reducers. you can get the final count of rows as follows:

    $HADOOP_HOME/bin/hadoop fs -cat <output_path>/* | paste -sd+ | bc
    

    How to use pip on windows behind an authenticating proxy

    I had the same issue on a remote windows environment. I tried many solutions found here or on other similars posts but nothing worked. Finally, the solution was quite simple. I had to set NO_PROXY with cmd :

    set NO_PROXY="<domain>\<username>:<password>@<host>:<port>"
    pip install <packagename>
    

    You have to use double quotes and set NO_PROXY to upper case. You can also add NO_PROXY as an environment variable instead of setting it each time you use the console.

    I hope this will help if any other solution posted here works.

    How to implement reCaptcha for ASP.NET MVC?

    I have added reCaptcha to a project I'm currently working on. I needed it to use the AJAX API as the reCaptcha element was loaded into the page dynamically. I couldn't find any existing controls and the API is simple so I created my own.

    I'll post my code here in case anyone finds it useful.

    1: Add the script tag to the master page headers

    <script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
    

    2: Add your keys to the web.config

    <appSettings>
        <add key="ReCaptcha.PrivateKey" value="[key here]" />
        <add key="ReCaptcha.PublicKey" value="[key here]" />
    </appSettings>
    

    3: Create the Action Attribute and Html Helper extensions

    namespace [Your chosen namespace].ReCaptcha
    {
        public enum Theme { Red, White, BlackGlass, Clean }
    
        [Serializable]
        public class InvalidKeyException : ApplicationException
        {
            public InvalidKeyException() { }
            public InvalidKeyException(string message) : base(message) { }
            public InvalidKeyException(string message, Exception inner) : base(message, inner) { }
        }
    
        public class ReCaptchaAttribute : ActionFilterAttribute
        {
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                var userIP = filterContext.RequestContext.HttpContext.Request.UserHostAddress;
    
                var privateKey = ConfigurationManager.AppSettings.GetString("ReCaptcha.PrivateKey", "");
    
                if (string.IsNullOrWhiteSpace(privateKey))
                    throw new InvalidKeyException("ReCaptcha.PrivateKey missing from appSettings");
    
                var postData = string.Format("&privatekey={0}&remoteip={1}&challenge={2}&response={3}",
                                             privateKey,
                                             userIP,
                                             filterContext.RequestContext.HttpContext.Request.Form["recaptcha_challenge_field"],
                                             filterContext.RequestContext.HttpContext.Request.Form["recaptcha_response_field"]);
    
                var postDataAsBytes = Encoding.UTF8.GetBytes(postData);
    
                // Create web request
                var request = WebRequest.Create("http://www.google.com/recaptcha/api/verify");
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = postDataAsBytes.Length;
                var dataStream = request.GetRequestStream();
                dataStream.Write(postDataAsBytes, 0, postDataAsBytes.Length);
                dataStream.Close();
    
                // Get the response.
                var response = request.GetResponse();
    
                using (dataStream = response.GetResponseStream())
                {
                    using (var reader = new StreamReader(dataStream))
                    {
                        var responseFromServer = reader.ReadToEnd();
    
                        if (!responseFromServer.StartsWith("true"))
                            ((Controller)filterContext.Controller).ModelState.AddModelError("ReCaptcha", "Captcha words typed incorrectly");
                    }
                }
            }
        }
    
        public static class HtmlHelperExtensions
        {
            public static MvcHtmlString GenerateCaptcha(this HtmlHelper helper, Theme theme, string callBack = null)
            {
                const string htmlInjectString = @"<div id=""recaptcha_div""></div>
    <script type=""text/javascript"">
        Recaptcha.create(""{0}"", ""recaptcha_div"", {{ theme: ""{1}"" {2}}});
    </script>";
    
                var publicKey = ConfigurationManager.AppSettings.GetString("ReCaptcha.PublicKey", "");
    
                if (string.IsNullOrWhiteSpace(publicKey))
                    throw new InvalidKeyException("ReCaptcha.PublicKey missing from appSettings");
    
                if (!string.IsNullOrWhiteSpace(callBack))
                    callBack = string.Concat(", callback: ", callBack);
    
                var html = string.Format(htmlInjectString, publicKey, theme.ToString().ToLower(), callBack);
                return MvcHtmlString.Create(html);
            }
        }
    }
    

    4: Add the captcha to your view

    @using (Html.BeginForm("MyAction", "MyController"))
    {
       @Html.TextBox("EmailAddress", Model.EmailAddress)
       @Html.GenerateCaptcha(Theme.White)
       <input type="submit" value="Submit" />
    }
    

    5: Add the attribute to your action

    [HttpPost]
    [ReCaptcha]
    public ActionResult MyAction(MyModel model)
    {
       if (!ModelState.IsValid) // Will have a Model Error "ReCaptcha" if the user input is incorrect
          return Json(new { capthcaInvalid = true });
    
       ... other stuff ...
    }
    

    6: Note you will need to reload the captcha after each post even if it was valid and another part of the form was invalid. Use Recaptcha.reload();

    How do I remove the file suffix and path portion from a path string in Bash?

    Beware of the suggested perl solution: it removes anything after the first dot.

    $ echo some.file.with.dots | perl -pe 's/\..*$//;s{^.*/}{}'
    some
    

    If you want to do it with perl, this works:

    $ echo some.file.with.dots | perl -pe 's/(.*)\..*$/$1/;s{^.*/}{}'
    some.file.with
    

    But if you are using Bash, the solutions with y=${x%.*} (or basename "$x" .ext if you know the extension) are much simpler.

    Sum all the elements java arraylist

    Using Java 8 streams:

    double sum = m.stream()
        .mapToDouble(a -> a)
        .sum();
    
    System.out.println(sum); 
    

    Run as java application option disabled in eclipse

    I had this same problem. For me, the reason turned out to be that I had a mismatch in the name of the class and the name of the file. I declared class "GenSig" in a file called "SignatureTester.java".

    I changed the name of the class to "SignatureTester", and the "Run as Java Application" option showed up immediately.

    Best way to extract a subvector from a vector?

    Posting this late just for others..I bet the first coder is done by now. For simple datatypes no copy is needed, just revert to good old C code methods.

    std::vector <int>   myVec;
    int *p;
    // Add some data here and set start, then
    p=myVec.data()+start;
    

    Then pass the pointer p and a len to anything needing a subvector.

    notelen must be!! len < myVec.size()-start

    What is the best way to conditionally apply a class?

    I am new to Angular but have found this to solve my issue:

    <i class="icon-download" ng-click="showDetails = ! showDetails" ng-class="{'icon-upload': showDetails}"></i>
    

    This will conditionally apply a class based on a var. It starts off with a icon-download as a default, the using ng-class, I check the status of showDetails if true/false and apply class icon-upload. Its working great.

    Hope it helps.

    Javascript to stop HTML5 video playback on modal window close

    Try this:

    $(document).ready(function(){
        $("#showSimpleModal").click(function() {
            $("div#simpleModal").addClass("show");
            $("#videoContainer")[0].play();
            return false;   
        });
    
        $("#closeSimple").click(function() {
            $("div#simpleModal").removeClass("show");
            $("#videoContainer")[0].pause();
            return false;                   
        });
    });
    

    JAX-WS client : what's the correct path to access the local WSDL?

    One other approach that we have taken successfully is to generate the WS client proxy code using wsimport (from Ant, as an Ant task) and specify the wsdlLocation attribute.

    <wsimport debug="true" keep="true" verbose="false" target="2.1" sourcedestdir="${generated.client}" wsdl="${src}${wsdl.file}" wsdlLocation="${wsdl.file}">
    </wsimport>
    

    Since we run this for a project w/ multiple WSDLs, the script resolves the $(wsdl.file} value dynamically which is set up to be /META-INF/wsdl/YourWebServiceName.wsdl relative to the JavaSource location (or /src, depending on how you have your project set up). During the build proess, the WSDL and XSDs files are copied to this location and packaged in the JAR file. (similar to the solution described by Bhasakar above)

    MyApp.jar
    |__META-INF
       |__wsdl
          |__YourWebServiceName.wsdl
          |__YourWebServiceName_schema1.xsd
          |__YourWebServiceName_schmea2.xsd
    

    Note: make sure the WSDL files are using relative refrerences to any imported XSDs and not http URLs:

      <types>
        <xsd:schema>
          <xsd:import namespace="http://valueobject.common.services.xyz.com/" schemaLocation="YourWebService_schema1.xsd"/>
        </xsd:schema>
        <xsd:schema>
          <xsd:import namespace="http://exceptions.util.xyz.com/" schemaLocation="YourWebService_schema2.xsd"/>
        </xsd:schema>
      </types>
    

    In the generated code, we find this:

    /**
     * This class was generated by the JAX-WS RI.
     * JAX-WS RI 2.2-b05-
     * Generated source version: 2.1
     * 
     */
    @WebServiceClient(name = "YourService", targetNamespace = "http://test.webservice.services.xyz.com/", wsdlLocation = "/META-INF/wsdl/YourService.wsdl")
    public class YourService_Service
        extends Service
    {
    
        private final static URL YOURWEBSERVICE_WSDL_LOCATION;
        private final static WebServiceException YOURWEBSERVICE_EXCEPTION;
        private final static QName YOURWEBSERVICE_QNAME = new QName("http://test.webservice.services.xyz.com/", "YourService");
    
        static {
            YOURWEBSERVICE_WSDL_LOCATION = com.xyz.services.webservice.test.YourService_Service.class.getResource("/META-INF/wsdl/YourService.wsdl");
            WebServiceException e = null;
            if (YOURWEBSERVICE_WSDL_LOCATION == null) {
                e = new WebServiceException("Cannot find '/META-INF/wsdl/YourService.wsdl' wsdl. Place the resource correctly in the classpath.");
            }
            YOURWEBSERVICE_EXCEPTION = e;
        }
    
        public YourService_Service() {
            super(__getWsdlLocation(), YOURWEBSERVICE_QNAME);
        }
    
        public YourService_Service(URL wsdlLocation, QName serviceName) {
            super(wsdlLocation, serviceName);
        }
    
        /**
         * 
         * @return
         *     returns YourService
         */
        @WebEndpoint(name = "YourServicePort")
        public YourService getYourServicePort() {
            return super.getPort(new QName("http://test.webservice.services.xyz.com/", "YourServicePort"), YourService.class);
        }
    
        /**
         * 
         * @param features
         *     A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy.  Supported features not in the <code>features</code> parameter will have their default values.
         * @return
         *     returns YourService
         */
        @WebEndpoint(name = "YourServicePort")
        public YourService getYourServicePort(WebServiceFeature... features) {
            return super.getPort(new QName("http://test.webservice.services.xyz.com/", "YourServicePort"), YourService.class, features);
        }
    
        private static URL __getWsdlLocation() {
            if (YOURWEBSERVICE_EXCEPTION!= null) {
                throw YOURWEBSERVICE_EXCEPTION;
            }
            return YOURWEBSERVICE_WSDL_LOCATION;
        }
    
    }
    

    Perhaps this might help too. It's just a different approach that does not use the "catalog" approach.

    int to hex string

    Try C# string interpolation introduced in C# 6:

    var id = 100;
    var hexid = $"0x{id:X}";
    

    hexid value:

    "0x64"
    

    How to define dimens.xml for every different screen size in android?

    You can put dimens.xml in

    1) values

    2) values-hdpi

    3) values-xhdpi

    4) values-xxhdpi

    And give different sizes in dimens.xml within corresponding folders according to densities.

    How to discard local commits in Git?

    git reset --hard origin/master
    

    will remove all commits not in origin/master where origin is the repo name and master is the name of the branch.

    How to do a PUT request with curl?

    Using the -X flag with whatever HTTP verb you want:

    curl -X PUT -d arg=val -d arg2=val2 localhost:8080
    

    This example also uses the -d flag to provide arguments with your PUT request.

    Extract the first (or last) n characters of a string

    Make it simple and use R basic functions:

    # To get the LEFT part:
    > substr(a, 1, 4)
    [1] "left"
    > 
    # To get the MIDDLE part:
    > substr(a, 3, 7)
    [1] "ftrig"
    > 
    # To get the RIGHT part:
    > substr(a, 5, 10)
    [1] "right"
    

    The substr() function tells you where start and stop substr(x, start, stop)

    Installing packages in Sublime Text 2

    Try using Sublime Package Control to install your packages.

    Also take a look at these tips

    How to uninstall jupyter

    In my case, I have installed it via pip3 on mac.

    pip3 uninstall notebook
    

    How do I create a multiline Python string with inline variables?

    If anyone came here from python-graphql client looking for a solution to pass an object as variable here's what I used:

    query = """
    {{
      pairs(block: {block} first: 200, orderBy: trackedReserveETH, orderDirection: desc) {{
        id
        txCount
        reserveUSD
        trackedReserveETH
        volumeUSD
      }}
    }}
    """.format(block=''.join(['{number: ', str(block), '}']))
    
     query = gql(query)
    

    Make sure to escape all curly braces like I did: "{{", "}}"

    subtract time from date - moment js

    There is a simple function subtract which moment library gives us to subtract time from some time. Using it is also very simple.

    moment(Date.now()).subtract(7, 'days'); // This will subtract 7 days from current time
    moment(Date.now()).subtract(3, 'd'); // This will subtract 3 days from current time
    
    //You can do this for days, years, months, hours, minutes, seconds
    //You can also subtract multiple things simulatneously
    
    //You can chain it like this.
    moment(Date.now()).subtract(3, 'd').subtract(5. 'h'); // This will subtract 3 days and 5 hours from current time
    
    //You can also use it as object literal
    moment(Date.now()).subtract({days:3, hours:5}); // This will subtract 3 days and 5 hours from current time
    

    Hope this helps!

    "Press Any Key to Continue" function in C

    Try this:-

    printf("Let the Battle Begin!\n");
    printf("Press Any Key to Continue\n");
    getch();
    

    getch() is used to get a character from console but does not echo to the screen.

    What is username and password when starting Spring Boot with Tomcat?

    I think that you have Spring Security on your class path and then spring security is automatically configured with a default user and generated password

    Please look into your pom.xml file for:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    

    If you have that in your pom than you should have a log console message like this:

    Using default security password: ce6c3d39-8f20-4a41-8e01-803166bb99b6

    And in the browser prompt you will import the user user and the password printed in the console.

    Or if you want to configure spring security you can take a look at Spring Boot secured example

    It is explained in the Spring Boot Reference documentation in the Security section, it indicates:

    The default AuthenticationManager has a single user (‘user’ username and random password, printed at `INFO` level when the application starts up)
    
    Using default security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35
    

    Angularjs on page load call function

    You should call this function from the controller.

    angular.module('App', [])
      .controller('CinemaCtrl', ['$scope', function($scope) {
        myFunction();
      }]);
    

    Even with normal javascript/html your function won't run on page load as all your are doing is defining the function, you never call it. This is really nothing to do with angular, but since you're using angular the above would be the "angular way" to invoke the function.

    Obviously better still declare the function in the controller too.

    Edit: Actually I see your "onload" - that won't get called as angular injects the HTML into the DOM. The html is never "loaded" (or the page is only loaded once).

    Colon (:) in Python list index

    a[len(a):] - This gets you the length of a to the end. It selects a range. If you reverse a[:len(a)] it will get you the beginning to whatever is len(a).

    Checking if a key exists in a JS object

    That's not a jQuery object, it's just an object.

    You can use the hasOwnProperty method to check for a key:

    if (obj.hasOwnProperty("key1")) {
      ...
    }
    

    How to merge two files line by line in Bash

    Check

    man paste
    

    possible followed by some command like untabify or tabs2spaces

    ImportError: No module named MySQLdb

    Or try this:

    apt-get install python-mysqldb
    

    How to align LinearLayout at the center of its parent?

    add layout_gravity="center" or "center_horizontal" to the parent layout.

    On a side note, your LinearLayout inside your TableRow seems un-necessary, as a TableRow is already an horizontal LinearLayout.

    Simulate limited bandwidth from within Chrome?

    Starting with Chrome 38 you can do this without any plugins. Just click inspect element (or F12 hotkey), then click on toggle device mod (the phone button)

    enter image description here

    and you will see something like this:

    enter image description here

    Among many other features it allows you to simulate specific internet connection (3G, GPRS)

    What are Transient and Volatile Modifiers?

    Transient :

    First need to know where it needed how it bridge the gap.

    1) An Access modifier transient is only applicable to variable component only. It will not used with method or class.

    2) Transient keyword cannot be used along with static keyword.

    3) What is serialization and where it is used? Serialization is the process of making the object's state persistent. That means the state of the object is converted into a stream of bytes to be used for persisting (e.g. storing bytes in a file) or transferring (e.g. sending bytes across a network). In the same way, we can use the deserialization to bring back the object's state from bytes. This is one of the important concepts in Java programming because serialization is mostly used in networking programming. The objects that need to be transmitted through the network have to be converted into bytes. Before understanding the transient keyword, one has to understand the concept of serialization. If the reader knows about serialization, please skip the first point.

    Note 1) Transient is mainly use for serialzation process. For that the class must implement the java.io.Serializable interface. All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

    Note 2) When deserialized process taken place they get set to the default value - zero, false, or null as per type constraint.

    Note 3) Transient keyword and its purpose? A field which is declare with transient modifier it will not take part in serialized process. When an object is serialized(saved in any state), the values of its transient fields are ignored in the serial representation, while the field other than transient fields will take part in serialization process. That is the main purpose of the transient keyword.

    Dart SDK is not configured

    After installing Flutter, the best way to install Dart sdk is by creating a new project. In this window, click INSTALL SDK. This installs all necessary to work properly.

    Counting lines, words, and characters within a text file using Python

    One of the way I like is this one , but may be good for small files

    with open(fileName,'r') as content_file:
        content = content_file.read()
        lineCount = len(re.split("\n",content))
        words = re.split("\W+",content.lower())
    

    To count words, there is two way, if you don't care about repetition you can just do

    words_count = len(words)
    

    if you want the counts of each word you can just do

    import collections
    words_count = collections.Counter(words) #Count the occurrence of each word
    

    class << self idiom in Ruby

    ? singleton method is a method that is defined only for a single object.

    Example:

    class SomeClass
      class << self
        def test
        end
      end
    end
    
    test_obj = SomeClass.new
    
    def test_obj.test_2
    end
    
    class << test_obj
      def test_3
      end
    end
    
    puts "Singleton's methods of SomeClass"
    puts SomeClass.singleton_methods
    puts '------------------------------------------'
    puts "Singleton's methods of test_obj"
    puts test_obj.singleton_methods
    

    Singleton's methods of SomeClass

    test


    Singleton's methods of test_obj

    test_2

    test_3

    How to install sshpass on mac?

    Some years have passed and there is now a proper Homebrew Tap for sshpass, maintained by Aleks Hudochenkov. To install sshpass from this tap, run:

    brew install hudochenkov/sshpass/sshpass
    

    How to playback MKV video in web browser?

    HTML5 and the VLC web plugin were a no go for me but I was able to get this work using the following setup:

    DivX Web Player (NPAPI browsers only)

    AC3 Audio Decoder

    And here is the HTML:

    <embed id="divxplayer" type="video/divx" width="1024" height="768" 
    src ="path_to_file" autoPlay=\"true\" 
    pluginspage=\"http://go.divx.com/plugin/download/\"></embed>
    

    The DivX player seems to allow for a much wider array of video and audio options than the native HTML5, so far I am very impressed by it.

    Setting the target version of Java in ant javac

    You may also set {{ant.build.javac.target=1.5}} ant property to update default target version of task. See http://ant.apache.org/manual/javacprops.html#target

    Why this line xmlns:android="http://schemas.android.com/apk/res/android" must be the first in the layout xml file?

    I think it makes clear with the namespace, as we can create our own attributes and if the user specified attribute is the same as the Android one it avoid the conflict of the namespace.

    Can anyone explain python's relative imports?

    You are importing from package "sub". start.py is not itself in a package even if there is a __init__.py present.

    You would need to start your program from one directory over parent.py:

    ./start.py
    
    ./pkg/__init__.py
    ./pkg/parent.py
    ./pkg/sub/__init__.py
    ./pkg/sub/relative.py
    

    With start.py:

    import pkg.sub.relative
    

    Now pkg is the top level package and your relative import should work.


    If you want to stick with your current layout you can just use import parent. Because you use start.py to launch your interpreter, the directory where start.py is located is in your python path. parent.py lives there as a separate module.

    You can also safely delete the top level __init__.py, if you don't import anything into a script further up the directory tree.

    Difference between numeric, float and decimal in SQL Server

    use the float or real data types only if the precision provided by decimal (up to 38 digits) is insufficient

    • Approximate numeric data types do not store the exact values specified for many numbers; they store an extremely close approximation of the value.(Technet)

    • Avoid using float or real columns in WHERE clause search conditions, especially the = and <> operators (Technet)

    so generally because the precision provided by decimal is [10E38 ~ 38 digits] if your number can fit in it, and smaller storage space (and maybe speed) of Float is not important and dealing with abnormal behaviors and issues of approximate numeric types are not acceptable, use Decimal generally.

    more useful information

    • numeric = decimal (5 to 17 bytes) (Exact Numeric Data Type)
      • will map to Decimal in .NET
      • both have (18, 0) as default (precision,scale) parameters in SQL server
      • scale = maximum number of decimal digits that can be stored to the right of the decimal point.
      • kindly note that money(8 byte) and smallmoney(4 byte) are also exact and map to Decimal In .NET and have 4 decimal points(MSDN)
      • decimal and numeric (Transact-SQL) - MSDN
    • real (4 byte) (Approximate Numeric Data Type)
    • float (8 byte) (Approximate Numeric Data Type)
      • will map to Double in .NET
    • All exact numeric types always produce the same result, regardless of which kind of processor architecture is being used or the magnitude of the numbers
    • The parameter supplied to the float data type defines the number of bits that are used to store the mantissa of the floating point number.
    • Approximate Numeric Data Type usually uses less storage and have better speed (up to 20x) and you should also consider when they got converted in .NET

    Exact Numeric Data Types Approximate Numeric Data Types

    main source : MCTS Self-Paced Training Kit (Exam 70-433): Microsoft® SQL Server® 2008 Database Development - Chapter 3 - Tables , Data Types , and Declarative Data Integrity Lesson 1 - Choosing Data Types (Guidelines) - Page 93