Programs & Examples On #Shared directory

Virtualbox shared folder permissions

The issue is that the shared folder's permissions are set to not allow symbolic links by default. You can enable them in a few easy steps.

  1. Shut down the virtual machine.
  2. Note your machine name at Machine > Settings > General > Name
  3. Note your shared folder name at 'Machine > Settings > Shared Folders`
  4. Find your VirtualBox root directory and execute the following command. VBoxManage setextradata "" VBoxInternal2/SharedFoldersEnableSymlinksCreate/ 1
  5. Start up the virtual machine and the shared folder will now allow symbolic links.

How do I remove newlines from a text file?

Was having the same case today, super easy in vim or nvim, you can use gJ to join lines. For your use case, just do

99gJ

this will join all your 99 lines. You can adjust the number 99 as need according to how many lines to join. If just join 1 line, then only gJ is good enough.

Cygwin - Makefile-error: recipe for target `main.o' failed

You see the two empty -D entries in the g++ command line? They're causing the problem. You must have values in the -D items e.g. -DWIN32

if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers

just to clarify, what actually got sent to g++ was -D -DWindows_NT, i.e. define a preprocessor macro called -DWindows_NT; which is of course not a valid identifier (similarly for -D -I.)

How to clear all <div>s’ contents inside a parent <div>?

$("#masterdiv div[id^='childdiv']").each(function(el){$(el).empty();});

or

$("#masterdiv").find("div[id^='childdiv']").each(function(el){$(el).empty();});

Maven dependency update on commandline

mvn clean install -U

-U means force update of dependencies.

Also, if you want to import the project into eclipse, I first run:

mvn eclipse:eclipse

then run

mvn eclipse:clean

Seems to work for me, but that's just my pennies worth.

Select a date from date picker using Selenium webdriver

Here's a tidy solution where you provide the target date as a Calendar object.

// Used to translate the Month value of a JQuery calendar to the month value expected by a Calendar.
private static final Map<String,Integer> MONTH_TO_CALENDAR_INDEX = new HashMap<String,Integer>();
static {
    MONTH_TO_CALENDAR_INDEX.put("January",  0);
    MONTH_TO_CALENDAR_INDEX.put("February",1);
    MONTH_TO_CALENDAR_INDEX.put("March",2);
    MONTH_TO_CALENDAR_INDEX.put("April",3);
    MONTH_TO_CALENDAR_INDEX.put("May",4);
    MONTH_TO_CALENDAR_INDEX.put("June",5);
    MONTH_TO_CALENDAR_INDEX.put("July",6);
    MONTH_TO_CALENDAR_INDEX.put("August",7);
    MONTH_TO_CALENDAR_INDEX.put("September",8);
    MONTH_TO_CALENDAR_INDEX.put("October",9);
    MONTH_TO_CALENDAR_INDEX.put("November",10);
    MONTH_TO_CALENDAR_INDEX.put("December",11);
}

        // ====================================================================================================
        // setCalendarPicker
        // ====================================================================================================

        /**
         * Sets the value of specified web element while assuming the element is a JQuery calendar.
         * @param byOpen The By phrase that locates the control that opens the JQuery calendar when clicked.
         * @param byPicker The By phrase that locates the JQuery calendar.
         * @param targetDate The target date that you want set.
         * @throws AssertionError if the method is unable to set the date.
         */

        public void setCalendarPicker(By byOpen, By byPicker, Calendar targetDate) {

            // Open the JQuery calendar.
            WebElement opener = driver.findElement(byOpen);
            opener.click();

            // Locate the JQuery calendar.
            WebElement picker = driver.findElement(byPicker);

            // Calculate the target and current year-and-month as an integer where value = year*12+month.
            // The difference between the two is the number of months we have to move ahead or backward.
            int targetYearMonth = targetDate.get(Calendar.YEAR) * 12 + targetDate.get(Calendar.MONTH);
            int currentYearMonth = Integer.valueOf(picker.findElement(By.className("ui-datepicker-year")).getText()) * 12
                    + Integer.valueOf(MONTH_TO_CALENDAR_INDEX.get(picker.findElement(By.className("ui-datepicker-month")).getText()));
            // Calculate the number of months we need to move the JQuery calendar.
            int delta = targetYearMonth - currentYearMonth;
            // As a sanity check, let's not allow more than 10 years so that we don't inadvertently spin in a loop for zillions of months.
            if (Math.abs(delta) > 120) throw new AssertionError("Target date is more than 10 years away");

            // Push the JQuery calendar forward or backward as appropriate.
            if (delta > 0) {
                while (delta-- > 0) picker.findElement(By.className("ui-icon-circle-triangle-e")).click();
            } else if (delta < 0 ){
                while (delta++ < 0) picker.findElement(By.className("ui-icon-circle-triangle-w")).click();
            }

            // Select the day within the month.
            String dayOfMonth = String.valueOf(targetDate.get(Calendar.DAY_OF_MONTH));
            WebElement tableOfDays = picker.findElement(By.cssSelector("tbody:nth-child(2)"));
            for (WebElement we : tableOfDays.findElements(By.tagName("td"))) {
                if (dayOfMonth.equals(we.getText())) {
                    we.click();

                    // Send a tab to completely leave this control.  If the next control the user will access is another CalendarPicker,
                    // the picker might not get selected properly if we stay on the current control.
                    opener.sendKeys("\t");

                    return;
                }
            }

            throw new AssertionError(String.format("Unable to select specified day"));
        }

Command line tool to dump Windows DLL version?

and one way with makecab:

; @echo off
;;goto :end_help
;;setlocal DsiableDelayedExpansion
;;;
;;;
;;; fileinf /l list of full file paths separated with ;
;;; fileinf /f text file with a list of files to be processed ( one on each line )
;;; fileinf /? prints the help
;;;
;;:end_help

; REM Creating a Newline variable (the two blank lines are required!)
; set NLM=^


; set NL=^^^%NLM%%NLM%^%NLM%%NLM%
; if "%~1" equ "/?" type "%~f0" | find ";;;" | find /v "find" && exit /b 0
; if "%~2" equ "" type "%~f0" | find ";;;" | find /v "find" && exit /b 0
; setlocal enableDelayedExpansion
; if "%~1" equ "/l" (
;  set "_files=%~2"
;  echo !_files:;=%NL%!>"%TEMP%\file.paths"
;  set _process_file="%TEMP%\file.paths"
;  goto :get_info
; )

; if "%~1" equ "/f" if exist "%~2" (
;  set _process_file="%~2"
;  goto :get_info
; )

; echo incorect parameters & exit /b 1
; :get_info
; set "file_info="

; makecab /d InfFileName=%TEMP%\file.inf /d "DiskDirectory1=%TEMP%" /f "%~f0"  /f %_process_file% /v0>nul

; for /f "usebackq skip=4 delims=" %%f in ("%TEMP%\file.inf") do (
;  set "file_info=%%f"
;  echo !file_info:,=%nl%!
; )

; endlocal
;endlocal
; del /q /f %TEMP%\file.inf 2>nul
; del /q /f %TEMP%\file.path 2>nul
; exit /b 0

.set DoNotCopyFiles=on
.set DestinationDir=;
.set RptFileName=nul
.set InfFooter=;
.set InfHeader=;
.Set ChecksumWidth=8
.Set InfDiskLineFormat=;
.Set Cabinet=off
.Set Compress=off
.Set GenerateInf=ON
.Set InfDiskHeader=;
.Set InfFileHeader=;
.set InfCabinetHeader=;
.Set InfFileLineFormat=",file:*file*,date:*date*,size:*size*,csum:*csum*,time:*time*,vern:*ver*,vers:*vers*,lang:*lang*"

example output (it has a string version which is a small addition to wmic method :) ):

c:> fileinfo.bat /l C:\install.exe
    file:install.exe
    date:11/07/07
    size:562688
    csum:380ef239
    time:07:03:18a
    vern:9.0.21022.8
    vers:9.0.21022.8 built by: RTM
    lang:1033

and one more Using shell.application and hybrid batch\jscript.Here's tooptipInfo.bat :

@if (@X)==(@Y) @end /* JScript comment
    @echo off

    rem :: the first argument is the script name as it will be used for proper help message
    cscript //E:JScript //nologo "%~f0" %*

    exit /b %errorlevel%

@if (@X)==(@Y) @end JScript comment */

////// 
FSOObj = new ActiveXObject("Scripting.FileSystemObject");
var ARGS = WScript.Arguments;
if (ARGS.Length < 1 ) {
 WScript.Echo("No file passed");
 WScript.Quit(1);
}
var filename=ARGS.Item(0);
var objShell=new ActiveXObject("Shell.Application");
/////


//fso
ExistsItem = function (path) {
    return FSOObj.FolderExists(path)||FSOObj.FileExists(path);
}

getFullPath = function (path) {
    return FSOObj.GetAbsolutePathName(path);
}
//

//paths
getParent = function(path){
    var splitted=path.split("\\");
    var result="";
    for (var s=0;s<splitted.length-1;s++){
        if (s==0) {
            result=splitted[s];
        } else {
            result=result+"\\"+splitted[s];
        }
    }
    return result;
}


getName = function(path){
    var splitted=path.split("\\");
    return splitted[splitted.length-1];
}
//

function main(){
    if (!ExistsItem(filename)) {
        WScript.Echo(filename + " does not exist");
        WScript.Quit(2);
    }
    var fullFilename=getFullPath(filename);
    var namespace=getParent(fullFilename);
    var name=getName(fullFilename);
    var objFolder=objShell.NameSpace(namespace);
    var objItem=objFolder.ParseName(name);
    //https://msdn.microsoft.com/en-us/library/windows/desktop/bb787870(v=vs.85).aspx
    WScript.Echo(fullFilename + " : ");
    WScript.Echo(objFolder.GetDetailsOf(objItem,-1));

}

main();

used against cmd.exe :

C:\Windows\System32\cmd.exe :
File description: Windows Command Processor
Company: Microsoft Corporation
File version: 6.3.9600.16384
Date created: ?22-?Aug-?13 ??13:03
Size: 347 KB

Change link color of the current page with CSS

JavaScript will get the job done.

Get all links in the document and compare their reference URLs to the document's URL. If there is a match, add a class to that link.

JavaScript

<script>
    currentLinks = document.querySelectorAll('a[href="'+document.URL+'"]')
    currentLinks.forE??ach(function(link) {
        link.className += ' current-link')
    });
</script>

One Liner Version of Above

document.querySelectorAll('a[href="'+document.URL+'"]').forE??ach(function(elem){e??lem.className += ' current-link')});

CSS

.current-link {
    color:#baada7;
}

Other Notes

Taraman's jQuery answer above only searches on [href] which will return link tags and tags other than a which rely on the href attribute. Searching on a[href='*https://urlofcurrentpage.com*'] captures only those links which meets the criteria and therefore runs faster.

In addtion, if you don't need to rely on the jQuery library, a vanilla JavaScript solution is definitely the way to go.

How to import and use image in a Vue single file component?

These both work for me in JavaScript and TypeScript

<img src="@/assets/images/logo.png" alt=""> 

or

 <img src="./assets/images/logo.png" alt="">

How does the communication between a browser and a web server take place?

Your browser is sitting on top of TCP/IP, as the web is based on standards, usually port 80, what happens is when you enter an address, such as google.com, your computer where the browser is running on, creates packets of data, encapsulated at each layer accordingly to the OSI standards, (think of envelopes of different sizes, packed into each envelope of next size), OSI defines 7 layers, in one of the envelopes contains the source address and destination address(that is the website) encoded in binary.

As it reaches the 1st layer, in OSI terms, it gets transmitted across the media transmitter (such as cable, DSL).

If you are connected via ISP, the layered pack of envelopes gets transmitted to the ISP, the ISP's network system, peeks through the layered pack of envelopes by decoding in reverse order to find out the address, then the ISP checks their Domain Name System database to find out if they have a route to that address (cached in memory, if it does, it forwards it across the internet network - again layered pack of envelopes).

If it doesn't, the ISP interrogates the top level DNS server to say 'Hey, get me the route for the address as supplied by you, ie. the browser', the top level DNS server then passes the route to the ISP which is then stored in the ISP's server memory.

The layered pack of envelopes are transmitted and received by the website server after successful routing of the packets (think of routing as signposts for directions to get to the server), which in turn, unpacks the layered pack of envelopes, extracts the source address and says 'Aha, that is for me, right, I know the destination address (that is you, the browser), then the server packetizes the webpages into a packed layered envelopes and sends it back (usually in reverse route, but not always the case).

Your browser than receives the packetized envelopes and unpacks each of them. Then your computer descrambles the data and your browser renders the pages on the screen.

I hope this answer is sufficient enough for your understanding.

How do I see which version of Swift I'm using?

Updated answer for how to find which version of Swift your project is using in a few click in Xcode 12 to help out rookies like me.

  1. Click on your Project (top level Blue Icon in the left hand pane)
  2. Click on Build Settings (5th item in the Project > Header)
  3. Scroll down to Swift Compiler - Language, and look at the dropdown.

enter image description here

Can you append strings to variables in PHP?

This is because PHP uses the period character . for string concatenation, not the plus character +. Therefore to append to a string you want to use the .= operator:

for ($i=1;$i<=100;$i++)
{
    $selectBox .= '<option value="' . $i . '">' . $i . '</option>';
}
$selectBox .= '</select>';

Multiple rows to one comma-separated value in Sql Server

Test Data

DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)

Query

SELECT  ID
       ,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
         FROM @Table1 
         WHERE ID = t.ID
         FOR XML PATH(''), TYPE)
        .value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

SQL Server 2017 and Later Versions

If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:

DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);


SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

Controlling execution order of unit tests in Visual Studio

Here is a class that can be used to setup and run ordered tests independent of MS Ordered Tests framework for whatever reason--like not have to adjust mstest.exe arguments on a build machine, or mixing ordered with non-ordered in a class.

The original testing framework only sees the list of ordered tests as a single test so any init/cleanup like [TestInitalize()] Init() is only called before and after the entire set.

Usage:

        [TestMethod] // place only on the list--not the individuals
        public void OrderedStepsTest()
        {
            OrderedTest.Run(TestContext, new List<OrderedTest>
            {
                new OrderedTest ( T10_Reset_Database, false ),
                new OrderedTest ( T20_LoginUser1, false ),
                new OrderedTest ( T30_DoLoginUser1Task1, true ), // continue on failure
                new OrderedTest ( T40_DoLoginUser1Task2, true ), // continue on failure
                // ...
            });                
        }

Implementation:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace UnitTests.Utility
{    
    /// <summary>
    /// Define and Run a list of ordered tests. 
    /// 2016/08/25: Posted to SO by crokusek 
    /// </summary>    
    public class OrderedTest
    {
        /// <summary>Test Method to run</summary>
        public Action TestMethod { get; private set; }

        /// <summary>Flag indicating whether testing should continue with the next test if the current one fails</summary>
        public bool ContinueOnFailure { get; private set; }

        /// <summary>Any Exception thrown by the test</summary>
        public Exception ExceptionResult;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="testMethod"></param>
        /// <param name="continueOnFailure">True to continue with the next test if this test fails</param>
        public OrderedTest(Action testMethod, bool continueOnFailure = false)
        {
            TestMethod = testMethod;
            ContinueOnFailure = continueOnFailure;
        }

        /// <summary>
        /// Run the test saving any exception within ExceptionResult
        /// Throw to the caller only if ContinueOnFailure == false
        /// </summary>
        /// <param name="testContextOpt"></param>
        public void Run()
        {
            try
            {
                TestMethod();
            }
            catch (Exception ex)
            {
                ExceptionResult = ex;
                throw;
            }
        }

        /// <summary>
        /// Run a list of OrderedTest's
        /// </summary>
        static public void Run(TestContext testContext, List<OrderedTest> tests)
        {
            Stopwatch overallStopWatch = new Stopwatch();
            overallStopWatch.Start();

            List<Exception> exceptions = new List<Exception>();

            int testsAttempted = 0;
            for (int i = 0; i < tests.Count; i++)
            {
                OrderedTest test = tests[i];

                Stopwatch stopWatch = new Stopwatch();
                stopWatch.Start();

                testContext.WriteLine("Starting ordered test step ({0} of {1}) '{2}' at {3}...\n",
                    i + 1,
                    tests.Count,
                    test.TestMethod.Method,
                    DateTime.Now.ToString("G"));

                try
                {
                    testsAttempted++;
                    test.Run();
                }
                catch
                {
                    if (!test.ContinueOnFailure)
                        break;
                }
                finally
                {
                    Exception testEx = test.ExceptionResult;

                    if (testEx != null)  // capture any "continue on fail" exception
                        exceptions.Add(testEx);

                    testContext.WriteLine("\n{0} ordered test step {1} of {2} '{3}' in {4} at {5}{6}\n",
                        testEx != null ? "Error:  Failed" : "Successfully completed",
                        i + 1,
                        tests.Count,
                        test.TestMethod.Method,
                        stopWatch.ElapsedMilliseconds > 1000
                            ? (stopWatch.ElapsedMilliseconds * .001) + "s"
                            : stopWatch.ElapsedMilliseconds + "ms",
                        DateTime.Now.ToString("G"),
                        testEx != null
                            ? "\nException:  " + testEx.Message +
                                "\nStackTrace:  " + testEx.StackTrace +
                                "\nContinueOnFailure:  " + test.ContinueOnFailure
                            : "");
                }
            }

            testContext.WriteLine("Completed running {0} of {1} ordered tests with a total of {2} error(s) at {3} in {4}",
                testsAttempted,
                tests.Count,
                exceptions.Count,
                DateTime.Now.ToString("G"),
                overallStopWatch.ElapsedMilliseconds > 1000
                    ? (overallStopWatch.ElapsedMilliseconds * .001) + "s"
                    : overallStopWatch.ElapsedMilliseconds + "ms");

            if (exceptions.Any())
            {
                // Test Explorer prints better msgs with this hierarchy rather than using 1 AggregateException().
                throw new Exception(String.Join("; ", exceptions.Select(e => e.Message), new AggregateException(exceptions)));
            }
        }
    }
}

How can I convert an RGB image into grayscale in Python?

you could do:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

def rgb_to_gray(img):
        grayImage = np.zeros(img.shape)
        R = np.array(img[:, :, 0])
        G = np.array(img[:, :, 1])
        B = np.array(img[:, :, 2])

        R = (R *.299)
        G = (G *.587)
        B = (B *.114)

        Avg = (R+G+B)
        grayImage = img

        for i in range(3):
           grayImage[:,:,i] = Avg

        return grayImage       

image = mpimg.imread("your_image.png")   
grayImage = rgb_to_gray(image)  
plt.imshow(grayImage)
plt.show()

Java using enum with switch statement

This should work in the way that you describe. What error are you getting? If you could pastebin your code that would help.

http://download.oracle.com/javase/tutorial/java/javaOO/enum.html

EDIT: Are you sure you want to define a static enum? That doesn't sound right to me. An enum is much like any other object. If your code compiles and runs but gives incorrect results, this would probably be why.

access key and value of object using *ngFor

change demo type to array or iterate over your object and push to another array

public details =[];   
Object.keys(demo).forEach(key => {
      this.details.push({"key":key,"value":demo[key]);
    });

and from html:

<div *ngFor="obj of details">
  <p>{{obj.key}}</p>
  <p>{{obj.value}}</p>
  <p></p>
</div>

What's the common practice for enums in Python?

class Materials:
    Shaded, Shiny, Transparent, Matte = range(4)

>>> print Materials.Matte
3

Add alternating row color to SQL Server Reporting services report

If for the entire report you need an alternating color, you can use the DataSet your Tablix is bound to for a report-wide identity rownumber on the report and use that in the RowNumber function...

=IIf(RowNumber("DataSet1")  Mod 2 = 1, "White","Blue")

changing iframe source with jquery

Should work.

Here's a working example:

http://jsfiddle.net/rhpNc/

Excerpt:

function loadIframe(iframeName, url) {
    var $iframe = $('#' + iframeName);
    if ($iframe.length) {
        $iframe.attr('src',url);
        return false;
    }
    return true;
}

How to return a string value from a Bash function

The most straightforward and robust solution is to use command substitution, as other people wrote:

assign()
{
    local x
    x="Test"
    echo "$x"
}

x=$(assign) # This assigns string "Test" to x

The downside is performance as this requires a separate process.

The other technique suggested in this topic, namely passing the name of a variable to assign to as an argument, has side effects, and I wouldn't recommend it in its basic form. The problem is that you will probably need some variables in the function to calculate the return value, and it may happen that the name of the variable intended to store the return value will interfere with one of them:

assign()
{
    local x
    x="Test"
    eval "$1=\$x"
}

assign y # This assigns string "Test" to y, as expected

assign x # This will NOT assign anything to x in this scope
         # because the name "x" is declared as local inside the function

You might, of course, not declare internal variables of the function as local, but you really should always do it as otherwise you may, on the other hand, accidentally overwrite an unrelated variable from the parent scope if there is one with the same name.

One possible workaround is an explicit declaration of the passed variable as global:

assign()
{
    local x
    eval declare -g $1
    x="Test"
    eval "$1=\$x"
}

If name "x" is passed as an argument, the second row of the function body will overwrite the previous local declaration. But the names themselves might still interfere, so if you intend to use the value previously stored in the passed variable prior to write the return value there, be aware that you must copy it into another local variable at the very beginning; otherwise the result will be unpredictable! Besides, this will only work in the most recent version of BASH, namely 4.2. More portable code might utilize explicit conditional constructs with the same effect:

assign()
{
    if [[ $1 != x ]]; then
      local x
    fi
    x="Test"
    eval "$1=\$x"
}

Perhaps the most elegant solution is just to reserve one global name for function return values and use it consistently in every function you write.

How do you run a Python script as a service in Windows?

Although I upvoted the chosen answer a couple of weeks back, in the meantime I struggled a lot more with this topic. It feels like having a special Python installation and using special modules to run a script as a service is simply the wrong way. What about portability and such?

I stumbled across the wonderful Non-sucking Service Manager, which made it really simple and sane to deal with Windows Services. I figured since I could pass options to an installed service, I could just as well select my Python executable and pass my script as an option.

I have not yet tried this solution, but I will do so right now and update this post along the process. I am also interested in using virtualenvs on Windows, so I might come up with a tutorial sooner or later and link to it here.

ERROR 1064 (42000): You have an error in your SQL syntax;

Try this:

Use back-ticks for NAME

CREATE TABLE `teachers` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `addr` varchar(255) NOT NULL,
  `phone` int(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Cannot delete directory with Directory.Delete(path, true)

It appears that having the path or subfolder selected in Windows Explorer is enough to block a single execution of Directory.Delete(path, true), throwing an IOException as described above and dying instead of booting Windows Explorer out to a parent folder and proceding as expected.

Stacked Tabs in Bootstrap 3

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

UPDATE

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

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

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

How to get option text value using AngularJS?

Also you can do like this:

<select class="form-control postType" ng-model="selectedProd">
    <option ng-repeat="product in productList" value="{{product}}">{{product.name}}</option>
</select>

where "selectedProd" will be selected product.

String replace method is not replacing characters

You should re-assign the result of the replacement, like this:

 sentence = sentence.replace("and", " ");

Be aware that the String class is immutable, meaning that all of its methods return a new string and never modify the original string in-place, so the result of invoking a method in an instance of String must be assigned to a variable or used immediately for the change to take effect.

IntelliJ IDEA 13 uses Java 1.5 despite setting to 1.7

[For IntelliJ IDEA 2016.2]

I would like to expand upon part of Peter Gromov's answer with an up-to-date screenshot. Specifically this particular part:

You might also want to take a look at Settings | Compiler | Java Compiler | Per-module bytecode version.

I believe that (at least in 2016.2): checking out different commits in git resets these to 1.5.

Per-module bytecode version

MSSQL Error 'The underlying provider failed on Open'

This is common issue only. Even I have faced this issue. On the development machine, configured with Windows authentication, it is worked perfectly:

<add name="ShoppingCartAdminEntities" connectionString="metadata=res://*/ShoppingCartAPIModel.csdl|res://*/ShoppingCartAPIModel.ssdl|res://*/ShoppingCartAPIModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\SQlExpress;initial catalog=ShoppingCartAdmin;Integrated Security=True;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" />

Once hosted in IIS with the same configuration, I got this error:

The underlying provider failed on Open

It was solved changing connectionString in the configuration file:

<add name="MyEntities" connectionString="metadata=res://*/ShoppingCartAPIModel.csdl|res://*/ShoppingCartAPIModel.ssdl|res://*/ShoppingCartAPIModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MACHINE_Name\SQlExpress;initial catalog=ShoppingCartAdmin;persist security info=True;user id=sa;password=notmyrealpassword;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" />

Other common mistakes could be:

  1. Database service could be stopped
  2. Data Source attributes pointing to a local database with Windows authentication and hosted in IIS
  3. Username and password could be wrong.

PostgreSQL, checking date relative to "today"

I think this will do it:

SELECT * FROM MyTable WHERE mydate > now()::date - 365;

Convert stdClass object to array in PHP

Very simple, first turn your object into a json object, this will return a string of your object into a JSON representative.

Take that result and decode with an extra parameter of true, where it will convert to associative array

$array = json_decode(json_encode($oObject),true);

How to compile a 32-bit binary on a 64-bit linux machine with gcc/cmake

For C++, you could do:

export CXXFLAGS=-m32

This works with cmake.

Difference between "while" loop and "do while" loop

while test the condition before executing statements in the while loop.

do while test the condition after having executed statement inside the loop.

How to programmatically tell if a Bluetooth device is connected?

There is an isConnected function in BluetoothDevice system API in https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/bluetooth/BluetoothDevice.java

If you want to know if the a bounded(paired) device is currently connected or not, the following function works fine for me:

public static boolean isConnected(BluetoothDevice device) {
    try {
        Method m = device.getClass().getMethod("isConnected", (Class[]) null);
        boolean connected = (boolean) m.invoke(device, (Object[]) null);
        return connected;
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

How to dynamically change header based on AngularJS partial view?

Simplistic solution for angular-ui-router :

HTML :

<html ng-app="myApp">
  <head>
     <title ng-bind="title"></title>
     .....
     .....  
  </head>
</html>

App.js > myApp.config block

$stateProvider
    .state("home", {
        title: "My app title this will be binded in html title",
        url: "/home",
        templateUrl: "/home.html",
        controller: "homeCtrl"
    })

App.js>myApp.run

myApp.run(['$rootScope','$state', function($rootScope,$state) {
   $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
    $rootScope.title = $state.current.title;
    console.log($state);
   });
}]);

When to use Interface and Model in TypeScript / Angular

Interfaces are only at compile time. This allows only you to check that the expected data received follows a particular structure. For this you can cast your content to this interface:

this.http.get('...')
    .map(res => <Product[]>res.json());

See these questions:

You can do something similar with class but the main differences with class are that they are present at runtime (constructor function) and you can define methods in them with processing. But, in this case, you need to instantiate objects to be able to use them:

this.http.get('...')
    .map(res => {
      var data = res.json();
      return data.map(d => {
        return new Product(d.productNumber,
          d.productName, d.productDescription);
      });
    });

Can I set subject/content of email using mailto:?

here is the trick http://neworganizing.com/content/blog/tip-prepopulate-mailto-links-with-subject-body-text

<a href="mailto:[email protected]?subject=Your+tip+on+mailto+links&body=Thanks+for+this+tip">tell a friend</a>

Execute function after Ajax call is complete

Add .done() to your function

var id;
var vname;
function ajaxCall(){
for(var q = 1; q<=10; q++){
 $.ajax({                                            
         url: 'api.php',                        
         data: 'id1='+q+'',                                                         
         dataType: 'json',
         async:false,                    
         success: function(data)          
         {   
            id = data[0];              
            vname = data[1];
         }
      }).done(function(){
           printWithAjax(); 
      });



 }//end of the for statement
}//end of ajax call function

Filter an array using a formula (without VBA)

This will do it if you only want the first "B" value, you can sub a cell address for "B" if you want to make it more generic.

=INDEX(A2:A6,SUMPRODUCT(MATCH(TRUE,(B2:B6)="B",0)),1)

To use this based on two columns, just concatenate inside the match:

=INDEX(A2:A6,SUMPRODUCT(MATCH(TRUE,(A2:A6&B2:B6)=("3"&"B"),0)),1)

How to make a .jar out from an Android Studio project

the way i found was to find the project compiler output (project structure > project). then find the complied folder of the module you wish to turn to a jar, compress it with zip and change the extension of the output from zip to jar.

How to pass parameter to click event in Jquery

As DOC says, you can pass data to the handler as next:

// say your selector and click handler looks something like this...
$("some selector").on('click',{param1: "Hello", param2: "World"}, cool_function);

// in your function, just grab the event object and go crazy...
function cool_function(event){
    alert(event.data.param1);
    alert(event.data.param2);

    // access element's id where click occur
    alert( event.target.id ); 
}

How to include PHP files that require an absolute path?

Another option, related to Kevin's, is use __FILE__, but instead replace the php file name from within it:

<?php

$docRoot = str_replace($_SERVER['SCRIPT_NAME'], '', __FILE__);
require_once($docRoot . '/lib/include.php');

?>

I've been using this for a while. The only problem is sometimes you don't have $_SERVER['SCRIPT_NAME'], but sometimes there is another variable similar.

How to get first record in each group using Linq

    var res = from element in list
              group element by element.F1
                  into groups
                  select groups.OrderBy(p => p.F2).First();

Use JSTL forEach loop's varStatus as an ID

Its really helped me to dynamically generate ids of showDetailItem for the below code.

<af:forEach id="fe1" items="#{viewScope.bean.tranTypeList}" var="ttf" varStatus="ttfVs" > 
<af:showDetailItem  id ="divIDNo${ttfVs.count}" text="#{ttf.trandef}"......>

if you execute this line <af:outputText value="#{ttfVs}"/> prints the below:

{index=3, count=4, last=false, first=false, end=8, step=1, begin=0}

android listview get selected item

final ListView lv = (ListView) findViewById(R.id.ListView01);

lv.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
        String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));

      }                 
});

I hope this fixes your problem.

How do I find out my python path using python?

import sys
for a in sys.path:
    a.replace('\\\\','\\')
    print(a)

It will give all the paths ready for place in the Windows.

php stdClass to array

use this function to get a standard array back of the type you are after...

return get_object_vars($booking);

String.Format not work in TypeScript

You can use TypeScript's native string interpolation in case if your only goal to eliminate ugly string concatenations and boring string conversions:

var yourMessage = `Your text ${yourVariable} your text continued ${yourExpression} and so on.`

NOTE:

At the right side of the assignment statement the delimiters are neither single or double quotes, instead a special char called backtick or grave accent.

The TypeScript compiler will translate your right side special literal to a string concatenation expression. With other words this syntax is not relies the ECMAScript 6 feature instead a native TypeScript feature. Your generated javascript code remains compatible.

What is null in Java?

Null in Java(tm)

In C and C++, "NULL" is a constant defined in a header file, with a value like:

    0

or:

    0L

or:

    ((void*)0)

depending on the compiler and memory model options. NULL is not, strictly speaking, part of C/C++ itself.

In Java(tm), "null" is not a keyword, but a special literal of the null type. It can be cast to any reference type, but not to any primitive type such as int or boolean. The null literal doesn't necessarily have value zero. And it is impossible to cast to the null type or declare a variable of this type.

store return value of a Python script in a bash script

In addition to what Tichodroma said, you might end up using this syntax:

outputString=$(python myPythonScript arg1 arg2 arg3)

Variable number of arguments in C++?

in c++11 you can do:

void foo(const std::list<std::string> & myArguments) {
   //do whatever you want, with all the convenience of lists
}

foo({"arg1","arg2"});

list initializer FTW!

regular expression for Indian mobile numbers

This is worked for me using JAVA script for chrome extension.

document.body.innerHTML = myFunction();
function myFunction()
{
    var phonedef = new RegExp("(?:(?:\\+|0{0,2})91(\\s*[\\- ]\\s*)?|[0 ]?)?[789]\\d{9}|(\\d[ -]?){10}\\d", "g");

    var str = document.body.innerHTML; 
    var res = str.replace(phonedef, function myFunction(x){return "<a href='tel:"+x.replace( /(\s|-)/g, "")+"'>"+x+"</a>";});

    return res;
}

This covers following numbers pattern

9883443344
8888564723 
7856128945

09883443344 
0 9883443344 
0-9883443344

919883443344 
91 8834433441 
91-9883443344 
91 -9883443344 
91- 9883443344 
91 - 9883443344 
91 -9883443344

+917878525200 
+91 8834433441 
+91-9883443344 
+91 -9883443344 
+91- 9883443344 
+91 - 9883443344 
+91 -9883443344

0919883443344 
0091-7779015989 
0091 - 8834433440 
022-24130000 
080 25478965 
0416-2565478 
08172-268032 
04512-895612 
02162-240000 
022-24141414 
079-22892350

Volatile vs. Interlocked vs. lock

EDIT: As noted in comments, these days I'm happy to use Interlocked for the cases of a single variable where it's obviously okay. When it gets more complicated, I'll still revert to locking...

Using volatile won't help when you need to increment - because the read and the write are separate instructions. Another thread could change the value after you've read but before you write back.

Personally I almost always just lock - it's easier to get right in a way which is obviously right than either volatility or Interlocked.Increment. As far as I'm concerned, lock-free multi-threading is for real threading experts, of which I'm not one. If Joe Duffy and his team build nice libraries which will parallelise things without as much locking as something I'd build, that's fabulous, and I'll use it in a heartbeat - but when I'm doing the threading myself, I try to keep it simple.

CSS3 scrollbar styling on a div

.scroll {
   width: 200px; height: 400px;
   overflow: auto;
}

Check if checkbox is NOT checked on click - jQuery

The Answer already posted .But We can use the jquery in this way also

demo

$(function(){
    $('#check1').click(function() {
        if($('#check1').attr('checked'))
            alert('checked');
        else
            alert('unchecked');
    });

    $('#check2').click(function() {
        if(!$('#check2').attr('checked'))
            alert('unchecked');
        else
            alert('checked');
    });
});

What is the best project structure for a Python application?

Non-python data is best bundled inside your Python modules using the package_data support in setuptools. One thing I strongly recommend is using namespace packages to create shared namespaces which multiple projects can use -- much like the Java convention of putting packages in com.yourcompany.yourproject (and being able to have a shared com.yourcompany.utils namespace).

Re branching and merging, if you use a good enough source control system it will handle merges even through renames; Bazaar is particularly good at this.

Contrary to some other answers here, I'm +1 on having a src directory top-level (with doc and test directories alongside). Specific conventions for documentation directory trees will vary depending on what you're using; Sphinx, for instance, has its own conventions which its quickstart tool supports.

Please, please leverage setuptools and pkg_resources; this makes it much easier for other projects to rely on specific versions of your code (and for multiple versions to be simultaneously installed with different non-code files, if you're using package_data).

No resource found - Theme.AppCompat.Light.DarkActionBar

AppCompat is a library project. You need to reference the library project in your android project.

Check the topic Adding libraries with resources.

Update

Adding material theme should be the way. Check https://material.io/develop/android/docs/getting-started for more details.

Can anonymous class implement interface?

The best solution is just not to use anonymous classes.

public class Test
{
    class DummyInterfaceImplementor : IDummyInterface
    {
        public string A { get; set; }
        public string B { get; set; }
    }

    public void WillThisWork()
    {
        var source = new DummySource[0];
        var values = from value in source
                     select new DummyInterfaceImplementor()
                     {
                         A = value.A,
                         B = value.C + "_" + value.D
                     };

        DoSomethingWithDummyInterface(values.Cast<IDummyInterface>());

    }

    public void DoSomethingWithDummyInterface(IEnumerable<IDummyInterface> values)
    {
        foreach (var value in values)
        {
            Console.WriteLine("A = '{0}', B = '{1}'", value.A, value.B);
        }
    }
}

Note that you need to cast the result of the query to the type of the interface. There might be a better way to do it, but I couldn't find it.

jQuery - Create hidden form element on the fly

$('<input>').attr('type','hidden').appendTo('form');

To answer your second question:

$('<input>').attr({
    type: 'hidden',
    id: 'foo',
    name: 'bar'
}).appendTo('form');

How to compare arrays in C#?

There is no static Equals method in the Array class, so what you are using is actually Object.Equals, which determines if the two object references point to the same object.

If you want to check if the arrays contains the same items in the same order, you can use the SequenceEquals extension method:

childe1.SequenceEqual(grandFatherNode)

Edit:

To use SequenceEquals with multidimensional arrays, you can use an extension to enumerate them. Here is an extension to enumerate a two dimensional array:

public static IEnumerable<T> Flatten<T>(this T[,] items) {
  for (int i = 0; i < items.GetLength(0); i++)
    for (int j = 0; j < items.GetLength(1); j++)
      yield return items[i, j];
}

Usage:

childe1.Flatten().SequenceEqual(grandFatherNode.Flatten())

If your array has more dimensions than two, you would need an extension that supports that number of dimensions. If the number of dimensions varies, you would need a bit more complex code to loop a variable number of dimensions.

You would of course first make sure that the number of dimensions and the size of the dimensions of the arrays match, before comparing the contents of the arrays.

Edit 2:

Turns out that you can use the OfType<T> method to flatten an array, as RobertS pointed out. Naturally that only works if all the items can actually be cast to the same type, but that is usually the case if you can compare them anyway. Example:

childe1.OfType<Person>().SequenceEqual(grandFatherNode.OfType<Person>())

Div table-cell vertical align not working

In my case, I wanted to center in a parent container with position: absolute.

<div class="absolute-container">
    <div class="parent-container">
        <div class="centered-content">
            My content
        </div>
    </div>
</div>

I had to add some positioning for top, bottom, left & right.

.absolute-container {
    position:absolute;
    top:0;
    left:0;
    bottom:0;
    right:0;
}

.parent-container {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    display: table
}

.centered-content {
    display: table-cell;
    text-align: center;
    vertical-align: middle
}

how to kill hadoop jobs

An unhandled exception will (assuming it's repeatable like bad data as opposed to read errors from a particular data node) eventually fail the job anyway.

You can configure the maximum number of times a particular map or reduce task can fail before the entire job fails through the following properties:

  • mapred.map.max.attempts - The maximum number of attempts per map task. In other words, framework will try to execute a map task these many number of times before giving up on it.
  • mapred.reduce.max.attempts - Same as above, but for reduce tasks

If you want to fail the job out at the first failure, set this value from its default of 4 to 1.

Xcode error: Code signing is required for product type 'Application' in SDK 'iOS 10.0'

For those using Ionic and receiving this error - you need to open your $project_dir/platform/ios/$project_name.xcodeproj - then follow the steps listed in the "answer"

Dynamic height for DIV

You should be okay to just take the height property out of the CSS.

Why is there no SortedList in Java?

Consider using indexed-tree-map . It's an enhanced JDK's TreeSet that provides access to element by index and finding the index of an element without iteration or hidden underlying lists that back up the tree. The algorithm is based on updating weights of changing nodes every time there is a change.

Sorting a Dictionary in place with respect to keys

Take a look at SortedDictionary, there's even a constructor overload so you can pass in your own IComparable for the comparisons.

How do I remove all HTML tags from a string without knowing which tags are in it?

You can parse the string using Html Agility pack and get the InnerText.

    HtmlDocument htmlDoc = new HtmlDocument();
    htmlDoc.LoadHtml(@"<b> Hulk Hogan's Celebrity Championship Wrestling &nbsp;&nbsp;&nbsp;<font color=\"#228b22\">[Proj # 206010]</font></b>&nbsp;&nbsp;&nbsp; (Reality Series, &nbsp;)");
    string result = htmlDoc.DocumentNode.InnerText;

In plain English, what does "git reset" do?

Remember that in git you have:

  • the HEAD pointer, which tells you what commit you're working on
  • the working tree, which represents the state of the files on your system
  • the staging area (also called the index), which "stages" changes so that they can later be committed together

Please include detailed explanations about:

--hard, --soft and --merge;

In increasing order of dangerous-ness:

  • --soft moves HEAD but doesn't touch the staging area or the working tree.
  • --mixed moves HEAD and updates the staging area, but not the working tree.
  • --merge moves HEAD, resets the staging area, and tries to move all the changes in your working tree into the new working tree.
  • --hard moves HEAD and adjusts your staging area and working tree to the new HEAD, throwing away everything.

concrete use cases and workflows;

  • Use --soft when you want to move to another commit and patch things up without "losing your place". It's pretty rare that you need this.

--

# git reset --soft example
touch foo                            // Add a file, make some changes.
git add foo                          // 
git commit -m "bad commit message"   // Commit... D'oh, that was a mistake!
git reset --soft HEAD^               // Go back one commit and fix things.
git commit -m "good commit"          // There, now it's right.

--

  • Use --mixed (which is the default) when you want to see what things look like at another commit, but you don't want to lose any changes you already have.

  • Use --merge when you want to move to a new spot but incorporate the changes you already have into that the working tree.

  • Use --hard to wipe everything out and start a fresh slate at the new commit.

Random color generator

A bit enhanced one-liner to make the approach more vivid

'#' + Math.round((0x1000000 + 0xffffff * Math.random())).toString(16).slice(1)

Escaping backslash in string - javascript

Escape the backslash character.

foo.split('\\')

Is it possible to use the SELECT INTO clause with UNION [ALL]?

For MS Access queries, this worked:

SELECT * INTO tmpFerdeen FROM( 
    SELECT top(100) *
    FROM Customers 
UNION All 
    SELECT top(100) *  
    FROM CustomerEurope 
UNION All 
    SELECT top(100) *  
    FROM CustomerAsia 
UNION All 
    SELECT top(100) *  
    FROM CustomerAmericas
) 

This did NOT work in MS Access

SELECT top(100) * 
  INTO tmpFerdeen
  FROM Customers
UNION All
  SELECT top(100) * 
  FROM CustomerEurope
UNION All
  SELECT top(100) * 
  FROM CustomerAsia
UNION All
  SELECT top(100) * 
  FROM CustomerAmericas

Exception 'open failed: EACCES (Permission denied)' on Android

For anyone coming here from search results and are targeting Android 10: Android 10 (API 29) changes some permissions related to storage.

I fixed the issue when I replaced my previous instances of Environment.getExternalStorageDirectory() (which is deprecated with API 29) with context.getExternalFilesDir(null).

Note that context.getExternalFilesDir(type) can return null if the storage location isn't available, so be sure to check that whenever you're checking if you have external permissions.

Read more here.

jQuery equivalent of JavaScript's addEventListener method

As of jQuery 1.7, .on() is now the preferred method of binding events, rather than .bind():

From http://api.jquery.com/bind/:

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().

The documentation page is located at http://api.jquery.com/on/

How can I search for a multiline pattern in a file?

With silver searcher:

ag 'abc.*(\n|.)*efg'

Speed optimizations of silver searcher could possibly shine here.

Spring boot - configure EntityManager

Hmmm you can find lot of examples for configuring spring framework. Anyways here is a sample

@Configuration
@Import({PersistenceConfig.class})
@ComponentScan(basePackageClasses = { 
    ServiceMarker.class,
    RepositoryMarker.class }
)
public class AppConfig {

}

PersistenceConfig

@Configuration
@PropertySource(value = { "classpath:database/jdbc.properties" })
@EnableTransactionManagement
public class PersistenceConfig {

    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH = "hibernate.max_fetch_depth";
    private static final String PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE = "hibernate.jdbc.fetch_size";
    private static final String PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE = "hibernate.jdbc.batch_size";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
    private static final String[] ENTITYMANAGER_PACKAGES_TO_SCAN = {"a.b.c.entities", "a.b.c.converters"};

    @Autowired
    private Environment env;

     @Bean(destroyMethod = "close")
     public DataSource dataSource() {
         BasicDataSource dataSource = new BasicDataSource();
         dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
         dataSource.setUrl(env.getProperty("jdbc.url"));
         dataSource.setUsername(env.getProperty("jdbc.username"));
         dataSource.setPassword(env.getProperty("jdbc.password"));
         return dataSource;
     }

     @Bean
     public JpaTransactionManager jpaTransactionManager() {
         JpaTransactionManager transactionManager = new JpaTransactionManager();
         transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
         return transactionManager;
     }

    private HibernateJpaVendorAdapter vendorAdaptor() {
         HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
         vendorAdapter.setShowSql(true);
         return vendorAdapter;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {

         LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
         entityManagerFactoryBean.setJpaVendorAdapter(vendorAdaptor());
         entityManagerFactoryBean.setDataSource(dataSource());
         entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
         entityManagerFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);             
         entityManagerFactoryBean.setJpaProperties(jpaHibernateProperties());

         return entityManagerFactoryBean;
     }

     private Properties jpaHibernateProperties() {

         Properties properties = new Properties();

         properties.put(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH, env.getProperty(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH));
         properties.put(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE));
         properties.put(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE));
         properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));

         properties.put(AvailableSettings.SCHEMA_GEN_DATABASE_ACTION, "none");
         properties.put(AvailableSettings.USE_CLASS_ENHANCER, "false");      
         return properties;       
     }

}

Main

public static void main(String[] args) { 
    try (GenericApplicationContext springContext = new AnnotationConfigApplicationContext(AppConfig.class)) {
        MyService myService = springContext.getBean(MyServiceImpl.class);
        try {
            myService.handleProcess(fromDate, toDate);
        } catch (Exception e) {
            logger.error("Exception occurs", e);
            myService.handleException(fromDate, toDate, e);
        }
    } catch (Exception e) {
        logger.error("Exception occurs in loading Spring context: ", e);
    }
}

MyService

@Service
public class MyServiceImpl implements MyService {

    @Inject
    private MyDao myDao;

    @Override
    public void handleProcess(String fromDate, String toDate) {
        List<Student> myList = myDao.select(fromDate, toDate);
    }
}

MyDaoImpl

@Repository
@Transactional
public class MyDaoImpl implements MyDao {

    @PersistenceContext
    private EntityManager entityManager;

    public Student select(String fromDate, String toDate){

        TypedQuery<Student> query = entityManager.createNamedQuery("Student.findByKey", Student.class);
        query.setParameter("fromDate", fromDate);
        query.setParameter("toDate", toDate);
        List<Student> list = query.getResultList();
        return CollectionUtils.isEmpty(list) ? null : list;
    }

}

Assuming maven project: Properties file should be in src/main/resources/database folder

jdbc.properties file

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=your db url
jdbc.username=your Username
jdbc.password=Your password

hibernate.max_fetch_depth = 3
hibernate.jdbc.fetch_size = 50
hibernate.jdbc.batch_size = 10
hibernate.show_sql = true

ServiceMarker and RepositoryMarker are just empty interfaces in your service or repository impl package.

Let's say you have package name a.b.c.service.impl. MyServiceImpl is in this package and so is ServiceMarker.

public interface ServiceMarker {

}

Same for repository marker. Let's say you have a.b.c.repository.impl or a.b.c.dao.impl package name. Then MyDaoImpl is in this this package and also Repositorymarker

public interface RepositoryMarker {

}

a.b.c.entities.Student

//dummy class and dummy query
@Entity
@NamedQueries({
@NamedQuery(name="Student.findByKey", query="select s from Student s where s.fromDate=:fromDate" and s.toDate = :toDate)
})
public class Student implements Serializable {

    private LocalDateTime fromDate;
    private LocalDateTime toDate;

    //getters setters

}

a.b.c.converters

@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {

    @Override
    public Timestamp convertToDatabaseColumn(LocalDateTime dateTime) {

        if (dateTime == null) {
            return null;
        }
        return Timestamp.valueOf(dateTime);
    }

    @Override
    public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {

        if (timestamp == null) {
            return null;
        }    
        return timestamp.toLocalDateTime();
    }
}

pom.xml

<properties>
    <java-version>1.8</java-version>
    <org.springframework-version>4.2.1.RELEASE</org.springframework-version>
    <hibernate-entitymanager.version>5.0.2.Final</hibernate-entitymanager.version>
    <commons-dbcp2.version>2.1.1</commons-dbcp2.version>
    <mysql-connector-java.version>5.1.36</mysql-connector-java.version>
     <junit.version>4.12</junit.version> 
</properties>

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
        <scope>test</scope>
    </dependency>

    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>javax.inject</groupId>
        <artifactId>javax.inject</artifactId>
        <version>1</version>
        <scope>compile</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>${hibernate-entitymanager.version}</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql-connector-java.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
        <version>${commons-dbcp2.version}</version>
    </dependency>
</dependencies>

<build>
     <finalName>${project.artifactId}</finalName>
     <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.3</version>
            <configuration>
                <source>${java-version}</source>
                <target>${java-version}</target>
                <compilerArgument>-Xlint:all</compilerArgument>
                <showWarnings>true</showWarnings>
                <showDeprecation>true</showDeprecation>
            </configuration>
        </plugin>
     </plugins>
</build>

Hope it helps. Thanks

Find and replace with sed in directory and sub directories

Your find should look like that to avoid sending directory names to sed:

find ./ -type f -exec sed -i -e 's/apple/orange/g' {} \;

What does <![CDATA[]]> in XML mean?

From Wikipedia:

[In] an XML document or external parsed entity, a CDATA section is a section of element content that is marked for the parser to interpret as only character data, not markup.

http://en.wikipedia.org/wiki/CDATA

Thus: text inside CDATA is seen by the parser but only as characters not as XML nodes.

Enable CORS in Web API 2

 var cors = new EnableCorsAttribute("*","*","*");
 config.EnableCors(cors);

 var constraints = new {httpMethod = new HttpMethodConstraint(HttpMethod.Options)};
 config.Routes.IgnoreRoute("OPTIONS", "*pathInfo",constraints);

how to kill the tty in unix

You can use killall command as well .

-o, --older-than Match only processes that are older (started before) the time specified. The time is specified as a float then a unit. The units are s,m,h,d,w,M,y for seconds, minutes, hours, days,

-e, --exact Require an exact match for very long names.

-r, --regexp Interpret process name pattern as an extended regular expression.

This worked like a charm.

Why aren't Xcode breakpoints functioning?

Having both Xcode 5 and 6 GM caused the former to lose breakpoint functionality (Xcode 6 betas were ok).

I tried many of the suggested methods but finally gave up and I'm just using Xcode 6 now.

How to check if a string in Python is in ASCII?

I use the following to determine if the string is ascii or unicode:

>> print 'test string'.__class__.__name__
str
>>> print u'test string'.__class__.__name__
unicode
>>> 

Then just use a conditional block to define the function:

def is_ascii(input):
    if input.__class__.__name__ == "str":
        return True
    return False

Set content of iframe

$('#myiframe').contents().find('html').html(s); 

you can check from here http://jsfiddle.net/Y9beh/

Batch file to copy files from one folder to another folder

If you want to copy file not using absolute path, relative path in other words:

Don't forget to write backslash in the path AND NOT slash

Example:

copy children-folder\file.something .\other-children-folder

PS: absolute path can be retrieved using these wildcards called "batch parameters"

@echo off
echo %%~dp0 is "%~dp0"
echo %%0 is "%0"
echo %%~dpnx0 is "%~dpnx0"
echo %%~f1 is "%~f1"
echo %%~dp0%%~1 is "%~dp0%~1"

Check documentation here about copy: https://technet.microsoft.com/en-us/library/bb490886.aspx

And also here for batch parameters documentation: https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/percent.mspx?mfr=true

Django templates: If false?

You could write a custom template filter to do this in a half-dozen lines of code:

from django.template import Library

register = Library()

@register.filter
def is_false(arg): 
    return arg is False

Then in your template:

{% if myvar|is_false %}...{% endif %}

Of course, you could make that template tag much more generic... but this suits your needs specifically ;-)

Python: how can I check whether an object is of type datetime.date?

In Python 3.5, isinstance(x, date) works to me:

>>> from datetime import date
>>> x = date(2012, 9, 1)
>>> type(x)
<class 'datetime.date'>
>>> isinstance(x, date)
True
>>> type(x) is date
True

XML Document to String

Assuming doc is your instance of org.w3c.dom.Document:

TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString().replaceAll("\n|\r", "");

Objective-C : BOOL vs bool

The Objective-C type you should use is BOOL. There is nothing like a native boolean datatype, therefore to be sure that the code compiles on all compilers use BOOL. (It's defined in the Apple-Frameworks.

Passing Variable through JavaScript from one html page to another page

There are two pages: Pageone.html :

<script>
var hello = "hi"
location.replace("http://example.com/PageTwo.html?" + hi + "");
</script>

PageTwo.html :

<script>
var link = window.location.href;
link = link.replace("http://example.com/PageTwo.html?","");
document.write("The variable contained this content:" + link + "");
</script>

Hope it helps!

Javascript Debugging line by line using Google Chrome

Assuming you're running on a Windows machine...

  1. Hit the F12 key
  2. Select the Scripts, or Sources, tab in the developer tools
  3. Click the little folder icon in the top level
  4. Select your JavaScript file
  5. Add a breakpoint by clicking on the line number on the left (adds a little blue marker)
  6. Execute your JavaScript

Then during execution debugging you can do a handful of stepping motions...

  • F8 Continue: Will continue until the next breakpoint
  • F10 Step over: Steps over next function call (won't enter the library)
  • F11 Step into: Steps into the next function call (will enter the library)
  • Shift + F11 Step out: Steps out of the current function

Update

After reading your updated post; to debug your code I would recommend temporarily using the jQuery Development Source Code. Although this doesn't directly solve your problem, it will allow you to debug more easily. For what you're trying to achieve I believe you'll need to step-in to the library, so hopefully the production code should help you decipher what's happening.

Apache Spark: The number of cores vs. the number of executors

There is a small issue in the First two configurations i think. The concepts of threads and cores like follows. The concept of threading is if the cores are ideal then use that core to process the data. So the memory is not fully utilized in first two cases. If you want to bench mark this example choose the machines which has more than 10 cores on each machine. Then do the bench mark.

But dont give more than 5 cores per executor there will be bottle neck on i/o performance.

So the best machines to do this bench marking might be data nodes which have 10 cores.

Data node machine spec: CPU: Core i7-4790 (# of cores: 10, # of threads: 20) RAM: 32GB (8GB x 4) HDD: 8TB (2TB x 4)

What is the difference between 127.0.0.1 and localhost

There is nothing different. One is easier to remember than the other. Generally, you define a name to associate with an IP address. You don't have to specify localhost for 127.0.0.1, you could specify any name you want.

Different ways of adding to Dictionary

To answer the question first we need to take a look at the purpose of a dictionary and underlying technology.

Dictionary is the list of KeyValuePair<Tkey, Tvalue> where each value is represented by its unique key. Let's say we have a list of your favorite foods. Each value (food name) is represented by its unique key (a position = how much you like this food).

Example code:

Dictionary<int, string> myDietFavorites = new Dictionary<int, string>()
{
    { 1, "Burger"},
    { 2, "Fries"},
    { 3, "Donuts"}
};

Let's say you want to stay healthy, you've changed your mind and you want to replace your favorite "Burger" with salad. Your list is still a list of your favorites, you won't change the nature of the list. Your favorite will remain number one on the list, only it's value will change. This is when you call this:

/*your key stays 1, you only replace the value assigned to this key
  you alter existing record in your dictionary*/
myDietFavorites[1] = "Salad";

But don't forget you're the programmer, and from now on you finishes your sentences with ; you refuse to use emojis because they would throw compilation error and all list of favorites is 0 index based.

Your diet changed too! So you alter your list again:

/*you don't want to replace Salad, you want to add this new fancy 0
  position to your list. It wasn't there before so you can either define it*/
myDietFavorites[0] = "Pizza";

/*or Add it*/
myDietFavorites.Add(0, "Pizza");

There are two possibilities with defining, you either want to give a new definition for something not existent before or you want to change definition which already exists.

Add method allows you to add a record but only under one condition: key for this definition may not exist in your dictionary.

Now we are going to look under the hood. When you are making a dictionary your compiler make a reservation for the bucket (spaces in memory to store your records). Bucket don't store keys in the way you define them. Each key is hashed before going to the bucket (defined by Microsoft), worth mention that value part stays unchanged.

I'll use the CRC32 hashing algorithm to simplify my example. When you defining:

myDietFavorites[0] = "Pizza";

What is going to the bucket is db2dc565 "Pizza" (simplified).

When you alter the value in with:

myDietFavorites[0] = "Spaghetti";

You hash your 0 which is again db2dc565 then you look up this value in your bucket to find if it's there. If it's there you simply rewrite the value assigned to the key. If it's not there you'll place your value in the bucket.

When you calling Add function on your dictionary like:

myDietFavorite.Add(0, "Chocolate");

You hash your 0 to compare it's value to ones in the bucket. You may place it in the bucket only if it's not there.

It's crucial to know how it works especially if you work with dictionaries of string or char type of key. It's case sensitive because of undergoing hashing. So for example "name" != "Name". Let's use our CRC32 to depict this.

Value for "name" is: e04112b1 Value for "Name" is: 1107fb5b

Best Way to View Generated Source of Webpage?

Only thing i found is the BetterSource extension for Safari this will show you the manipulated source of the document only downside is nothing remotely like it for Firefox

How would you do a "not in" query with LINQ?

items in the first list where the Email does not exist in the second list.

from item1 in List1
where !(list2.Any(item2 => item2.Email == item1.Email))
select item1;

Using different Web.config in development and production environment

The Enterprise Library configuration editor can help you do this. It allows you to create a base config file and then deltas for each environment. You can then merge the base config and the delta to create an environment-specific web.config. Take a look at the information here which takes you through it better than I can.

Blocks and yields in Ruby

I wanted to sort of add why you would do things that way to the already great answers.

No idea what language you are coming from, but assuming it is a static language, this sort of thing will look familiar. This is how you read a file in java

public class FileInput {

  public static void main(String[] args) {

    File file = new File("C:\\MyFile.txt");
    FileInputStream fis = null;
    BufferedInputStream bis = null;
    DataInputStream dis = null;

    try {
      fis = new FileInputStream(file);

      // Here BufferedInputStream is added for fast reading.
      bis = new BufferedInputStream(fis);
      dis = new DataInputStream(bis);

      // dis.available() returns 0 if the file does not have more lines.
      while (dis.available() != 0) {

      // this statement reads the line from the file and print it to
        // the console.
        System.out.println(dis.readLine());
      }

      // dispose all the resources after using them.
      fis.close();
      bis.close();
      dis.close();

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Ignoring the whole stream chaining thing, The idea is this

  1. Initialize resource that needs to be cleaned up
  2. use resource
  3. make sure to clean it up

This is how you do it in ruby

File.open("readfile.rb", "r") do |infile|
    while (line = infile.gets)
        puts "#{counter}: #{line}"
        counter = counter + 1
    end
end

Wildly different. Breaking this one down

  1. tell the File class how to initialize the resource
  2. tell the file class what to do with it
  3. laugh at the java guys who are still typing ;-)

Here, instead of handling step one and two, you basically delegate that off into another class. As you can see, that dramatically brings down the amount of code you have to write, which makes things easier to read, and reduces the chances of things like memory leaks, or file locks not getting cleared.

Now, its not like you can't do something similar in java, in fact, people have been doing it for decades now. It's called the Strategy pattern. The difference is that without blocks, for something simple like the file example, strategy becomes overkill due to the amount of classes and methods you need to write. With blocks, it is such a simple and elegant way of doing it, that it doesn't make any sense NOT to structure your code that way.

This isn't the only way blocks are used, but the others (like the Builder pattern, which you can see in the form_for api in rails) are similar enough that it should be obvious whats going on once you wrap your head around this. When you see blocks, its usually safe to assume that the method call is what you want to do, and the block is describing how you want to do it.

How to increase memory limit for PHP over 2GB?

Have you tried using the value in MB ?

php_value memory_limit 2048M

Also try editing this value in php.ini not Apache.

QString to char* conversion

Qt provides the simplest API

const char *qPrintable(const QString &str)
const char *qUtf8Printable(const QString &str)

If you want non-const data pointer use

str.toLocal8Bit().data()
str.toUtf8().data()

GenyMotion Unable to start the Genymotion virtual device

Firewall might be the cause, just try disabling it In my case it was due to the firewall. I tried all these suggestions in the answers and none of them worked for me. Finally I disabled the firewall It worked for me.

C# Enum - How to Compare Value

use this

if (userProfile.AccountType == AccountType.Retailer)
{
     ...
}

If you want to get int from your AccountType enum and compare it (don't know why) do this:

if((int)userProfile.AccountType == 1)
{ 
     ...
}

Objet reference not set to an instance of an object exception is because your userProfile is null and you are getting property of null. Check in debug why it's not set.

EDIT (thanks to @Rik and @KonradMorawski) :

Maybe you can do some check before:

if(userProfile!=null)
{
}

or

if(userProfile==null)
{
   throw new ArgumentNullException(nameof(userProfile)); // or any other exception
}

How do I remove diacritics (accents) from a string in .NET?

Not having enough reputations, apparently I can not comment on Alexander's excellent link. - Lucene appears to be the only solution working in reasonably generic cases.

For those wanting a simple copy-paste solution, here it is, leveraging code in Lucene:

string testbed = "ÁÂÄÅÇÉÍÎÓÖØÚÜÞàáâãäåæçèéêëìíîïðñóôöøúüaacÐegiLlnOorSsšzž????";

Console.WriteLine(Lucene.latinizeLucene(testbed));

AAAACEIIOOOUUTHaaaaaaaeceeeeiiiidnoooouuaacDegiLlnOorSsszzsteu

//////////

public static class Lucene
{
    // source: https://raw.githubusercontent.com/apache/lucenenet/master/src/Lucene.Net.Analysis.Common/Analysis/Miscellaneous/ASCIIFoldingFilter.cs
    // idea: https://stackoverflow.com/questions/249087/how-do-i-remove-diacritics-accents-from-a-string-in-net (scroll down, search for lucene by Alexander)
    public static string latinizeLucene(string arg)
    {
        char[] argChar = arg.ToCharArray();

        // latinizeLuceneImpl can expand one char up to four chars - e.g. Þ to TH, or æ to ae, or in fact ? to (10)
        char[] resultChar = new String(' ', arg.Length * 4).ToCharArray();

        int outputPos = Lucene.latinizeLuceneImpl(argChar, 0, ref resultChar, 0, arg.Length);

        string ret = new string(resultChar);
        ret = ret.Substring(0, outputPos);

        return ret;
    }

    /// <summary>
    /// Converts characters above ASCII to their ASCII equivalents.  For example,
    /// accents are removed from accented characters. 
    /// <para/>
    /// @lucene.internal
    /// </summary>
    /// <param name="input">     The characters to fold </param>
    /// <param name="inputPos">  Index of the first character to fold </param>
    /// <param name="output">    The result of the folding. Should be of size >= <c>length * 4</c>. </param>
    /// <param name="outputPos"> Index of output where to put the result of the folding </param>
    /// <param name="length">    The number of characters to fold </param>
    /// <returns> length of output </returns>
    private static int latinizeLuceneImpl(char[] input, int inputPos, ref char[] output, int outputPos, int length)
    {
        int end = inputPos + length;
        for (int pos = inputPos; pos < end; ++pos)
        {
            char c = input[pos];

            // Quick test: if it's not in range then just keep current character
            if (c < '\u0080')
            {
                output[outputPos++] = c;
            }
            else
            {
                switch (c)
                {
                    case '\u00C0': // À  [LATIN CAPITAL LETTER A WITH GRAVE]
                    case '\u00C1': // Á  [LATIN CAPITAL LETTER A WITH ACUTE]
                    case '\u00C2': // Â  [LATIN CAPITAL LETTER A WITH CIRCUMFLEX]
                    case '\u00C3': // Ã  [LATIN CAPITAL LETTER A WITH TILDE]
                    case '\u00C4': // Ä  [LATIN CAPITAL LETTER A WITH DIAERESIS]
                    case '\u00C5': // Å  [LATIN CAPITAL LETTER A WITH RING ABOVE]
                    case '\u0100': // A  [LATIN CAPITAL LETTER A WITH MACRON]
                    case '\u0102': // A  [LATIN CAPITAL LETTER A WITH BREVE]
                    case '\u0104': // A  [LATIN CAPITAL LETTER A WITH OGONEK]
                    case '\u018F': // ?  http://en.wikipedia.org/wiki/Schwa  [LATIN CAPITAL LETTER SCHWA]
                    case '\u01CD': // A  [LATIN CAPITAL LETTER A WITH CARON]
                    case '\u01DE': // A  [LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON]
                    case '\u01E0': // ?  [LATIN CAPITAL LETTER A WITH DOT ABOVE AND MACRON]
                    case '\u01FA': // ?  [LATIN CAPITAL LETTER A WITH RING ABOVE AND ACUTE]
                    case '\u0200': // ?  [LATIN CAPITAL LETTER A WITH DOUBLE GRAVE]
                    case '\u0202': // ?  [LATIN CAPITAL LETTER A WITH INVERTED BREVE]
                    case '\u0226': // ?  [LATIN CAPITAL LETTER A WITH DOT ABOVE]
                    case '\u023A': // ?  [LATIN CAPITAL LETTER A WITH STROKE]
                    case '\u1D00': // ?  [LATIN LETTER SMALL CAPITAL A]
                    case '\u1E00': // ?  [LATIN CAPITAL LETTER A WITH RING BELOW]
                    case '\u1EA0': // ?  [LATIN CAPITAL LETTER A WITH DOT BELOW]
                    case '\u1EA2': // ?  [LATIN CAPITAL LETTER A WITH HOOK ABOVE]
                    case '\u1EA4': // ?  [LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND ACUTE]
                    case '\u1EA6': // ?  [LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND GRAVE]
                    case '\u1EA8': // ?  [LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND HOOK ABOVE]
                    case '\u1EAA': // ?  [LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND TILDE]
                    case '\u1EAC': // ?  [LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND DOT BELOW]
                    case '\u1EAE': // ?  [LATIN CAPITAL LETTER A WITH BREVE AND ACUTE]
                    case '\u1EB0': // ?  [LATIN CAPITAL LETTER A WITH BREVE AND GRAVE]
                    case '\u1EB2': // ?  [LATIN CAPITAL LETTER A WITH BREVE AND HOOK ABOVE]
                    case '\u1EB4': // ?  [LATIN CAPITAL LETTER A WITH BREVE AND TILDE]
                    case '\u1EB6': // ?  [LATIN CAPITAL LETTER A WITH BREVE AND DOT BELOW]
                    case '\u24B6': // ?  [CIRCLED LATIN CAPITAL LETTER A]
                    case '\uFF21': // A  [FULLWIDTH LATIN CAPITAL LETTER A]
                        output[outputPos++] = 'A';
                        break;
                    case '\u00E0': // à  [LATIN SMALL LETTER A WITH GRAVE]
                    case '\u00E1': // á  [LATIN SMALL LETTER A WITH ACUTE]
                    case '\u00E2': // â  [LATIN SMALL LETTER A WITH CIRCUMFLEX]
                    case '\u00E3': // ã  [LATIN SMALL LETTER A WITH TILDE]
                    case '\u00E4': // ä  [LATIN SMALL LETTER A WITH DIAERESIS]
                    case '\u00E5': // å  [LATIN SMALL LETTER A WITH RING ABOVE]
                    case '\u0101': // a  [LATIN SMALL LETTER A WITH MACRON]
                    case '\u0103': // a  [LATIN SMALL LETTER A WITH BREVE]
                    case '\u0105': // a  [LATIN SMALL LETTER A WITH OGONEK]
                    case '\u01CE': // a  [LATIN SMALL LETTER A WITH CARON]
                    case '\u01DF': // a  [LATIN SMALL LETTER A WITH DIAERESIS AND MACRON]
                    case '\u01E1': // ?  [LATIN SMALL LETTER A WITH DOT ABOVE AND MACRON]
                    case '\u01FB': // ?  [LATIN SMALL LETTER A WITH RING ABOVE AND ACUTE]
                    case '\u0201': // ?  [LATIN SMALL LETTER A WITH DOUBLE GRAVE]
                    case '\u0203': // ?  [LATIN SMALL LETTER A WITH INVERTED BREVE]
                    case '\u0227': // ?  [LATIN SMALL LETTER A WITH DOT ABOVE]
                    case '\u0250': // ?  [LATIN SMALL LETTER TURNED A]
                    case '\u0259': // ?  [LATIN SMALL LETTER SCHWA]
                    case '\u025A': // ?  [LATIN SMALL LETTER SCHWA WITH HOOK]
                    case '\u1D8F': // ?  [LATIN SMALL LETTER A WITH RETROFLEX HOOK]
                    case '\u1D95': // ?  [LATIN SMALL LETTER SCHWA WITH RETROFLEX HOOK]
                    case '\u1E01': // ?  [LATIN SMALL LETTER A WITH RING BELOW]
                    case '\u1E9A': // ?  [LATIN SMALL LETTER A WITH RIGHT HALF RING]
                    case '\u1EA1': // ?  [LATIN SMALL LETTER A WITH DOT BELOW]
                    case '\u1EA3': // ?  [LATIN SMALL LETTER A WITH HOOK ABOVE]
                    case '\u1EA5': // ?  [LATIN SMALL LETTER A WITH CIRCUMFLEX AND ACUTE]
                    case '\u1EA7': // ?  [LATIN SMALL LETTER A WITH CIRCUMFLEX AND GRAVE]
                    case '\u1EA9': // ?  [LATIN SMALL LETTER A WITH CIRCUMFLEX AND HOOK ABOVE]
                    case '\u1EAB': // ?  [LATIN SMALL LETTER A WITH CIRCUMFLEX AND TILDE]
                    case '\u1EAD': // ?  [LATIN SMALL LETTER A WITH CIRCUMFLEX AND DOT BELOW]
                    case '\u1EAF': // ?  [LATIN SMALL LETTER A WITH BREVE AND ACUTE]
                    case '\u1EB1': // ?  [LATIN SMALL LETTER A WITH BREVE AND GRAVE]
                    case '\u1EB3': // ?  [LATIN SMALL LETTER A WITH BREVE AND HOOK ABOVE]
                    case '\u1EB5': // ?  [LATIN SMALL LETTER A WITH BREVE AND TILDE]
                    case '\u1EB7': // ?  [LATIN SMALL LETTER A WITH BREVE AND DOT BELOW]
                    case '\u2090': // ?  [LATIN SUBSCRIPT SMALL LETTER A]
                    case '\u2094': // ?  [LATIN SUBSCRIPT SMALL LETTER SCHWA]
                    case '\u24D0': // ?  [CIRCLED LATIN SMALL LETTER A]
                    case '\u2C65': // ?  [LATIN SMALL LETTER A WITH STROKE]
                    case '\u2C6F': // ?  [LATIN CAPITAL LETTER TURNED A]
                    case '\uFF41': // a  [FULLWIDTH LATIN SMALL LETTER A]
                        output[outputPos++] = 'a';
                        break;
                    case '\uA732': // ?  [LATIN CAPITAL LETTER AA]
                        output[outputPos++] = 'A';
                        output[outputPos++] = 'A';
                        break;
                    case '\u00C6': // Æ  [LATIN CAPITAL LETTER AE]
                    case '\u01E2': // ?  [LATIN CAPITAL LETTER AE WITH MACRON]
                    case '\u01FC': // ?  [LATIN CAPITAL LETTER AE WITH ACUTE]
                    case '\u1D01': // ?  [LATIN LETTER SMALL CAPITAL AE]
                        output[outputPos++] = 'A';
                        output[outputPos++] = 'E';
                        break;
                    case '\uA734': // ?  [LATIN CAPITAL LETTER AO]
                        output[outputPos++] = 'A';
                        output[outputPos++] = 'O';
                        break;
                    case '\uA736': // ?  [LATIN CAPITAL LETTER AU]
                        output[outputPos++] = 'A';
                        output[outputPos++] = 'U';
                        break;

        // etc. etc. etc.
        // see link above for complete source code
        // 
        // unfortunately, postings are limited, as in
        // "Body is limited to 30000 characters; you entered 136098."

                    [...]

                    case '\u2053': // ?  [SWUNG DASH]
                    case '\uFF5E': // ~  [FULLWIDTH TILDE]
                        output[outputPos++] = '~';
                        break;
                    default:
                        output[outputPos++] = c;
                        break;
                }
            }
        }
        return outputPos;
    }
}

How to replace a string in an existing file in Perl?

$_='~s/blue/red/g';

Uh, what??

Just

s/blue/red/g;

or, if you insist on using a variable (which is not necessary when using $_, but I just want to show the right syntax):

$_ =~ s/blue/red/g;

CSS strikethrough different color from text?

If it helps someone you can just use css property

text-decoration-color: red;

Python 3 - Encode/Decode vs Bytes/Str

To add to add to the previous answer, there is even a fourth way that can be used

import codecs
encoded4 = codecs.encode(original, 'utf-8')
print(encoded4)

How to represent a fix number of repeats in regular expression?

^\w{14}$ in Perl and any Perl-style regex.

If you want to learn more about regular expressions - or just need a handy reference - the Wikipedia Entry on Regular Expressions is actually pretty good.

I want my android application to be only run in portrait mode?

in the manifest:

<activity android:name=".activity.MainActivity"
        android:screenOrientation="portrait"
        tools:ignore="LockedOrientationActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

or : in the MainActivity

@SuppressLint("SourceLockedOrientationActivity")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

How can I list all commits that changed a specific file?

To just get a list of the commit hashes use git rev-list

 git rev-list HEAD <filename>

Output:

b7c4f0d7ebc3e4c61155c76b5ebc940e697600b1
e3920ac6c08a4502d1c27cea157750bd978b6443
ea62422870ea51ef21d1629420c6441927b0d3ea
4b1eb462b74c309053909ab83451e42a7239c0db
4df2b0b581e55f3d41381f035c0c2c9bd31ee98d

which means 5 commits have touched this file. It's reverse chronological order, so the first commit in the list b7c4f0d7 is the most recent one.

Remove characters from a string

ONELINER which remove characters LIST (more than one at once) - for example remove +,-, ,(,) from telephone number:

var str = "+(48) 123-456-789".replace(/[-+()\s]/g, '');  // result: "48123456789"

We use regular expression [-+()\s] where we put unwanted characters between [ and ]

(the "\s" is 'space' character escape - for more info google 'character escapes in in regexp')

Writing a dictionary to a text file?

import json

with open('tokenler.json', 'w') as file:
     file.write(json.dumps(mydict, ensure_ascii=False))

Measuring Query Performance : "Execution Plan Query Cost" vs "Time Taken"

I understand it’s an old question – however I would like to add an example where cost is same but one query is better than the other.

As you observed in the question, % shown in execution plan is not the only yardstick for determining best query. In the following example, I have two queries doing the same task. Execution Plan shows both are equally good (50% each). Now I executed the queries with SET STATISTICS IO ON which shows clear differences.

In the following example, the query 1 uses seek whereas Query 2 uses scan on the table LWManifestOrderLineItems. When we actually checks the execution time however it is find that Query 2 works better.

Also read When is a Seek not a Seek? by Paul White

QUERY

---Preparation---------------
-----------------------------
DBCC FREEPROCCACHE
GO
DBCC DROPCLEANBUFFERS
GO

SET STATISTICS IO ON  --IO
SET STATISTICS TIME ON

--------Queries---------------
------------------------------

SELECT LW.Manifest,LW.OrderID,COUNT(DISTINCT LineItemID)
FROM LWManifestOrderLineItems LW
INNER JOIN ManifestContainers MC
    ON MC.Manifest = LW.Manifest
GROUP BY LW.Manifest,LW.OrderID
ORDER BY COUNT(DISTINCT LineItemID) DESC  

SELECT LW.Manifest,LW.OrderID,COUNT( LineItemID) LineCount
FROM LWManifestOrderLineItems LW
WHERE LW.Manifest IN (SELECT Manifest FROM ManifestContainers)
GROUP BY LW.Manifest,LW.OrderID
ORDER BY COUNT( LineItemID) DESC  

Statistics IO

enter image description here

Execution Plan

enter image description here

Redirect parent window from an iframe action

If you'd like to redirect to another domain without the user having to do anything you can use a link with the property:

target="_parent"

as said previously, and then use:

document.getElementById('link').click();

to have it automatically redirect.

Example:

<!DOCTYPE HTML>

<html>

<head>

</head>

<body>

<a id="link" target="_parent" href="outsideDomain.html"></a>

<script type="text/javascript">
    document.getElementById('link').click();
</script>

</body>

</html>

Note: The javascript click() command must come after you declare the link.

CORS header 'Access-Control-Allow-Origin' missing

This happens generally when you try access another domain's resources.

This is a security feature for avoiding everyone freely accessing any resources of that domain (which can be accessed for example to have an exact same copy of your website on a pirate domain).

The header of the response, even if it's 200OK do not allow other origins (domains, port) to access the ressources.

You can fix this problem if you are the owner of both domains:

Solution 1: via .htaccess

To change that, you can write this in the .htaccess of the requested domain file:

    <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
    </IfModule>

If you only want to give access to one domain, the .htaccess should look like this:

    <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin 'https://my-domain.tdl'
    </IfModule>

Solution 2: set headers the correct way

If you set this into the response header of the requested file, you will allow everyone to access the ressources:

Access-Control-Allow-Origin : *

OR

Access-Control-Allow-Origin : http://www.my-domain.com

Peace and code ;)

Unit testing with Spring Security

Using a static in this case is the best way to write secure code.

Yes, statics are generally bad - generally, but in this case, the static is what you want. Since the security context associates a Principal with the currently running thread, the most secure code would access the static from the thread as directly as possible. Hiding the access behind a wrapper class that is injected provides an attacker with more points to attack. They wouldn't need access to the code (which they would have a hard time changing if the jar was signed), they just need a way to override the configuration, which can be done at runtime or slipping some XML onto the classpath. Even using annotation injection would be overridable with external XML. Such XML could inject the running system with a rogue principal.

keytool error bash: keytool: command not found

If you are not using openjdk, use the below commands to set your keytool.

sudo update-alternatives --install "/usr/bin/keytool" "keytool" "/usr/lib/jvm/java8/jdk1.8.0_251/bin/keytool" 1

AND

sudo update-alternatives --set keytool /usr/lib/jvm/java8/jdk1.8.0_251/bin/keytool

This worked for me!

How do I create a user with the same privileges as root in MySQL/MariaDB?

% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;

How to get the id of the element clicked using jQuery

Since you are loading in the spans via ajax you will have to attach delegate handlers to the events to catch them as they bubble up.

$(document).on('click','span',function(e){
    console.log(e.target.id)
})

you will want to attach the event to the closest static member you can to increase efficiency.

$('#main_div').on('click','span',function(e){
    console.log(e.target.id)
})

is better than binding to the document for instance.

This question may help you understand

Direct vs. Delegated - jQuery .on()

How to make the corners of a button round?

If you want something like this

Button preview

here is the code.

1.Create a xml file in your drawable folder like mybutton.xml and paste the following markup:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true" >
        <shape android:shape="rectangle"  >
            <corners android:radius="3dip" />
            <stroke android:width="1dip" android:color="#5e7974" />
            <gradient android:angle="-90" android:startColor="#345953" android:endColor="#689a92"  />            
        </shape>
    </item>
    <item android:state_focused="true">
        <shape android:shape="rectangle"  >
            <corners android:radius="3dip" />
            <stroke android:width="1dip" android:color="#5e7974" />
            <solid android:color="#58857e"/>       
        </shape>
    </item>  
    <item >
       <shape android:shape="rectangle"  >
            <corners android:radius="3dip" />
            <stroke android:width="1dip" android:color="#5e7974" />
            <gradient android:angle="-90" android:startColor="#8dbab3" android:endColor="#58857e" />            
       </shape>
    </item>
</selector>

2.Now use this drawable for the background of your view. If the view is button then something like this:

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:textColor="#ffffff"
    android:background="@drawable/mybutton"
    android:text="Buttons" />

Connecting to Postgresql in a docker container from outside

I managed to get it run on linux

  1. run the docker postgres - make sure the port is published, I use alpine because it's lightweight.

    docker run --rm -P -p 127.0.0.1:5432:5432 -e POSTGRES_PASSWORD="1234" --name pg postgres:alpine
    
  2. using another terminal, access the database from the host using the postgres uri

    psql postgresql://postgres:1234@localhost:5432/postgres
    

for mac users, replace psql with pgcli

MAX(DATE) - SQL ORACLE

Oracle 9i+ (maybe 8i too) has FIRST/LAST aggregate functions, that make computation over groups of rows according to row's rank in group. Assuming all rows as one group, you'll get what you want without subqueries:

SELECT
  max(MEMBSHIP_ID)
  keep (
      dense_rank first
      order by paym_date desc NULLS LAST
  ) as LATEST_MEMBER_ID
FROM user_payment
WHERE user_id=1

AttributeError: module 'cv2.cv2' has no attribute 'createLBPHFaceRecognizer'

I had a similar problem:

module cv2 has no attribute "cv2.TrackerCSRT_create"

My Python version is 3.8.0 under Windows 10. The problem was the opencv version installation.

So I fixed this way (cmd prompt with administrator privileges):

  1. Uninstalled opencv-python: pip uninstall opencv-python
  2. Installed only opencv-contrib-python: pip install opencv-contrib-python

Anyway you can read the following guide:

https://github.com/skvark/opencv-python

How do I clear the dropdownlist values on button click event using jQuery?

If you want to reset the selected options

$('select option:selected').removeAttr('selected');

If you actually want to remove the options (although I don't think you mean this).

$('select').empty();

Substitute select for the most appropriate selector in your case (this may be by id or by CSS class). Using as is will reset all <select> elements on the page

How to fix curl: (60) SSL certificate: Invalid certificate chain

After attempting all of the above solutions to eliminate the "curl: (60) SSL certificate problem: unable to get local issuer certificate" error, the solution that finally worked for me on OSX 10.9 was:

  1. Locate the curl certificate PEM file location 'curl-config --ca' -- > /usr/local/etc/openssl/cert.pem

  2. Use the folder location to identify the PEM file 'cd /usr/local/etc/openssl'

  3. Create a backup of the cert.pem file 'cp cert.pem cert_pem.bkup'

  4. Download the updated Certificate file from the curl website 'sudo wget http://curl.haxx.se/ca/cacert.pem'

  5. Copy the downloaded PEM file to replace the old PEM file 'cp cacert.pem cert.pem'

    This is a modified version of a solution posted to correct the same issue in Ubuntu found here:

https://serverfault.com/questions/151157/ubuntu-10-04-curl-how-do-i-fix-update-the-ca-bundle

How would I stop a while loop after n amount of time?

You do not need to use the while True: loop in this case. There is a much simpler way to use the time condition directly:

import time

# timeout variable can be omitted, if you use specific value in the while condition
timeout = 300   # [seconds]

timeout_start = time.time()

while time.time() < timeout_start + timeout:
    test = 0
    if test == 5:
        break
    test -= 1

Conditional step/stage in Jenkins pipeline

According to other answers I am adding the parallel stages scenario:

pipeline {
    agent any
    stages {
        stage('some parallel stage') {
            parallel {
                stage('parallel stage 1') {
                    when {
                      expression { ENV == "something" }
                    }
                    steps {
                        echo 'something'
                    }
                }
                stage('parallel stage 2') {
                    steps {
                        echo 'something'
                    }
                }
            }
        }
    }
}

mysqldump with create database line

By default mysqldump always creates the CREATE DATABASE IF NOT EXISTS db_name; statement at the beginning of the dump file.

[EDIT] Few things about the mysqldump file and it's options:

--all-databases, -A

Dump all tables in all databases. This is the same as using the --databases option and naming all the databases on the command line.

--add-drop-database

Add a DROP DATABASE statement before each CREATE DATABASE statement. This option is typically used in conjunction with the --all-databases or --databases option because no CREATE DATABASE statements are written unless one of those options is specified.

--databases, -B

Dump several databases. Normally, mysqldump treats the first name argument on the command line as a database name and following names as table names. With this option, it treats all name arguments as database names. CREATE DATABASE and USE statements are included in the output before each new database.

--no-create-db, -n

This option suppresses the CREATE DATABASE statements that are otherwise included in the output if the --databases or --all-databases option is given.

Some time ago, there was similar question actually asking about not having such statement on the beginning of the file (for XML file). Link to that question is here.

So to answer your question:

  • if you have one database to dump, you should have the --add-drop-database option in your mysqldump statement.
  • if you have multiple databases to dump, you should use the option --databases or --all-databases and the CREATE DATABASE syntax will be added automatically

More information at MySQL Reference Manual

%Like% Query in spring JpaRepository

The spring data JPA query needs the "%" chars as well as a space char following like in your query, as in

@Query("Select c from Registration c where c.place like %:place%").

Cf. http://docs.spring.io/spring-data/jpa/docs/current/reference/html.

You may want to get rid of the @Queryannotation alltogether, as it seems to resemble the standard query (automatically implemented by the spring data proxies); i.e. using the single line

List<Registration> findByPlaceContaining(String place);

is sufficient.

Limiting the number of characters per line with CSS

If you use CSS to select a monospace font, the problem of varying character length is easily solved.

How to overlay density plots in R?

You can use the ggjoy package. Let's say that we have three different beta distributions such as:

set.seed(5)
b1<-data.frame(Variant= "Variant 1", Values = rbeta(1000, 101, 1001))
b2<-data.frame(Variant= "Variant 2", Values = rbeta(1000, 111, 1011))
b3<-data.frame(Variant= "Variant 3", Values = rbeta(1000, 11, 101))


df<-rbind(b1,b2,b3)

You can get the three different distributions as follows:

library(tidyverse)
library(ggjoy)


ggplot(df, aes(x=Values, y=Variant))+
    geom_joy(scale = 2, alpha=0.5) +
    scale_y_discrete(expand=c(0.01, 0)) +
    scale_x_continuous(expand=c(0.01, 0)) +
    theme_joy()

enter image description here

Git log out user from command line

I came across this same problem, and the above answer didn't work for me because github was being fed my credentials through windows credential manager instead of git bash.

You may have to check windows credential manager and delete the github entry under control panel > user accounts > credential manager > Windows credentials > Generic credentials

How to size an Android view based on its parent's dimensions

Roman, if you want to do your layout in Java code (ViewGroup descendant), it is possible. The trick is that you have to implement both onMeasure and onLayout methods. The onMeasure gets called first and you need to "measure" the subview (effectively sizing it to the desired value) there. You need to size it again in the onLayout call. If you fail to do this sequence or fail to call setMeasuredDimension() at the end of your onMeasure code, you won't get results. Why is this designed in such complicated and fragile way is beyond me.

jQuery '.each' and attaching '.click' event

One solution you could use is to assign a more generalized class to any div you want the click event handler bound to.

For example:

HTML:

<body>
<div id="dog" class="selected" data-selected="false">dog</div>
<div id="cat" class="selected" data-selected="true">cat</div>
<div id="mouse" class="selected" data-selected="false">mouse</div>

<div class="dog"><img/></div>
<div class="cat"><img/></div>
<div class="mouse"><img/></div>
</body>

JS:

$( ".selected" ).each(function(index) {
    $(this).on("click", function(){
        // For the boolean value
        var boolKey = $(this).data('selected');
        // For the mammal value
        var mammalKey = $(this).attr('id'); 
    });
});

Error: No default engine was specified and no extension was provided

You are missing the view engine, for example use jade:

change your

app.set('view engine', 'html');

with

app.set('view engine', 'jade');

If you want use a html friendly syntax use instead ejs

app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

EDIT

As you can read from view.js Express View Module

module.exports = View;

/**
 * Initialize a new `View` with the given `name`.
 *
 * Options:
 *
 *   - `defaultEngine` the default template engine name
 *   - `engines` template engine require() cache
 *   - `root` root path for view lookup
 *
 * @param {String} name
 * @param {Object} options
 * @api private
 */

function View(name, options) {
  options = options || {};
  this.name = name;
  this.root = options.root;
  var engines = options.engines;
  this.defaultEngine = options.defaultEngine;
  var ext = this.ext = extname(name);
  if (!ext && !this.defaultEngine) throw new Error('No default engine was specified and no extension was provided.');
  if (!ext) name += (ext = this.ext = ('.' != this.defaultEngine[0] ? '.' : '') + this.defaultEngine);
  this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express);
  this.path = this.lookup(name);
}

You must have installed a default engine

Express search default layout view by program.template as you can read below:

mkdir(path + '/views', function(){
      switch (program.template) {
        case 'ejs':
          write(path + '/views/index.ejs', ejsIndex);
          break;
        case 'jade':
          write(path + '/views/layout.jade', jadeLayout);
          write(path + '/views/index.jade', jadeIndex);
          break;
        case 'jshtml':
          write(path + '/views/layout.jshtml', jshtmlLayout);
          write(path + '/views/index.jshtml', jshtmlIndex);
          break;
        case 'hjs':
          write(path + '/views/index.hjs', hoganIndex);
          break;

      }
    });

and as you can read below:

program.template = 'jade';
if (program.ejs) program.template = 'ejs';
if (program.jshtml) program.template = 'jshtml';
if (program.hogan) program.template = 'hjs';

the default view engine is jade

Why does ASP.NET webforms need the Runat="Server" attribute?

Pretty redundant attribute, considering the "asp" tag is obviously an ASP element and should be enough to identify it as a server side accessible element.

Elsewhere however it used to elevate normal tags to be used in the code-behind.

m2e lifecycle-mapping not found

this step works on me : 1. Remove your project on eclipse 2. Re import project 3. Delete target folder on your project 4. mvn or mvnw install

Protect image download

No there actually is no way to prevent a user from doing a particular task. But you can always take measures! The image sharing websites have a huge team of developers working day and night to create such an algorithm where you prevent user from saving the image files.

First way

Try this:

$('img').mousedown(function (e) {
  if(e.button == 2) { // right click
    return false; // do nothing!
  }
}

So the user won't be able to click on the Save Image As... option from the menu and in turn he won't get a chance to save the image.

Second way

Other way is to use background-image. This way, the user won't be able to right click and Save the Image As... But he can still see the resources in the Inspector.

Third way

Even I am new to this one, few days ago I was surfing Flickr when I tried to right click, it did not let me do a thing. Which in turn was the first method that I provided you with. Then I tried to go and see the inspector, there I found nothing. Why? Since they were using background-image and at the same time they were using data:imagesource as its location.

Which was amazing for me too. You can precvent user from saving image files this way easily.

It is known as Data URI Scheme: http://en.wikipedia.org/wiki/Data_URI_scheme

Note

Please remember brother, when you're letting a user surf your website you're giving him READ permissions on the server side so he can read all the files without any problem. The same is the issue with image files. He can read the image files, and then he can easily save them. He downloads the images on the first place when he is surfing your website. So there is not an issue for him to save them on his disk.

Simple way to create matrix of random numbers

random_matrix = [[random.random for j in range(collumns)] for i in range(rows)
for i in range(rows):
    print random_matrix[i]

SyntaxError: Use of const in strict mode?

One important step after you update your node is to link your node binary to the latest installed node version

sudo ln -sf /usr/local/n/versions/node/6.0.0/bin/node /usr/bin/node  

Extension mysqli is missing, phpmyadmin doesn't work

I solved this problem by editing /usr/local/zend/etc/php.ini.

(found it by doing netstat -nlp ¦ grep apache, then strace -p somepid ¦ grep php.ini).

At the end of the file, I added:

extension=/usr/lib/php5/20090626+lfs/mysql.so
extension=/usr/lib/php5/20090626+lfs/mysqli.so
extension=/usr/lib/php5/20090626+lfs/mcrypt.so

Adding it without the path did not work.

Then after a restart it worked.

How can I get the image url in a Wordpress theme?

I had to use Stylesheet directory to work for me.

<img src="<?php echo get_stylesheet_directory_uri(); ?>/images/image.png">

Shell - How to find directory of some command?

If you're using Bash or zsh, use this:

type -a lshw

This will show whether the target is a builtin, a function, an alias or an external executable. If the latter, it will show each place it appears in your PATH.

bash$ type -a lshw
lshw is /usr/bin/lshw
bash$ type -a ls
ls is aliased to `ls --color=auto'
ls is /bin/ls
bash$ zsh
zsh% type -a which
which is a shell builtin
which is /usr/bin/which

In Bash, for functions type -a will also display the function definition. You can use declare -f functionname to do the same thing (you have to use that for zsh, since type -a doesn't).

ImportError: No module named sklearn.cross_validation

train_test_split is now in model_selection. Just type:

from sklearn.model_selection import train_test_split

it should work

Generating random numbers with normal distribution in Excel

Use the NORMINV function together with RAND():

=NORMINV(RAND(),10,7)

To keep your set of random values from changing, select all the values, copy them, and then paste (special) the values back into the same range.


Sample output (column A), 500 numbers generated with this formula:

enter image description here

How to change an element's title attribute using jQuery

Before we write any code, let's discuss the difference between attributes and properties. Attributes are the settings you apply to elements in your HTML markup; the browser then parses the markup and creates DOM objects of various types that contain properties initialized with the values of the attributes. On DOM objects, such as a simple HTMLElement, you almost always want to be working with its properties, not its attributes collection.

The current best practice is to avoid working with attributes unless they are custom or there is no equivalent property to supplement it. Since title does indeed exist as a read/write property on many HTMLElements, we should take advantage of it.

You can read more about the difference between attributes and properties here or here.

With this in mind, let's manipulate that title...

Get or Set an element's title property without jQuery

Since title is a public property, you can set it on any DOM element that supports it with plain JavaScript:

document.getElementById('yourElementId').title = 'your new title';

Retrieval is almost identical; nothing special here:

var elementTitle = document.getElementById('yourElementId').title;

This will be the fastest way of changing the title if you're an optimization nut, but since you wanted jQuery involved:

Get or Set an element's title property with jQuery (v1.6+)

jQuery introduced a new method in v1.6 to get and set properties. To set the title property on an element, use:

$('#yourElementId').prop('title', 'your new title');

If you'd like to retrieve the title, omit the second parameter and capture the return value:

var elementTitle = $('#yourElementId').prop('title');

Check out the prop() API documentation for jQuery.

If you really don't want to use properties, or you're using a version of jQuery prior to v1.6, then you should read on:

Get or Set an element's title attribute with jQuery (versions <1.6)

You can change the title attribute with the following code:

$('#yourElementId').attr('title', 'your new title');

Or retrieve it with:

var elementTitle = $('#yourElementId').attr('title');

Check out the attr() API documentation for jQuery.

how to drop database in sqlite?

The concept of creating or dropping a database is not meaningful for an embedded database engine like SQLite. It only has meaning with a client-sever database system, such as used by MySQL or Postgres.

To create a new database, just do sqlite_open() or from the command line sqlite3 databasefilename.

To drop a database, delete the file.

Reference: sqlite - Unsupported SQL

Converting time stamps in excel to dates

This DATE-thing won't work in all Excel-versions.

=CELL_ID/(60 * 60 * 24) + "1/1/1970"

is a save bet instead.
The quotes are necessary to prevent Excel from calculating the term.

How to query for Xml values and attributes from table in SQL Server?

Actually you're close to your goal, you just need to use nodes() method to split your rows and then get values:

select
    s.SqmId,
    m.c.value('@id', 'varchar(max)') as id,
    m.c.value('@type', 'varchar(max)') as type,
    m.c.value('@unit', 'varchar(max)') as unit,
    m.c.value('@sum', 'varchar(max)') as [sum],
    m.c.value('@count', 'varchar(max)') as [count],
    m.c.value('@minValue', 'varchar(max)') as minValue,
    m.c.value('@maxValue', 'varchar(max)') as maxValue,
    m.c.value('.', 'nvarchar(max)') as Value,
    m.c.value('(text())[1]', 'nvarchar(max)') as Value2
from sqm as s
    outer apply s.data.nodes('Sqm/Metrics/Metric') as m(c)

sql fiddle demo

In c# is there a method to find the max of 3 numbers?

Let's assume that You have a List<int> intList = new List<int>{1,2,3} if You want to get a max value You could do

int maxValue = intList.Max();

Checking if a worksheet-based checkbox is checked

Building on the previous answers, you can leverage the fact that True is -1 and False is 0 and shorten your code like this:

Sub Button167_Click()
  Range("Y12").Value = _
    Abs(Worksheets(1).Shapes("Check Box 1").OLEFormat.Object.Value > 0)
End Sub

If the checkbox is checked, .Value = 1.

Worksheets(1).Shapes("Check Box 1").OLEFormat.Object.Value > 0 returns True.

Applying the Abs function converts True to 1.

If the checkbox is unchecked, .Value = -4146.

Worksheets(1).Shapes("Check Box 1").OLEFormat.Object.Value > 0 returns False.

Applying the Abs function converts False to 0.

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'

Try to move:

apply plugin: 'com.google.gms.google-services'

just below:

apply plugin: 'com.android.application'

In your module Gradle file, then make sure all Google service's have the version 9.0.0.

Make sure that only this build tools is used:

classpath 'com.android.tools.build:gradle:2.1.0'

Make sure in gradle-wrapper.properties:

distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip

After all above is correct, then make menu File -> Invalidate caches and restart.

Completely cancel a rebase

You are lucky that you didn't complete the rebase, so you can still do git rebase --abort. If you had completed the rebase (it rewrites history), things would have been much more complex. Consider tagging the tips of branches before doing potentially damaging operations (particularly history rewriting), that way you can rewind if something blows up.

Can I write into the console in a unit test? If yes, why doesn't the console window open?

NOTE: The original answer below should work for any version of Visual Studio up through Visual Studio 2012. Visual Studio 2013 does not appear to have a Test Results window any more. Instead, if you need test-specific output you can use @Stretch's suggestion of Trace.Write() to write output to the Output window.


The Console.Write method does not write to the "console" -- it writes to whatever is hooked up to the standard output handle for the running process. Similarly, Console.Read reads input from whatever is hooked up to the standard input.

When you run a unit test through Visual Studio 2010, standard output is redirected by the test harness and stored as part of the test output. You can see this by right-clicking the Test Results window and adding the column named "Output (StdOut)" to the display. This will show anything that was written to standard output.

You could manually open a console window, using P/Invoke as sinni800 says. From reading the AllocConsole documentation, it appears that the function will reset stdin and stdout handles to point to the new console window. (I'm not 100% sure about that; it seems kind of wrong to me if I've already redirected stdout for Windows to steal it from me, but I haven't tried.)

In general, though, I think it's a bad idea; if all you want to use the console for is to dump more information about your unit test, the output is there for you. Keep using Console.WriteLine the way you are, and check the output results in the Test Results window when it's done.

What is MVC and what are the advantages of it?

It separates Model and View controlled by a Controller, As far as Model is concerned, Your Models has to follow OO architecture, future enhancements and other maintenance of the code base should be very easy and the code base should be reusable.

Same model can have any no.of views e.g) same info can be shown in as different graphical views. Same view can have different no.of models e.g) different detailed can be shown as a single graph say as a bar graph. This is what is re-usability of both View and Model.

Enhancements in views and other support of new technologies for building the view can be implemented easily.

Guy who is working on view dose not need to know about the underlying Model code base and its architecture, vise versa for the model.

How to set thymeleaf th:field value from other variable

It has 2 possible solutions:

1) You can set it in the view by javascript... (not recomended)

<input class="form-control"
       type="text"
       id="tbFormControll"
       th:field="*{clientName}"/>

<script type="text/javascript">
        document.getElementById("tbFormControll").value = "default";
</script>

2) Or the better solution is to set the value in the model, that you attach to the view in GET operation by a controller. You can also change the value in the controller, just make a Java object from $client.name and call setClientName.

public class FormControllModel {
    ...
    private String clientName = "default";
    public String getClientName () {
        return clientName;
    }
    public void setClientName (String value) {
        clientName = value;
    }
    ...
}

I hope it helps.

How to update Python?

I have always just installed the new version on top and never had any issues. Do make sure that your path is updated to point to the new version though.

How to find if a given key exists in a C++ std::map

Use map::find

if ( m.find("f") == m.end() ) {
  // not found
} else {
  // found
}

Sort JavaScript object by key

ES6 - here is the 1 liner

_x000D_
_x000D_
var data = { zIndex:99,
             name:'sravan',
             age:25, 
             position:'architect',
             amount:'100k',
             manager:'mammu' };

console.log(Object.entries(data).sort().reduce( (o,[k,v]) => (o[k]=v,o), {} ));
_x000D_
_x000D_
_x000D_

There has been an error processing your request, Error log record number

When magento mode is default it showws such error Change magento mode to developer with

php bin/magento deploy:mode:set developer

then check your error on your browser and resolve that

Read and write a text file in typescript

import { readFileSync } from 'fs';

const file = readFileSync('./filename.txt', 'utf-8');

This worked for me. You may need to wrap the second command in any function or you may need to declare inside a class without keyword const.

Do fragments really need an empty constructor?

As noted by CommonsWare in this question https://stackoverflow.com/a/16064418/1319061, this error can also occur if you are creating an anonymous subclass of a Fragment, since anonymous classes cannot have constructors.

Don't make anonymous subclasses of Fragment :-)

Git Server Like GitHub?

You can even install GitHub on your local server (but not for free):

https://enterprise.github.com/

Iterate through <select> options

$("#selectId > option").each(function() {
    alert(this.text + ' ' + this.value);
});

How can the error 'Client found response content type of 'text/html'.. be interpreted

The webserver is returning an http 500 error code. These errors generally happen when an exception in thrown on the webserver and there's no logic to catch it so it spits out an http 500 error. You can usually resolve the problem by placing try-catch blocks in your code.

Facebook api: (#4) Application request limit reached

now Application-Level Rate Limiting 200 calls per hour !

you can look this image.enter image description here

Is null check needed before calling instanceof?

Very good question indeed. I just tried for myself.

public class IsInstanceOfTest {

    public static void main(final String[] args) {

        String s;

        s = "";

        System.out.println((s instanceof String));
        System.out.println(String.class.isInstance(s));

        s = null;

        System.out.println((s instanceof String));
        System.out.println(String.class.isInstance(s));
    }
}

Prints

true
true
false
false

JLS / 15.20.2. Type Comparison Operator instanceof

At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

API / Class#isInstance(Object)

If this Class object represents an interface, this method returns true if the class or any superclass of the specified Object argument implements this interface; it returns false otherwise. If this Class object represents a primitive type, this method returns false.

Linq with group by having count

Below solution may help you.

var unmanagedDownloadcountwithfilter = from count in unmanagedDownloadCount.Where(d =>d.downloaddate >= startDate && d.downloaddate <= endDate)
group count by count.unmanagedassetregistryid into grouped
where grouped.Count() > request.Download
select new
{
   UnmanagedAssetRegistryID = grouped.Key,
   Count = grouped.Count()
};

Creating composite primary key in SQL Server

If you use management studio, simply select the wardNo, BHTNo, testID columns and click on the key mark in the toolbar.

enter image description here

Command for this is,

ALTER TABLE dbo.testRequest
ADD CONSTRAINT PK_TestRequest 
PRIMARY KEY (wardNo, BHTNo, TestID)

How to style the parent element when hovering a child element?

This is extremely easy to do in Sass! Don't delve into JavaScript for this. The & selector in sass does exactly this.

http://thesassway.com/intermediate/referencing-parent-selectors-using-ampersand

how to get bounding box for div element in jquery

using JQuery:

myelement=$("#myelement")
[myelement.offset().left, myelement.offset().top,  myelement.width(), myelement.height()]

Using isKindOfClass with Swift

I would use:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    super.touchesBegan(touches, withEvent: event)
    let touch : UITouch = touches.anyObject() as UITouch

    if let touchView = touch.view as? UIPickerView
    {

    }
}

How to check if an element is off-screen

  • Get the distance from the top of the given element
  • Add the height of the same given element. This will tell you the total number from the top of the screen to the end of the given element.
  • Then all you have to do is subtract that from total document height

    jQuery(function () {
        var documentHeight = jQuery(document).height();
        var element = jQuery('#you-element');
        var distanceFromBottom = documentHeight - (element.position().top + element.outerHeight(true));
        alert(distanceFromBottom)
    });
    

Android: Use a SWITCH statement with setOnClickListener/onClick for more than 1 button?

I make it simple, if the layout is same i just put the intent it.

My code like this:

public class RegistrationMenuActivity extends AppCompatActivity implements View.OnClickListener {


    private Button btnCertificate, btnSeminarKit;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registration_menu);

        initClick();
    }

    private void initClick() {
        btnCertificate = (Button) findViewById(R.id.btn_Certificate);
        btnCertificate.setOnClickListener(this);

        btnSeminarKit = (Button) findViewById(R.id.btn_SeminarKit);
        btnSeminarKit.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_Certificate:
                break;
            case R.id.btn_SeminarKit:
                break;
        }
        Intent intent = new Intent(RegistrationMenuActivity.this, ScanQRCodeActivity.class);
        startActivity(intent);
    }
}

Asserting successive calls to a mock method

Usually, I don't care about the order of the calls, only that they happened. In that case, I combine assert_any_call with an assertion about call_count.

>>> import mock
>>> m = mock.Mock()
>>> m(1)
<Mock name='mock()' id='37578160'>
>>> m(2)
<Mock name='mock()' id='37578160'>
>>> m(3)
<Mock name='mock()' id='37578160'>
>>> m.assert_any_call(1)
>>> m.assert_any_call(2)
>>> m.assert_any_call(3)
>>> assert 3 == m.call_count
>>> m.assert_any_call(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "[python path]\lib\site-packages\mock.py", line 891, in assert_any_call
    '%s call not found' % expected_string
AssertionError: mock(4) call not found

I find doing it this way to be easier to read and understand than a large list of calls passed into a single method.

If you do care about order or you expect multiple identical calls, assert_has_calls might be more appropriate.

Edit

Since I posted this answer, I've rethought my approach to testing in general. I think it's worth mentioning that if your test is getting this complicated, you may be testing inappropriately or have a design problem. Mocks are designed for testing inter-object communication in an object oriented design. If your design is not objected oriented (as in more procedural or functional), the mock may be totally inappropriate. You may also have too much going on inside the method, or you might be testing internal details that are best left unmocked. I developed the strategy mentioned in this method when my code was not very object oriented, and I believe I was also testing internal details that would have been best left unmocked.

c# Image resizing to different size while preserving aspect ratio

This should do it.

private void resizeImage(string path, string originalFilename, 
                     /* note changed names */
                     int canvasWidth, int canvasHeight, 
                     /* new */
                     int originalWidth, int originalHeight)
{
    Image image = Image.FromFile(path + originalFilename);

    System.Drawing.Image thumbnail = 
        new Bitmap(canvasWidth, canvasHeight); // changed parm names
    System.Drawing.Graphics graphic = 
                 System.Drawing.Graphics.FromImage(thumbnail);

    graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
    graphic.SmoothingMode = SmoothingMode.HighQuality;
    graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
    graphic.CompositingQuality = CompositingQuality.HighQuality;

    /* ------------------ new code --------------- */

    // Figure out the ratio
    double ratioX = (double) canvasWidth / (double) originalWidth;
    double ratioY = (double) canvasHeight / (double) originalHeight;
    // use whichever multiplier is smaller
    double ratio = ratioX < ratioY ? ratioX : ratioY;

    // now we can get the new height and width
    int newHeight = Convert.ToInt32(originalHeight * ratio);
    int newWidth = Convert.ToInt32(originalWidth * ratio);

    // Now calculate the X,Y position of the upper-left corner 
    // (one of these will always be zero)
    int posX = Convert.ToInt32((canvasWidth - (originalWidth * ratio)) / 2);
    int posY = Convert.ToInt32((canvasHeight - (originalHeight * ratio)) / 2);

    graphic.Clear(Color.White); // white padding
    graphic.DrawImage(image, posX, posY, newWidth, newHeight);

    /* ------------- end new code ---------------- */

    System.Drawing.Imaging.ImageCodecInfo[] info =
                     ImageCodecInfo.GetImageEncoders();
    EncoderParameters encoderParameters;
    encoderParameters = new EncoderParameters(1);
    encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality,
                     100L);            
    thumbnail.Save(path + newWidth + "." + originalFilename, info[1], 
                     encoderParameters);
}

Edited to add:

Those who want to improve this code should put it in the comments, or a new answer. Don't edit this code directly.

addClass and removeClass in jQuery - not removing class

What happens is that your close button is placed inside your .clickable div, so the click event will be triggered in both elements.

The event bubbling will make the click event propagate from the child nodes to their parents. So your .close_button callback will be executed first, and when .clickable is reached, it will toggle the classes again. As this run very fast you can't notice the two events happened.

                    / \
--------------------| |-----------------
| .clickable        | |                |
|   ----------------| |-----------     |
|   | .close_button | |          |     |
|   ------------------------------     |
|             event bubbling           |
----------------------------------------

To prevent your event from reaching .clickable, you need to add the event parameter to your callback function and then call the stopPropagation method on it.

$(".close_button").click(function (e) { 
    $("#spot1").addClass("spot");
    $("#spot1").removeClass("grown");
    e.stopPropagation();
});

Fiddle: http://jsfiddle.net/u4GCk/1/

More info about event order in general: http://www.quirksmode.org/js/events_order.html (that's where I picked that pretty ASCII art =])

how to convert a string to date in mysql?

As was told at MySQL Using a string column with date text as a date field, you can do

SELECT  STR_TO_DATE(yourdatefield, '%m/%d/%Y')
FROM    yourtable

You can also handle these date strings in WHERE clauses. For example

SELECT whatever
  FROM yourtable
 WHERE STR_TO_DATE(yourdatefield, '%m/%d/%Y') > CURDATE() - INTERVAL 7 DAY

You can handle all kinds of date/time layouts this way. Please refer to the format specifiers for the DATE_FORMAT() function to see what you can put into the second parameter of STR_TO_DATE().

Web API Put Request generates an Http 405 Method Not Allowed error

I'm running an ASP.NET MVC 5 application on IIS 8.5. I tried all the variations posted here, and this is what my web.config looks like:

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
        <remove name="WebDAVModule"/> <!-- add this -->
    </modules>  
    <handlers>      
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="WebDAV" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers> 
</system.webServer>

I couldn't uninstall WebDav from my Server because I didn't have admin privileges. Also, sometimes I was getting the method not allowed on .css and .js files. In the end, with the configuration above set up everything started working again.

JavaScript override methods

Not unless you make all variables "public", i.e. make them members of the Function either directly or through the prototype property.

var C = function( ) {
    this.x = 10 , this.y = 20 ;
    this.modify = function( ) {
        this.x = 30 , this.y = 40 ;
        console.log("(!) C >> " + (this.x + this.y) ) ;
    } ;
} ;

var A = function( ) {
    this.modify = function( ) {
       this.x = 300 , this.y = 400 ;
       console.log("(!) A >> " + (this.x + this.y) ) ;
    } ;
} ;
    A.prototype = new C ;

var B = function( ) {
    this.modify = function( ) {
       this.x = 3000 , this.y = 4000 ;
       console.log("(!) B >> " + (this.x + this.y) ) ;
    } ;
} ;


new C( ).modify( ) ;
new A( ).modify( ) ;
new B( ).modify( ) ; 

You will notice a few changes.

Most importantly the call to the supposed "super-classes" constructor is now implicit within this line:

<name>.prototype = new C ;

Both A and B will now have individually modifiable members x and y which would not be the case if we would have written ... = C instead.

Then, x, y and modify are all "public" members so that assigning a different Function to them

 <name>.prototype.modify = function( ) { /* ... */ }

will "override" the original Function by that name.

Lastly, the call to modify cannot be done in the Function declaration because the implicit call to the "super-class" would then be executed again when we set the supposed "super-class" to the prototype property of the supposed "sub-classes".

But well, this is more or less how you would do this kind of thing in JavaScript.

HTH,

FK

How can I convert an HTML element to a canvas element?

the next code can be used in 2 modes, mode 1 save the html code to a image, mode 2 save the html code to a canvas.

this code work with the library: https://github.com/tsayen/dom-to-image

*the "id_div" is the id of the element html that you want to transform.

**the "canvas_out" is the id of the div that will contain the canvas so try this code. :

   function Guardardiv(id_div){

      var mode = 2 // default 1 (save to image), mode 2 = save to canvas
      console.log("Process start");
      var node = document.getElementById(id_div);
      // get the div that will contain the canvas
      var canvas_out = document.getElementById('canvas_out');
      var canvas = document.createElement('canvas');
      canvas.width = node.scrollWidth;
      canvas.height = node.scrollHeight;

      domtoimage.toPng(node).then(function (pngDataUrl) {
          var img = new Image();
          img.onload = function () {
          var context = canvas.getContext('2d');
          context.drawImage(img, 0, 0);
        };

        if (mode == 1){ // save to image
             downloadURI(pngDataUrl, "salida.png");
        }else if (mode == 2){ // save to canvas
          img.src = pngDataUrl;
          canvas_out.appendChild(img);

        }
      console.log("Process finish");
    });

    }

so, if you want to save to image just add this function:

    function downloadURI(uri, name) {
        var link = document.createElement("a");

        link.download = name;
        link.href = uri;
        document.body.appendChild(link);
        link.click();   
    }

Example of use:

 <html>
 <head>
 </script src="/dom-to-image.js"></script>
 </head> 
 <body>
 <div id="container">
   All content that want to transform
  </div>
  <button onclick="Guardardiv('container');">Convert<button> 

 <!-- if use mode 2 -->
 <div id="canvas_out"></div>
 </html>

Comment if that work. Comenten si les sirvio :)

curl Failed to connect to localhost port 80

If anyone else comes across this and the accepted answer doesn't work (it didn't for me), check to see if you need to specify a port other than 80. In my case, I was running a rails server at localhost:3000 and was just using curl http://localhost, which was hitting port 80.

Changing the command to curl http://localhost:3000 is what worked in my case.

Accessing dictionary value by index in python

While you can do

value = d.values()[index]

It should be faster to do

value = next( v for i, v in enumerate(d.itervalues()) if i == index )

edit: I just timed it using a dict of len 100,000,000 checking for the index at the very end, and the 1st/values() version took 169 seconds whereas the 2nd/next() version took 32 seconds.

Also, note that this assumes that your index is not negative

How to restart a rails server on Heroku?

heroku ps:restart [web|worker] --app app_name

works for all processes declared in your Procfile. So if you have multiple web processes or worker processes, each labeled with a number, you can selectively restart one of them:

heroku ps:restart web.2 --app app_name
heroku ps:restart worker.3 --app app_name

Rename multiple columns by names

There are a few answers mentioning the functions dplyr::rename_with and rlang::set_names already. By they are separate. this answer illustrates the differences between the two and the use of functions and formulas to rename columns.

rename_with from the dplyr package can use either a function or a formula to rename a selection of columns given as the .cols argument. For example passing the function name toupper:

library(dplyr)
rename_with(head(iris), toupper, starts_with("Petal"))

Is equivalent to passing the formula ~ toupper(.x):

rename_with(head(iris), ~ toupper(.x), starts_with("Petal"))

When renaming all columns, you can also use set_names from the rlang package. To make a different example, let's use paste0 as a renaming function. pasteO takes 2 arguments, as a result there are different ways to pass the second argument depending on whether we use a function or a formula.

rlang::set_names(head(iris), paste0, "_hi")
rlang::set_names(head(iris), ~ paste0(.x, "_hi"))

The same can be achieved with rename_with by passing the data frame as first argument .data, the function as second argument .fn, all columns as third argument .cols=everything() and the function parameters as the fourth argument .... Alternatively you can place the second, third and fourth arguments in a formula given as the second argument.

rename_with(head(iris), paste0, everything(), "_hi")
rename_with(head(iris), ~ paste0(.x, "_hi"))

rename_with only works with data frames. set_names is more generic and can also perform vector renaming

rlang::set_names(1:4, c("a", "b", "c", "d"))

check null,empty or undefined angularjs

You can use angular's function called angular.isUndefined(value) returns boolean.

You may read more about angular's functions here: AngularJS Functions (isUndefined)

Add CSS to iFrame

Based on solution You've already found How to apply CSS to iframe?:

var cssLink = document.createElement("link") 
cssLink.href = "file://path/to/style.css"; 
cssLink .rel = "stylesheet"; 
cssLink .type = "text/css"; 
frames['iframe'].document.body.appendChild(cssLink);

or more jqueryish (from Append a stylesheet to an iframe with jQuery):

var $head = $("iframe").contents().find("head");                
$head.append($("<link/>", 
    { rel: "stylesheet", href: "file://path/to/style.css", type: "text/css" }));

as for security issues: Disabling same-origin policy in Safari

updating Google play services in Emulator

Use emulator that has Play Store installed. Updating play services would be as easy as in real device.

Since Google introduced Google Play Store images in Android SDK Tools 26.0.0 now emulators comes with installed Google Play Store.

enter image description here

From 26.0.3

  • Adds a new tab in the extended window for Google Play Store images that displays the Play Services version and a button to check for updates to Play Services.

emulator settings

Is it possible to use a div as content for Twitter's Popover

Late to the party. Building off the other solutions. I needed a way to pass the target DIV as a variable. Here is what I did.

HTML for Popover source (added a data attribute data-pop that will hold value for destination DIV id/or class):

<div data-html="true" data-toggle="popover" data-pop="popper-content" class="popper">

HTML for Popover content (I am using bootstrap hide class):

<div id="popper-content" class="hide">Content goes here</div>

Script:

$('.popper').popover({
placement: popover_placement,
container: 'div.page-content',
html: true,
trigger: 'hover',
content: function () {
    var pop_dest = $(this).attr("data-pop");
    //console.log(plant);
    return $("#"+pop_dest).html();
}});

Generate UML Class Diagram from Java Project

How about the Omondo Plugin for Eclipse. I have used it and I find it to be quite useful. Although if you are generating diagrams for large sources, you might have to start Eclipse with more memory.

Setting cursor at the end of any text of a textbox

For Windows Forms you can control cursor position (and selection) with txtbox.SelectionStart and txtbox.SelectionLength properties. If you want to set caret to end try this:

txtbox.SelectionStart = txtbox.Text.Length;
txtbox.SelectionLength = 0;

For WPF see this question.

bootstrap datepicker setDate format dd/mm/yyyy

This line of code works for me

$("#datepicker").datepicker("option", "dateFormat", "dd/mm/yy");

you can change the id #datepicker with the class .input-group.date of course

How do I change select2 box height

I am using Select2 4.0. This works for me. I only have one Select2 control.

.select2-selection.select2-selection--multiple {
    min-height: 25px;
    max-height: 25px;
}

How to add default value for html <textarea>?

Placeholder cannot set the default value for text area. You can use

<textarea rows="10" cols="55" name="description"> /*Enter default value here to display content</textarea>

This is the tag if you are using it for database connection. You may use different syntax if you are using other languages than php.For php :

e.g.:

<textarea rows="10" cols="55" name="description" required><?php echo $description; ?></textarea>

required command minimizes efforts needed to check empty fields using php.

CSS3 Rotate Animation

To achieve the 360 degree rotation, here is the Working Solution.

The HTML:

<img class="image" src="your-image.png">

The CSS:

.image {
    overflow: hidden;
    transition-duration: 0.8s;
    transition-property: transform;
}
.image:hover {
    transform: rotate(360deg);
    -webkit-transform: rotate(360deg);
}

You have to hover on the image and you will get the 360 degree rotation effect.

PS: Add a -webkit- extension for it to work on chrome and other webkit browers. You can check the updated fiddle for webkit HERE

How to select and change value of table cell with jQuery?

$("td:contains('c')").html("new");

or, more precisely $("#table_headers td:contains('c')").html("new");

and maybe for reuse you could create a function to call

function ReplaceCellContent(find, replace)
{
    $("#table_headers td:contains('" + find + "')").html(replace);
}