Programs & Examples On #Sharepoint 2010

For SharePoint-specific questions, please see the SharePoint Stack Exchange site at http://sharepoint.stackexchange.com/

Error :The remote server returned an error: (401) Unauthorized

Shouldn't you be providing the credentials for your site, instead of passing the DefaultCredentials?

Something like request.Credentials = new NetworkCredential("UserName", "PassWord");

Also, remove request.UseDefaultCredentials = true; request.PreAuthenticate = true;

exceeds the list view threshold 5000 items in Sharepoint 2010

I had the same problem.please do the following it may help you: By Default List View Threshold set at only 5,000 items this is because of Sharepoint server performance.

To Change the LVT:

  1. Click SharePoint Central Administration,
  2. Go to Application Management
  3. Manage Web Applications
  4. Select your application
  5. Click General Settings at the ribbon
  6. Select Resource Throttling
  7. List View Threshold limit --> change the value to your need.
  8. Also change the List View Threshold for Auditors and Administrators.if you are a administrator.

Click OK to save it.

Could not load file or assembly '' or one of its dependencies

screenshotIn solution explorer right click on project (not solution), in build tab choose Platform target : "Any CPU".

Solving SharePoint Server 2010 - 503. The service is unavailable, After installation

I had the same issue but the password was good and "Log on as batch job" alone was not sufficient.

Check that the IIS application pool identity account or group has both the "Log on as Batch Job" permission AND that it can "impersonate a client after authentication".

To change these settings perform the following steps on the web front end server:

  • Start>Run type "secpol.msc"
    • Find: Security Settings>Local Policies>User Rights assignment
    • Add user or group to "Log on as Batch Job"
    • Check group membership of service account (in Active Directory) if a particular group is being used for this purpose.
    • Find "impersonate a client after authentication" and add the application pool identity
    • Reboot the server

You should be able to access the site!

Can two or more people edit an Excel document at the same time?

No, sadly:

The Excel 2010 client application does not support co-authoring workbooks in SharePoint Server 2010. However, the Excel client application does support non-real-time co-authoring workbooks stored locally or on network (UNC) paths by using the Shared Workbook feature. Co-authoring workbooks in SharePoint is supported by using the Microsoft Excel Web App, included with Office Web Apps

From Co-authoring overview (SharePoint Server 2010)

...and not for SharePoint 2013 either. Though it works for pretty much all other Office documents. Go figure.

Are global variables bad?

My professor used to say something like: using global variables are okay if you use them correctly. I don't think I ever got good at using them correctly, so I rarely used them at all.

Why can't Python import Image from PIL?

Any library/package you import must have its dependencies and subordinate parts in the same python directory. in linux if you

Python3.x -m pip install <your_library_name_without_braces>

what happens is, it installs on the default python. so first make sure that only 1 python 2.x and 1 python 3.x versions are on your pc.

If you want to successfully install matplotlib you need these lines,

python -m pip install matplotlib pillow numpy pandas

the last 2 were auxiliary libs, and must have.

How to get current moment in ISO 8601 format with date, hour, and minute?

tl;dr

Some of the other Answers are correct in recommending java.time classes but go about using unnecessary lengths for your specific needs.

Instant.now()                               // Capture the current moment in UTC with a resolution as fines nanoseconds but usually in microseconds or milliseconds.
       .truncatedTo( ChronoUnit.MINUTES )   // Lop off any seconds or fractional second, to get a value in whole minutes.
       .toString()                          // Generate a String in standard ISO 8601 format where a `T` separates the year-month-day from the hour-minute-second, and the `Z` on the end for “Zulu” means UTC.

2018-01-23T12:34Z

Instant::toString

The jav.time.Instant class represents a moment in UTC, always in UTC.

Instant instant = Instant.now() ;

instant.toString(): 2018-01-23T12:34:56.123456Z

The Z on the end of your example string 2010-10-12T08:50Z is pronounced “Zulu” and means UTC.

Your desired format happens to comply with the ISO 8601 standard. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern. Just call Instant::toString as seen above.

If you specifically want whole minutes without second or fractional second, then truncate. Specify a unit of time via ChronoUnit class.

Instant instant = Instant.now().truncatedTo( ChronoUnit.MINUTES ) ;
String output = instant.toString();  // Generate a `String` object in standard ISO 8601 format.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Return 0 if field is null in MySQL

Use IFNULL:

IFNULL(expr1, 0)

From the documentation:

If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns expr2. IFNULL() returns a numeric or string value, depending on the context in which it is used.

Python map object is not subscriptable

In Python 3, map returns an iterable object of type map, and not a subscriptible list, which would allow you to write map[i]. To force a list result, write

payIntList = list(map(int,payList))

However, in many cases, you can write out your code way nicer by not using indices. For example, with list comprehensions:

payIntList = [pi + 1000 for pi in payList]
for pi in payIntList:
    print(pi)

jQuery Dialog Box

I had the same problem and was looking for a way to solve it which brought me here. After reviewing the suggestion made from RaeLehman it led me to the solution. Here's my implementation.

In my $(document).ready event I initialize my dialog with the autoOpen set to false. I also chose to bind a click event to an element, like a button, which will open my dialog.

$(document).ready(function(){

    // Initialize my dialog
    $("#dialog").dialog({
        autoOpen: false,
        modal: true,
        buttons: {
        "OK":function() { // do something },
        "Cancel": function() { $(this).dialog("close"); }
    }
    });

    // Bind to the click event for my button and execute my function
    $("#x-button").click(function(){
        Foo.DoSomething();
    });
});

Next, I make sure that the function is defined and that is where I implement the dialog open method.

var Foo = {
    DoSomething: function(){
        $("#dialog").dialog("open");
    }
}

By the way, I tested this in IE7 and Firefox and it works fine. Hope this helps!

Change app language programmatically in Android

Create a class Extends Application and create a static method. Then you can call this method in all activities before setContentView().

public class MyApp extends Application {

@Override
public void onCreate() {
    super.onCreate();
}

public static void setLocaleFa (Context context){
    Locale locale = new Locale("fa"); 
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    config.locale = locale;
    context.getApplicationContext().getResources().updateConfiguration(config, null);
}

public static void setLocaleEn (Context context){
    Locale locale = new Locale("en_US"); 
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    config.locale = locale;
    context.getApplicationContext().getResources().updateConfiguration(config, null);
}

}

Usage in activities:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    MyApp.setLocaleFa(MainActivity.this);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);
}

Java System.out.print formatting

Are you sure that you want "055" as opposed to "55"? Some programs interpret a leading zero as meaning octal, so that it would read 055 as (decimal) 45 instead of (decimal) 55.

That should just mean dropping the '0' (zero-fill) flag.

e.g., change System.out.printf("%03d ", x); to the simpler System.out.printf("%3d ", x);

How to make correct date format when writing data to Excel

To format by code Date in Excel cells try this:

Excel.Range rg = (Excel.Range)xlWorkSheet.Cells[numberRow, numberColumn];

rg.NumberFormat = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;

After this you can set the DateTime value to specific cell

xlWorkSheet.Cells[numberRow, numberColumn] = myDate;

If you want to set entire column try this: Excel.Range rg = (Excel.Range)xlWorkSheet.Cells[numberRow, numberColumn];

rg.EntireColumn.NumberFormat = 
    CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;

Unstage a deleted file in git

From manual page,

git-reset - Reset current HEAD to the specified state
git reset [-q] [<tree-ish>] [--] <paths>...
In the first and second form, copy entries from <tree-ish> to the index.

for example, when we use git reset HEAD~1 it reset our current HEAD to HEAD~1

so when we use git reset 'some-deleted-file-path'

git assume 'some-deleted-file-path' as some commit point and try to reset out current HEAD to there.

And it ends up fail

fatal: ambiguous argument 'some-deleted-file-path': unknown revision or path not in the working tree.

CSS: 100% width or height while keeping aspect ratio?

Use JQuery or so, as CSS is a general misconception (the countless questions and discussions here about simple design goals show that).

It is not possible with CSS to do what you seem to wish: image shall have width of 100%, but if this width results in a height that is too large, a max-height shall apply - and of course the correct proportions shall be preserved.

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test

I had a similar problem, and the solution for me was quite different from what the other users posted.

The problem with me was related to the project I was working last year, which required a certain proxy on maven settings (located at <path to maven folder>\maven\conf\settings.xml and C:\Users\<my user>\.m2\settings.xml). The proxy was blocking the download of required external packages.

The solution was to put back the original file (settings.xml) on those places. Once things were restored, I was able to download the packages and everything worked.

Remove padding from columns in Bootstrap 3

None of the above solutions worked perfectly for me. Following this answer I was able to create something that works for me. Here I am also using a media query to limit this to small screens only.

@media (max-width: @screen-sm) {
    [class*="col-"] {
      padding-left: 0;
      padding-right: 0;
    }
    .row {
      margin-left: 0;
      margin-right: 0;
    }
    .container-fluid {
      margin: 0;
      padding: 0;
    }
}

ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result"

Your program does not know what precision for decimal numbers to use so it throws:

java.lang.ArithmeticException: Non-terminating decimal expansion

Solution to bypass exception:

MathContext precision = new MathContext(int setPrecisionYouWant); // example 2
BigDecimal a = new BigDecimal("1.6",precision);
BigDecimal b = new BigDecimal("9.2",precision);
a.divide(b) // result = 0.17

How to change Jquery UI Slider handle

This change only first handle in multihandle slider. In apiDoc you can see:"For example, if you specify values: [ 1, 5, 18 ] and create one custom handle, the plugin will create the other two."

Reverse a string in Python

To solve this in programing way for interview

def reverse_a_string(string: str) -> str:
    """
    This method is used to reverse a string.
    Args:
        string: a string to reverse

    Returns: a reversed string
    """
    if type(string) != str:
        raise TypeError("{0} This not a string, Please provide a string!".format(type(string)))
    string_place_holder = ""
    start = 0
    end = len(string) - 1
    if end >= 1:
        while start <= end:
            string_place_holder = string_place_holder + string[end]
            end -= 1
        return string_place_holder
    else:
        return string


a = "hello world"
rev = reverse_a_string(a)
print(rev)

Output:

dlrow olleh

Can gcc output C code after preprocessing?

Suppose we have a file as Message.cpp or a .c file

Steps 1: Preprocessing (Argument -E )

g++ -E .\Message.cpp > P1

P1 file generated has expanded macros and header file contents and comments are stripped off.

Step 2: Translate Preprocessed file to assembly (Argument -S). This task is done by compiler

g++ -S .\Message.cpp

An assembler (ASM) is generated (Message.s). It has all the assembly code.

Step 3: Translate assembly code to Object code. Note: Message.s was generated in Step2. g++ -c .\Message.s

An Object file with the name Message.o is generated. It is the binary form.

Step 4: Linking the object file. This task is done by linker

g++ .\Message.o -o MessageApp

An exe file MessageApp.exe is generated here.

#include <iostream>
using namespace std;

 //This a sample program
  int main()
{
cout << "Hello" << endl;
 cout << PQR(P,K) ;
getchar();
return 0;
}

Get value of div content using jquery

$('#field-function_purpose') will get you the element with ID field-function_purpose, which is your div element. text() returns you the content of the div.

var x = $('#field-function_purpose').text();

Callback when DOM is loaded in react.js

I applied componentDidUpdate to table to have all columns same height. it works same as on $(window).load() in jquery.

eg:

componentDidUpdate: function() {
        $(".tbl-tr").height($(".tbl-tr ").height());
    }

Executing a batch file in a remote machine through PsExec

Here's my current solution to run any code remotely on a given machine or list of machines asynchronously with logging, too!

@echo off
:: by Ralph Buchfelder, thanks to Mark Russinovich and Rob van der Woude for their work!
:: requires PsExec.exe to be in the same directory (download from http://technet.microsoft.com/de-de/sysinternals/bb897553.aspx)
:: troubleshoot remote commands with PsExec arguments -i or -s if neccessary (see http://forum.sysinternals.com/pstools_forum8.html)
:: will run *in parallel* on a list of remote pcs (if given); to run serially please remove 'START "" CMD.EXE /C' from the psexec call


:: help
if '%1' =='-h' (
 echo.
 echo %~n0
 echo.
 echo Runs a command on one or many remote machines. If no input parameters
 echo are given you will be asked for a target remote machine.
 echo.
 echo You will be prompted for remote credentials with elevated privileges.
 echo.
 echo UNC paths and local paths can be supplied.
 echo Commands will be executed on the remote side just the way you typed
 echo them, so be sure to mind extensions and the path variable!
 echo.
 echo Please note that PsExec.exe must be allowed on remote machines, i.e.
 echo not blocked by firewall or antivirus solutions.
 echo.
 echo Syntax: %~n0 [^<inputfile^>]
 echo.
 echo     inputfile      = a plain text file ^(one hostname or ip address per line^)
 echo.
 echo.
 echo Example:
 echo %~n0 mylist.txt
 exit /b 0
)


:checkAdmin
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
if '%errorlevel%' neq '0' (
 echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
 echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
 "%temp%\getadmin.vbs"
 del "%temp%\getadmin.vbs"
 exit /B
)
set ADMINTESTDIR=%WINDIR%\System32\Test_%RANDOM%
mkdir "%ADMINTESTDIR%" 2>NUL
if errorlevel 1 (
 cls
 echo ERROR: This script requires elevated privileges!
 echo.
 echo Launch by Right-Click / Run as Administrator ...
 pause
 exit /b 1
) else (
 rd /s /q "%ADMINTESTDIR%"
 echo Running with elevated privileges...
)
echo.


:checkRequirements
if not exist "%~dp0PsExec.exe" (
 echo PsExec.exe from Sysinternals/Microsoft not found 
 echo in %~dp0
 echo.
 echo Download from http://technet.microsoft.com/de-de/sysinternals/bb897553.aspx
 echo.
 pause
 exit /B
)


:environment
setlocal
echo.
echo %~n0
echo _____________________________
echo.
echo Working directory:  %cd%\
echo Script directory:   %~dp0
echo.
SET /P REMOTE_USER=Domain\Administrator : 
SET "psCommand=powershell -Command "$pword = read-host 'Kennwort' -AsSecureString ; ^
    $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
        [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set REMOTE_PASS=%%p
if NOT DEFINED REMOTE_PASS SET /P REMOTE_PASS=Password             : 
echo.
if '%1' =='' goto menu
SET REMOTE_LIST=%1


:inputMultipleTargets
if not exist %REMOTE_LIST% (
 echo File %REMOTE_LIST% not found
 goto menu
)
type %REMOTE_LIST% >nul
if '%errorlevel%' neq '0' (
 echo Access denied %REMOTE_LIST%
 goto menu
)
set batchProcessing=true
echo Batch processing:   %REMOTE_LIST%   ...
ping -n 2 127.0.0.1 >nul
goto runOnce


:menu
if exist "%~dp0last.computer"  set /p LAST_COMPUTER=<"%~dp0last.computer"
if exist "%~dp0last.listing"   set /p LAST_LISTING=<"%~dp0last.listing"
if exist "%~dp0last.directory" set /p LAST_DIRECTORY=<"%~dp0last.directory"
if exist "%~dp0last.command"   set /p LAST_COMMAND=<"%~dp0last.command"
if exist "%~dp0last.timestamp" set /p LAST_TIMESTAMP=<"%~dp0last.timestamp"
echo.
echo.
echo                (1)  select target computer [default]
echo                (2)  select multiple computers
echo                     -----------------------------------
echo                     last target : %LAST_COMPUTER%
echo                     last listing: %LAST_LISTING%
echo                     last path   : %LAST_DIRECTORY%
echo                     last command: %LAST_COMMAND%
echo                     last run    : %LAST_TIMESTAMP%
echo                     -----------------------------------
echo                (0)  exit
echo.
echo ENTER your choice.
echo.
echo.
:mychoice
SET /P mychoice=(0, 1, ...): 
if NOT DEFINED mychoice  goto promptSingleTarget
if "%mychoice%"=="1"     goto promptSingleTarget
if "%mychoice%"=="2"     goto promptMultipleTargets
if "%mychoice%"=="0"     goto end
goto mychoice


:promptMultipleTargets
echo.
echo Please provide an input file
echo [one IP address or hostname per line]
SET /P REMOTE_LIST=Filename             : 
goto inputMultipleTargets


:promptSingleTarget
SET batchProcessing=
echo.
echo Please provide a hostname
SET /P REMOTE_COMPUTER=Target computer      : 
goto runOnce


:runOnce
cls
echo Note: Paths are mandatory for CMD-commands (e.g. dir,copy) to work!
echo       Paths are provided on the remote machine via PUSHD.
echo.
SET /P REMOTE_PATH=UNC-Path or folder : 
SET /P REMOTE_CMD=Command with params: 
SET REMOTE_TIMESTAMP=%DATE% %TIME:~0,8%
echo.
echo Remote command starting (%REMOTE_PATH%\%REMOTE_CMD%) on %REMOTE_TIMESTAMP%...
if not defined batchProcessing goto runOnceSingle


:runOnceMulti
REM do for each line; this circumvents PsExec's @file to have stdouts separately
SET REMOTE_LOG=%~dp0\log\%REMOTE_LIST%
if not exist %REMOTE_LOG% md %REMOTE_LOG%
for /F "tokens=*" %%A in (%REMOTE_LIST%) do (
 if "%REMOTE_PATH%" =="" START "" CMD.EXE /C ^(%~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%%A cmd /c "%REMOTE_CMD%" ^>"%REMOTE_LOG%\%%A.log" 2^>"%REMOTE_LOG%\%%A_debug.log" ^)
 if not "%REMOTE_PATH%" =="" START "" CMD.EXE /C ^(%~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%%A cmd /c "pushd %REMOTE_PATH% && %REMOTE_CMD% & popd" ^>"%REMOTE_LOG%\%%A.log" 2^>"%REMOTE_LOG%\%%A_debug.log" ^)
)
goto restart


:runOnceSingle
SET REMOTE_LOG=%~dp0\log
if not exist %REMOTE_LOG% md %REMOTE_LOG%
if "%REMOTE_PATH%" =="" %~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%REMOTE_COMPUTER% cmd /c "%REMOTE_CMD%" >"%REMOTE_LOG%\%REMOTE_COMPUTER%.log" 2>"%REMOTE_LOG%\%REMOTE_COMPUTER%_debug.log"
if not "%REMOTE_PATH%" =="" %~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%REMOTE_COMPUTER% cmd /c "pushd %REMOTE_PATH% && %REMOTE_CMD% & popd" >"%REMOTE_LOG%\%REMOTE_COMPUTER%.log" 2>"%REMOTE_LOG%\%REMOTE_COMPUTER%_debug.log"
goto restart


:restart
echo.
echo.
echo Batch completed. Finished with last errorlevel %errorlevel% .
echo All outputs have been saved to %~dp0log\%REMOTE_TIMESTAMP%\.
echo %REMOTE_PATH% >"%~dp0last.directory"
echo %REMOTE_CMD% >"%~dp0last.command"
echo %REMOTE_LIST% >"%~dp0last.listing"
echo %REMOTE_COMPUTER% >"%~dp0last.computer"
echo %REMOTE_TIMESTAMP% >"%~dp0last.timestamp"
SET REMOTE_PATH=
SET REMOTE_CMD=
SET REMOTE_LIST=
SET REMOTE_COMPUTER=
SET REMOTE_LOG=
SET REMOTE_TIMESTAMP=
ping -n 2 127.0.0.1 >nul
goto menu


:end
SET REMOTE_USER=
SET REMOTE_PASS=

How to hide soft keyboard on android after clicking outside EditText?

Just Add this code in the class @Overide

public boolean dispatchTouchEvent(MotionEvent ev) {
    View view = getCurrentFocus();
    if (view != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) && view instanceof EditText && !view.getClass().getName().startsWith("android.webkit.")) {
        int scrcoords[] = new int[2];
        view.getLocationOnScreen(scrcoords);
        float x = ev.getRawX() + view.getLeft() - scrcoords[0];
        float y = ev.getRawY() + view.getTop() - scrcoords[1];
        if (x < view.getLeft() || x > view.getRight() || y < view.getTop() || y > view.getBottom())
            ((InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow((this.getWindow().getDecorView().getApplicationWindowToken()), 0);
    }
    return super.dispatchTouchEvent(ev);
}

ESLint - "window" is not defined. How to allow global variables in package.json

I'm aware he's not asking for the inline version. But since this question has almost 100k visits and I fell here looking for that, I'll leave it here for the next fellow coder:

Make sure ESLint is not run with the --no-inline-config flag (if this doesn't sound familiar, you're likely good to go). Then, write this in your code file (for clarity and convention, it's written on top of the file but it'll work anywhere):

/* eslint-env browser */

This tells ESLint that your working environment is a browser, so now it knows what things are available in a browser and adapts accordingly.

There are plenty of environments, and you can declare more than one at the same time, for example, in-line:

/* eslint-env browser, node */

If you are almost always using particular environments, it's best to set it in your ESLint's config file and forget about it.

From their docs:

An environment defines global variables that are predefined. The available environments are:

  • browser - browser global variables.
  • node - Node.js global variables and Node.js scoping.
  • commonjs - CommonJS global variables and CommonJS scoping (use this for browser-only code that uses Browserify/WebPack).
  • shared-node-browser - Globals common to both Node and Browser.

[...]

Besides environments, you can make it ignore anything you want. If it warns you about using console.log() but you don't want to be warned about it, just inline:

/* eslint-disable no-console */

You can see the list of all rules, including recommended rules to have for best coding practices.

How to change the blue highlight color of a UITableViewCell?

UITableViewCell has three default selection styles:-

  1. Blue
  2. Gray
  3. None

Implementation is as follows:-

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *) indexPath {

     [cell setSelectionStyle:UITableViewCellSelectionStyleNone];       
}

how to use a like with a join in sql?

Using INSTR:

SELECT *
  FROM TABLE a
  JOIN TABLE b ON INSTR(b.column, a.column) > 0

Using LIKE:

SELECT *
  FROM TABLE a
  JOIN TABLE b ON b.column LIKE '%'+ a.column +'%'

Using LIKE, with CONCAT:

SELECT *
  FROM TABLE a
  JOIN TABLE b ON b.column LIKE CONCAT('%', a.column ,'%')

Mind that in all options, you'll probably want to drive the column values to uppercase BEFORE comparing to ensure you are getting matches without concern for case sensitivity:

SELECT *
  FROM (SELECT UPPER(a.column) 'ua'
         TABLE a) a
  JOIN (SELECT UPPER(b.column) 'ub'
         TABLE b) b ON INSTR(b.ub, a.ua) > 0

The most efficient will depend ultimately on the EXPLAIN plan output.

JOIN clauses are identical to writing WHERE clauses. The JOIN syntax is also referred to as ANSI JOINs because they were standardized. Non-ANSI JOINs look like:

SELECT *
  FROM TABLE a,
       TABLE b
 WHERE INSTR(b.column, a.column) > 0

I'm not going to bother with a Non-ANSI LEFT JOIN example. The benefit of the ANSI JOIN syntax is that it separates what is joining tables together from what is actually happening in the WHERE clause.

Add Whatsapp function to website, like sms, tel

I just posted an answer on a thread similiar to this here https://stackoverflow.com/a/43357241/3958617

The approach with:

<a href="whatsapp://send?abid=username&text=Hello%2C%20World!">whatsapp</a>

and with

<a href="intent://send/0123456789#Intent;scheme=smsto;package=com.whatsapp;action=android.intent.action.SENDTO;end">whatsapp</a>

Only works if the person who clicked on your link have your number on their contact list.

Since not everybody will have it, the other solution is to use Whatsapp API like this:

<a href="https://api.whatsapp.com/send?phone=15551234567">Send Message</a>

Understanding Apache's access log

And what does "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.5 Safari/535.19" means ?

This is the value of User-Agent, the browser identification string.

For this reason, most Web browsers use a User-Agent string value as follows:

Mozilla/[version] ([system and browser information]) [platform] ([platform details]) [extensions]. For example, Safari on the iPad has used the following:

Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405 The components of this string are as follows:

Mozilla/5.0: Previously used to indicate compatibility with the Mozilla rendering engine. (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us): Details of the system in which the browser is running. AppleWebKit/531.21.10: The platform the browser uses. (KHTML, like Gecko): Browser platform details. Mobile/7B405: This is used by the browser to indicate specific enhancements that are available directly in the browser or through third parties. An example of this is Microsoft Live Meeting which registers an extension so that the Live Meeting service knows if the software is already installed, which means it can provide a streamlined experience to joining meetings.

This value will be used to identify what browser is being used by end user.

Refer

What do I need to do to get Internet Explorer 8 to accept a self signed certificate?

Unfortunately none of the solutions worked for me. I used Internet Explorer 8 on Windows 7. When I was looking for a solution, I found the settings about login information in the control panel. So I added a new entry under the certificate based information with the address of my server and I chose my prefered certificate.

After a clear of the SSL cache in Internet Explorer 8 I just refreshed the site and the right certificate was sent to the server.

This isn't the solution which I wanted, but it works.

Adding header to all request with Retrofit 2

Kotlin version would be

fun getHeaderInterceptor():Interceptor{
    return object : Interceptor {
        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain): Response {
            val request =
            chain.request().newBuilder()
                    .header(Headers.KEY_AUTHORIZATION, "Bearer.....")
                    .build()
            return chain.proceed(request)
        }
    }
}


private fun createOkHttpClient(): OkHttpClient {
    return OkHttpClient.Builder()
            .apply {
                if(BuildConfig.DEBUG){
                    this.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC))
                }
            }
            .addInterceptor(getHeaderInterceptor())
            .build()
}

Get the value of input text when enter key pressed

Try this:

<input type="text" placeholder="some text" class="search" onkeydown="search(this)"/>  
<input type="text" placeholder="some text" class="search" onkeydown="search(this)"/>

JS Code

function search(ele) {
    if(event.key === 'Enter') {
        alert(ele.value);        
    }
}

DEMO Link

Detecting IE11 using CSS Capability/Feature Detection

Here's an answer for 2017 on, where you probably only care about distinguishing <=IE11 from >IE11 ("Edge"):

@supports not (old: ie) { /* code for not old IE here */ }

More demonstrative example:

body:before { content: 'old ie'; }
/**/@supports not (old: ie) {
body:before { content: 'not old ie'; }
/**/}

This works because IE11 doesn't actually even support @supports, and all other relevant browser/version combinations do.

How to get file URL using Storage facade in laravel 5?

This method exists since Laravel 5.4, you can get it by:

$path = Storage::disk('public')->path($filename);

Getting the inputstream from a classpath resource (XML file)

someClassWithinYourSourceDir.getClass().getResourceAsStream();

What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?

A simple snnipet:

 public static String camelCase(String in) {
    if (in == null || in.length() < 1) { return ""; } //validate in
    String out = "";
    for (String part : in.toLowerCase().split("_")) {
        if (part.length() < 1) { //validate length
            continue;
        }
        out += part.substring(0, 1).toUpperCase();
        if (part.length() > 1) { //validate length
            out += part.substring(1);
        }
    }
    return out;
}

How do you convert between 12 hour time and 24 hour time in PHP?

// 24-hour time to 12-hour time 
$time_in_12_hour_format  = date("g:i a", strtotime("13:30"));

// 12-hour time to 24-hour time 
$time_in_24_hour_format  = date("H:i", strtotime("1:30 PM"));

Display PDF file inside my android application

You can download the source from here(Display PDF file inside my android application)

Add this dependency in your gradle file:

compile 'com.github.barteksc:android-pdf-viewer:2.0.3'

activity_main.xml

<RelativeLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    xmlns:android="http://schemas.android.com/apk/res/android" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="@color/colorPrimaryDark"
        android:text="View PDF"
        android:textColor="#ffffff"
        android:id="@+id/tv_header"
        android:textSize="18dp"
        android:gravity="center"></TextView>

    <com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/pdfView"
        android:layout_below="@+id/tv_header"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>


    </RelativeLayout>

MainActivity.java

package pdfviewer.pdfviewer;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;

import java.util.List;

public class MainActivity extends Activity implements OnPageChangeListener,OnLoadCompleteListener{
    private static final String TAG = MainActivity.class.getSimpleName();
    public static final String SAMPLE_FILE = "android_tutorial.pdf";
    PDFView pdfView;
    Integer pageNumber = 0;
    String pdfFileName;

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


        pdfView= (PDFView)findViewById(R.id.pdfView);
        displayFromAsset(SAMPLE_FILE);
    }

    private void displayFromAsset(String assetFileName) {
        pdfFileName = assetFileName;

        pdfView.fromAsset(SAMPLE_FILE)
                .defaultPage(pageNumber)
                .enableSwipe(true)

                .swipeHorizontal(false)
                .onPageChange(this)
                .enableAnnotationRendering(true)
                .onLoad(this)
                .scrollHandle(new DefaultScrollHandle(this))
                .load();
    }


    @Override
    public void onPageChanged(int page, int pageCount) {
        pageNumber = page;
        setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
    }


    @Override
    public void loadComplete(int nbPages) {
        PdfDocument.Meta meta = pdfView.getDocumentMeta();
        printBookmarksTree(pdfView.getTableOfContents(), "-");

    }

    public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
        for (PdfDocument.Bookmark b : tree) {

            Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));

            if (b.hasChildren()) {
                printBookmarksTree(b.getChildren(), sep + "-");
            }
        }
    }

}

KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.

There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.

I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException and Application.ThreadException, as appropriate.

Simple (non-secure) hash function for JavaScript?

Check out this MD5 implementation for JavaScript. Its BSD Licensed and really easy to use. Example:

md5 = hex_md5("message to digest")

Error: TypeError: $(...).dialog is not a function

If you comment out the following code from the _Layout.cshtml page, the modal popup will start working:

    </footer>

    @*@Scripts.Render("~/bundles/jquery")*@
    @RenderSection("scripts", required: false)
    </body>
</html>

How do I convert certain columns of a data frame to become factors?

Given the following sample

myData <- data.frame(A=rep(1:2, 3), B=rep(1:3, 2), Pulse=20:25)  

then

myData$A <-as.factor(myData$A)
myData$B <-as.factor(myData$B)

or you could select your columns altogether and wrap it up nicely:

# select columns
cols <- c("A", "B")
myData[,cols] <- data.frame(apply(myData[cols], 2, as.factor))

levels(myData$A) <- c("long", "short")
levels(myData$B) <- c("1kg", "2kg", "3kg")

To obtain

> myData
      A   B Pulse
1  long 1kg    20
2 short 2kg    21
3  long 3kg    22
4 short 1kg    23
5  long 2kg    24
6 short 3kg    25

HowTo Generate List of SQL Server Jobs and their owners

A colleague told me about this stored procedure...

USE msdb

EXEC dbo.sp_help_job

What is a blob URL and why it is used?

I have modified working solution to handle both the case.. when video is uploaded and when image is uploaded .. hope it will help some.

HTML

<input type="file" id="fileInput">
<div> duration: <span id='sp'></span><div>

Javascript

var fileEl = document.querySelector("input");

fileEl.onchange = function(e) {


    var file = e.target.files[0]; // selected file

    if (!file) {
        console.log("nothing here");
        return;
    }

    console.log(file);
    console.log('file.size-' + file.size);
    console.log('file.type-' + file.type);
    console.log('file.acutalName-' + file.name);

    let start = performance.now();

    var mime = file.type, // store mime for later
        rd = new FileReader(); // create a FileReader

    if (/video/.test(mime)) {

        rd.onload = function(e) { // when file has read:


            var blob = new Blob([e.target.result], {
                    type: mime
                }), // create a blob of buffer
                url = (URL || webkitURL).createObjectURL(blob), // create o-URL of blob
                video = document.createElement("video"); // create video element
            //console.log(blob);
            video.preload = "metadata"; // preload setting

            video.addEventListener("loadedmetadata", function() { // when enough data loads
                console.log('video.duration-' + video.duration);
                console.log('video.videoHeight-' + video.videoHeight);
                console.log('video.videoWidth-' + video.videoWidth);
                //document.querySelector("div")
                //  .innerHTML = "Duration: " + video.duration + "s" + " <br>Height: " + video.videoHeight; // show duration
                (URL || webkitURL).revokeObjectURL(url); // clean up

                console.log(start - performance.now());
                // ... continue from here ...

            });
            video.src = url; // start video load
        };
    } else if (/image/.test(mime)) {
        rd.onload = function(e) {

            var blob = new Blob([e.target.result], {
                    type: mime
                }),
                url = URL.createObjectURL(blob),
                img = new Image();

            img.onload = function() {
                console.log('iamge');
                console.dir('this.height-' + this.height);
                console.dir('this.width-' + this.width);
                URL.revokeObjectURL(this.src); // clean-up memory
                console.log(start - performance.now()); // add image to DOM
            }

            img.src = url;

        };
    }

    var chunk = file.slice(0, 1024 * 1024 * 10); // .5MB
    rd.readAsArrayBuffer(chunk); // read file object

};

jsFiddle Url

https://jsfiddle.net/PratapDessai/0sp3b159/

What is move semantics?

I find it easiest to understand move semantics with example code. Let's start with a very simple string class which only holds a pointer to a heap-allocated block of memory:

#include <cstring>
#include <algorithm>

class string
{
    char* data;

public:

    string(const char* p)
    {
        size_t size = std::strlen(p) + 1;
        data = new char[size];
        std::memcpy(data, p, size);
    }

Since we chose to manage the memory ourselves, we need to follow the rule of three. I am going to defer writing the assignment operator and only implement the destructor and the copy constructor for now:

    ~string()
    {
        delete[] data;
    }

    string(const string& that)
    {
        size_t size = std::strlen(that.data) + 1;
        data = new char[size];
        std::memcpy(data, that.data, size);
    }

The copy constructor defines what it means to copy string objects. The parameter const string& that binds to all expressions of type string which allows you to make copies in the following examples:

string a(x);                                    // Line 1
string b(x + y);                                // Line 2
string c(some_function_returning_a_string());   // Line 3

Now comes the key insight into move semantics. Note that only in the first line where we copy x is this deep copy really necessary, because we might want to inspect x later and would be very surprised if x had changed somehow. Did you notice how I just said x three times (four times if you include this sentence) and meant the exact same object every time? We call expressions such as x "lvalues".

The arguments in lines 2 and 3 are not lvalues, but rvalues, because the underlying string objects have no names, so the client has no way to inspect them again at a later point in time. rvalues denote temporary objects which are destroyed at the next semicolon (to be more precise: at the end of the full-expression that lexically contains the rvalue). This is important because during the initialization of b and c, we could do whatever we wanted with the source string, and the client couldn't tell a difference!

C++0x introduces a new mechanism called "rvalue reference" which, among other things, allows us to detect rvalue arguments via function overloading. All we have to do is write a constructor with an rvalue reference parameter. Inside that constructor we can do anything we want with the source, as long as we leave it in some valid state:

    string(string&& that)   // string&& is an rvalue reference to a string
    {
        data = that.data;
        that.data = nullptr;
    }

What have we done here? Instead of deeply copying the heap data, we have just copied the pointer and then set the original pointer to null (to prevent 'delete[]' from source object's destructor from releasing our 'just stolen data'). In effect, we have "stolen" the data that originally belonged to the source string. Again, the key insight is that under no circumstance could the client detect that the source had been modified. Since we don't really do a copy here, we call this constructor a "move constructor". Its job is to move resources from one object to another instead of copying them.

Congratulations, you now understand the basics of move semantics! Let's continue by implementing the assignment operator. If you're unfamiliar with the copy and swap idiom, learn it and come back, because it's an awesome C++ idiom related to exception safety.

    string& operator=(string that)
    {
        std::swap(data, that.data);
        return *this;
    }
};

Huh, that's it? "Where's the rvalue reference?" you might ask. "We don't need it here!" is my answer :)

Note that we pass the parameter that by value, so that has to be initialized just like any other string object. Exactly how is that going to be initialized? In the olden days of C++98, the answer would have been "by the copy constructor". In C++0x, the compiler chooses between the copy constructor and the move constructor based on whether the argument to the assignment operator is an lvalue or an rvalue.

So if you say a = b, the copy constructor will initialize that (because the expression b is an lvalue), and the assignment operator swaps the contents with a freshly created, deep copy. That is the very definition of the copy and swap idiom -- make a copy, swap the contents with the copy, and then get rid of the copy by leaving the scope. Nothing new here.

But if you say a = x + y, the move constructor will initialize that (because the expression x + y is an rvalue), so there is no deep copy involved, only an efficient move. that is still an independent object from the argument, but its construction was trivial, since the heap data didn't have to be copied, just moved. It wasn't necessary to copy it because x + y is an rvalue, and again, it is okay to move from string objects denoted by rvalues.

To summarize, the copy constructor makes a deep copy, because the source must remain untouched. The move constructor, on the other hand, can just copy the pointer and then set the pointer in the source to null. It is okay to "nullify" the source object in this manner, because the client has no way of inspecting the object again.

I hope this example got the main point across. There is a lot more to rvalue references and move semantics which I intentionally left out to keep it simple. If you want more details please see my supplementary answer.

How do I read all classes from a Java package in the classpath?

I use this one, it works with files or jar archives

public static ArrayList<String>getClassNamesFromPackage(String packageName) throws IOException{
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    URL packageURL;
    ArrayList<String> names = new ArrayList<String>();;

    packageName = packageName.replace(".", "/");
    packageURL = classLoader.getResource(packageName);

    if(packageURL.getProtocol().equals("jar")){
        String jarFileName;
        JarFile jf ;
        Enumeration<JarEntry> jarEntries;
        String entryName;

        // build jar file name, then loop through zipped entries
        jarFileName = URLDecoder.decode(packageURL.getFile(), "UTF-8");
        jarFileName = jarFileName.substring(5,jarFileName.indexOf("!"));
        System.out.println(">"+jarFileName);
        jf = new JarFile(jarFileName);
        jarEntries = jf.entries();
        while(jarEntries.hasMoreElements()){
            entryName = jarEntries.nextElement().getName();
            if(entryName.startsWith(packageName) && entryName.length()>packageName.length()+5){
                entryName = entryName.substring(packageName.length(),entryName.lastIndexOf('.'));
                names.add(entryName);
            }
        }

    // loop through files in classpath
    }else{
    URI uri = new URI(packageURL.toString());
    File folder = new File(uri.getPath());
        // won't work with path which contains blank (%20)
        // File folder = new File(packageURL.getFile()); 
        File[] contenuti = folder.listFiles();
        String entryName;
        for(File actual: contenuti){
            entryName = actual.getName();
            entryName = entryName.substring(0, entryName.lastIndexOf('.'));
            names.add(entryName);
        }
    }
    return names;
}

Java simple code: java.net.SocketException: Unexpected end of file from server

I got this exception too. MY error code is below

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(requestMethod);
        connection.setRequestProperty("Content-type", "JSON");

I found "Content-type" should not be "JSON",is wrong! I solved this exception by update this line to below

        connection.setRequestProperty("Content-type", "application/json");

you can check up your "Content-type"

Cropping images in the browser BEFORE the upload

If you will still use JCrop, you will need only this php functions to crop the file:

$img_src = imagecreatefromjpeg($src);
$img_dest = imagecreatetruecolor($new_w,$new_h);
imagecopyresampled($img_dest,$img_src,0,0,$x,$y,$new_w,$new_h,$w,$h);
imagejpeg($img_dest,$dest);

client side:

jQuery(function($){

    $('#target').Jcrop({
    onChange:   showCoords,
    onSelect:   showCoords,
    onRelease:  clearCoords
    });

});

var x,y,w,h; //these variables are necessary to crop
function showCoords(c)
{
    x = c.x;
    y = c.y;
    w = c.w;
    h = c.h;
};
function clearCoords()
{
    x=y=w=h=0;
}

How to return a specific status code and no contents from Controller?

The best way to do it is:

return this.StatusCode(StatusCodes.Status418ImATeapot, "Error message");

'StatusCodes' has every kind of return status and you can see all of them in this link https://httpstatuses.com/

Once you choose your StatusCode, return it with a message.

How to print a certain line of a file with PowerShell?

This will show the 10th line of myfile.txt:

get-content myfile.txt | select -first 1 -skip 9

both -first and -skip are optional parameters, and -context, or -last may be useful in similar situations.

Pure CSS multi-level drop-down menu

For a menu which responds to click events as opposed to just hover, and acts in a similar way to a select control...

Pure CSS Select Menu

HTML

<ul tabindex='0'>
    <li>
        <input id='item1' type='radio' name='item' checked='true' />
        <label for='item1'>Item 1</label>
    </li>
    <li>
        <input id='item2' type='radio' name='item' />
        <label for='item2'>Item 2</label>
    </li>
    <li>
        <input id='item3' type='radio' name='item' />
        <label for='item3'>Item 3</label>
    </li>
</ul>

CSS

ul, li {
    list-style:none;
    margin:0;
    padding:0;
}
li input {
    display:none;
}
ul:not(:focus) input:not(:checked), ul:not(:focus) input:not(:checked) + label {
    display:none;
}
input:checked+label {
    color:red;
}

Generate a UUID on iOS from Swift

Each time the same will be generated:

if let uuid = UIDevice.current.identifierForVendor?.uuidString {
    print(uuid)
}

Each time a new one will be generated:

let uuid = UUID().uuidString
print(uuid)

How do I select which GPU to run a job on?

In case of someone else is doing it in Python and it is not working, try to set it before do the imports of pycuda and tensorflow.

I.e.:

import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
...
import pycuda.autoinit
import tensorflow as tf
...

As saw here.

Install dependencies globally and locally using package.json

Due to the disadvantages described below, I would recommend following the accepted answer:

Use npm install --save-dev [package_name] then execute scripts with:

$ npm run lint
$ npm run build
$ npm test

My original but not recommended answer follows.


Instead of using a global install, you could add the package to your devDependencies (--save-dev) and then run the binary from anywhere inside your project:

"$(npm bin)/<executable_name>" <arguments>...

In your case:

"$(npm bin)"/node.io --help

This engineer provided an npm-exec alias as a shortcut. This engineer uses a shellscript called env.sh. But I prefer to use $(npm bin) directly, to avoid any extra file or setup.

Although it makes each call a little larger, it should just work, preventing:

  • potential dependency conflicts with global packages (@nalply)
  • the need for sudo
  • the need to set up an npm prefix (although I recommend using one anyway)

Disadvantages:

  • $(npm bin) won't work on Windows.
  • Tools deeper in your dev tree will not appear in the npm bin folder. (Install npm-run or npm-which to find them.)

It seems a better solution is to place common tasks (such as building and minifying) in the "scripts" section of your package.json, as Jason demonstrates above.

Which port we can use to run IIS other than 80?

Well you can disable skype to use port 80. Click tools --> Options --> Advanced --> Connection and uncheck the appropriate checkbox. Skype Screenshot

Pandas: sum DataFrame rows for given columns

The shortest and simpliest way here is to use

    df.eval('e = a + b + d')

Custom toast on Android: a simple example

STEP 1:

First create a layout for a custom toast in res/layout/custom_toast.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_toast_layout_id"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFF"
    android:orientation="horizontal"
    android:padding="5dp" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:textColor="#000" />

</LinearLayout>

STEP 2: In the Activity code, get the above custom view and attach to Toast:

// Get your custom_toast.xml ayout
LayoutInflater inflater = getLayoutInflater();

View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.custom_toast_layout_id));

// set a message
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Button is clicked!");

// Toast...
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

For more help see how we Create custom Toast in Android:

http://developer.android.com/guide/topics/ui/notifiers/toasts.html

How can I exclude one word with grep?

The -v option will show you all the lines that don't match the pattern.

grep -v ^unwanted_word

What is difference between sjlj vs dwarf vs seh?

There's a short overview at MinGW-w64 Wiki:

Why doesn't mingw-w64 gcc support Dwarf-2 Exception Handling?

The Dwarf-2 EH implementation for Windows is not designed at all to work under 64-bit Windows applications. In win32 mode, the exception unwind handler cannot propagate through non-dw2 aware code, this means that any exception going through any non-dw2 aware "foreign frames" code will fail, including Windows system DLLs and DLLs built with Visual Studio. Dwarf-2 unwinding code in gcc inspects the x86 unwinding assembly and is unable to proceed without other dwarf-2 unwind information.

The SetJump LongJump method of exception handling works for most cases on both win32 and win64, except for general protection faults. Structured exception handling support in gcc is being developed to overcome the weaknesses of dw2 and sjlj. On win64, the unwind-information are placed in xdata-section and there is the .pdata (function descriptor table) instead of the stack. For win32, the chain of handlers are on stack and need to be saved/restored by real executed code.

GCC GNU about Exception Handling:

GCC supports two methods for exception handling (EH):

  • DWARF-2 (DW2) EH, which requires the use of DWARF-2 (or DWARF-3) debugging information. DW-2 EH can cause executables to be slightly bloated because large call stack unwinding tables have to be included in th executables.
  • A method based on setjmp/longjmp (SJLJ). SJLJ-based EH is much slower than DW2 EH (penalising even normal execution when no exceptions are thrown), but can work across code that has not been compiled with GCC or that does not have call-stack unwinding information.

[...]

Structured Exception Handling (SEH)

Windows uses its own exception handling mechanism known as Structured Exception Handling (SEH). [...] Unfortunately, GCC does not support SEH yet. [...]

See also:

Truncate Two decimal places without rounding

If you don't worry too much about performance and your end result can be a string, the following approach will be resilient to floating precision issues:

string Truncate(double value, int precision)
{
    if (precision < 0)
    {
        throw new ArgumentOutOfRangeException("Precision cannot be less than zero");
    }

    string result = value.ToString();

    int dot = result.IndexOf('.');
    if (dot < 0)
    {
        return result;
    }

    int newLength = dot + precision + 1;

    if (newLength == dot + 1)
    {
        newLength--;
    }

    if (newLength > result.Length)
    {
        newLength = result.Length;
    }

    return result.Substring(0, newLength);
}

Does Android support near real time push notification?

There is a new open-source effort to develop a Java library for push notifications on Android, using the Meteor comet server as a backend. You can check it out at the Deacon Project Blog. We need developers, so please spread the word!

Jest spyOn function called

You're almost there. Although I agree with @Alex Young answer about using props for that, you simply need a reference to the instance before trying to spy on the method.

describe('my sweet test', () => {
 it('clicks it', () => {
    const app = shallow(<App />)
    const instance = app.instance()
    const spy = jest.spyOn(instance, 'myClickFunc')

    instance.forceUpdate();    

    const p = app.find('.App-intro')
    p.simulate('click')
    expect(spy).toHaveBeenCalled()
 })
})

Docs: http://airbnb.io/enzyme/docs/api/ShallowWrapper/instance.html

YouTube URL in Video Tag

This would be easy to do :

<iframe width="420" height="345"
src="http://www.youtube.com/embed/XGSy3_Czz8k">
</iframe>

Is just an example.

Detecting scroll direction

This is an addition to what prateek has answered.There seems to be a glitch in the code in IE so i decided to modify it a bit nothing fancy(just another condition)

$('document').ready(function() {
var lastScrollTop = 0;
$(window).scroll(function(event){
   var st = $(this).scrollTop();
   if (st > lastScrollTop){
       console.log("down")
   }
   else if(st == lastScrollTop)
   {
     //do nothing 
     //In IE this is an important condition because there seems to be some instances where the last scrollTop is equal to the new one
   }
   else {
      console.log("up")
   }
   lastScrollTop = st;
});});

C# Switch-case string starting with

If you knew that the length of conditions you would care about would all be the same length then you could:

switch(mystring.substring(0, Math.Min(3, mystring.Length))
{
  case "abc":
    //do something
    break;
  case "xyz":
    //do something else
    break;
  default:
    //do a different thing
    break;
}

The Math.Min(3, mystring.Length) is there so that a string of less than 3 characters won't throw an exception on the sub-string operation.

There are extensions of this technique to match e.g. a bunch of 2-char strings and a bunch of 3-char strings, where some 2-char comparisons matching are then followed by 3-char comparisons. Unless you've a very large number of such strings though, it quickly becomes less efficient than simple if-else chaining for both the running code and the person who has to maintain it.

Edit: Added since you've now stated they will be of different lengths. You could do the pattern I mentioned of checking the first X chars and then the next Y chars and so on, but unless there's a pattern where most of the strings are the same length this will be both inefficient and horrible to maintain (a classic case of premature pessimisation).

The command pattern is mentioned in another answer, so I won't give details of that, as is that where you map string patterns to IDs, but they are option.

I would not change from if-else chains to command or mapping patterns to gain the efficiency switch sometimes has over if-else, as you lose more in the comparisons for the command or obtaining the ID pattern. I would though do so if it made code clearer.

A chain of if-else's can work pretty well, either with string comparisons or with regular expressions (the latter if you have comparisons more complicated than the prefix-matches so far, which would probably be simpler and faster, I'm mentioning reg-ex's just because they do sometimes work well with more general cases of this sort of pattern).

If you go for if-elses, try to consider which cases are going to happen most often, and make those tests happen before those for less-common cases (though of course if "starts with abcd" is a case to look for it would have to be checked before "starts with abc").

What is the difference between POST and GET?

POST and GET are two HTTP request methods. GET is usually intended to retrieve some data, and is expected to be idempotent (repeating the query does not have any side-effects) and can only send limited amounts of parameter data to the server. GET requests are often cached by default by some browsers if you are not careful.

POST is intended for changing the server state. It carries more data, and repeating the query is allowed (and often expected) to have side-effects such as creating two messages instead of one.

Why does one use dependency injection?

As the other answers stated, dependency injection is a way to create your dependencies outside of the class that uses it. You inject them from the outside, and take control about their creation away from the inside of your class. This is also why dependency injection is a realization of the Inversion of control (IoC) principle.

IoC is the principle, where DI is the pattern. The reason that you might "need more than one logger" is never actually met, as far as my experience goes, but the actualy reason is, that you really need it, whenever you test something. An example:

My Feature:

When I look at an offer, I want to mark that I looked at it automatically, so that I don't forget to do so.

You might test this like this:

[Test]
public void ShouldUpdateTimeStamp
{
    // Arrange
    var formdata = { . . . }

    // System under Test
    var weasel = new OfferWeasel();

    // Act
    var offer = weasel.Create(formdata)

    // Assert
    offer.LastUpdated.Should().Be(new DateTime(2013,01,13,13,01,0,0));
}

So somewhere in the OfferWeasel, it builds you an offer Object like this:

public class OfferWeasel
{
    public Offer Create(Formdata formdata)
    {
        var offer = new Offer();
        offer.LastUpdated = DateTime.Now;
        return offer;
    }
}

The problem here is, that this test will most likely always fail, since the date that is being set will differ from the date being asserted, even if you just put DateTime.Now in the test code it might be off by a couple of milliseconds and will therefore always fail. A better solution now would be to create an interface for this, that allows you to control what time will be set:

public interface IGotTheTime
{
    DateTime Now {get;}
}

public class CannedTime : IGotTheTime
{
    public DateTime Now {get; set;}
}

public class ActualTime : IGotTheTime
{
    public DateTime Now {get { return DateTime.Now; }}
}

public class OfferWeasel
{
    private readonly IGotTheTime _time;

    public OfferWeasel(IGotTheTime time)
    {
        _time = time;
    }

    public Offer Create(Formdata formdata)
    {
        var offer = new Offer();
        offer.LastUpdated = _time.Now;
        return offer;
    }
}

The Interface is the abstraction. One is the REAL thing, and the other one allows you to fake some time where it is needed. The test can then be changed like this:

[Test]
public void ShouldUpdateTimeStamp
{
    // Arrange
    var date = new DateTime(2013, 01, 13, 13, 01, 0, 0);
    var formdata = { . . . }

    var time = new CannedTime { Now = date };

    // System under test
    var weasel= new OfferWeasel(time);

    // Act
    var offer = weasel.Create(formdata)

    // Assert
    offer.LastUpdated.Should().Be(date);
}

Like this, you applied the "inversion of control" principle, by injecting a dependency (getting the current time). The main reason to do this is for easier isolated unit testing, there are other ways of doing it. For example, an interface and a class here is unnecessary since in C# functions can be passed around as variables, so instead of an interface you could use a Func<DateTime> to achieve the same. Or, if you take a dynamic approach, you just pass any object that has the equivalent method (duck typing), and you don't need an interface at all.

You will hardly ever need more than one logger. Nonetheless, dependency injection is essential for statically typed code such as Java or C#.

And... It should also be noted that an object can only properly fulfill its purpose at runtime, if all its dependencies are available, so there is not much use in setting up property injection. In my opinion, all dependencies should be satisfied when the constructor is being called, so constructor-injection is the thing to go with.

I hope that helped.

Which selector do I need to select an option by its text?

This works for me

var options = $(dropdown).find('option');
var targetOption = $(options).filter(
function () { return $(this).html() == value; });

console.log($(targetOption).val());

Thanks for all the posts.

How do you connect to a MySQL database using Oracle SQL Developer?

Under Tools > Preferences > Databases there is a third party JDBC driver path that must be setup. Once the driver path is setup a separate 'MySQL' tab should appear on the New Connections dialog.

Note: This is the same jdbc connector that is available as a JAR download from the MySQL website.

document.getElementByID is not a function

I've modified your script to work with jQuery, if you wish to do so.

$(document).ready(function(){
    //To add a task when the user hits the return key
    $('#task-text').keydown(function(evt){
          if(evt.keyCode == 13)
          {
             add_task($(this), evt);
          }
    });
    //To add a task when the user clicks on the submit button
    $("#add-task").click(function(evt){
        add_task($("#task-text"),evt);
    });
});

function add_task(textBox, evt){
  evt.preventDefault();
  var taskText = textBox.val();
  $("<li />").text(taskText).appendTo("#tasks");
  textBox.val("");
};

Determine whether a key is present in a dictionary

In terms of bytecode, in saves a LOAD_ATTR and replaces a CALL_FUNCTION with a COMPARE_OP.

>>> dis.dis(indict)
  2           0 LOAD_GLOBAL              0 (name)
              3 LOAD_GLOBAL              1 (d)
              6 COMPARE_OP               6 (in)
              9 POP_TOP             


>>> dis.dis(haskey)
  2           0 LOAD_GLOBAL              0 (d)
              3 LOAD_ATTR                1 (haskey)
              6 LOAD_GLOBAL              2 (name)
              9 CALL_FUNCTION            1
             12 POP_TOP             

My feelings are that in is much more readable and is to be preferred in every case that I can think of.

In terms of performance, the timing reflects the opcode

$ python -mtimeit -s'd = dict((i, i) for i in range(10000))' "'foo' in d"
 10000000 loops, best of 3: 0.11 usec per loop

$ python -mtimeit -s'd = dict((i, i) for i in range(10000))' "d.has_key('foo')"
  1000000 loops, best of 3: 0.205 usec per loop

in is almost twice as fast.

Check variable equality against a list of values

For posterity you might want to use regular expressions as an alternative. Pretty good browser support as well (ref. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match#Browser_compatibility)

Try this

if (foo.toString().match(/^(1|3|12)$/)) {
    document.write('Regex me IN<br>');
} else {
    document.write('Regex me OUT<br>');
}

Why is python setup.py saying invalid command 'bdist_wheel' on Travis CI?

I already had wheel installed so I tried to uninstall and reinstall, and it fixed the issue:

pip uninstall wheel
pip install wheel

Weird...

How to get HTTP Response Code using Selenium WebDriver

You could try Mobilenium (https://github.com/rafpyprog/Mobilenium), a python package that binds BrowserMob Proxy and Selenium.

An usage example:

>>> from mobilenium import mobidriver
>>>
>>> browsermob_path = 'path/to/browsermob-proxy'
>>> mob = mobidriver.Firefox(browsermob_binary=browsermob_path)
>>> mob.get('http://python-requests.org')
301
>>> mob.response['redirectURL']
'http://docs.python-requests.org'
>>> mob.headers['Content-Type']
'application/json; charset=utf8'
>>> mob.title
'Requests: HTTP for Humans \u2014 Requests 2.13.0 documentation'
>>> mob.find_elements_by_tag_name('strong')[1].text
'Behold, the power of Requests'

React Native absolute positioning horizontal centre

create a full-width View with alignItems: "center" then insert desired children inside.

import React from "react";
import {View} from "react-native";

export default class AbsoluteComponent extends React.Component {
  render(){
    return(
     <View style={{position: "absolute", left: 0, right: 0, alignItems: "center"}}>
      {this.props.children}
     </View>    
    )
  }
}

you can add properties like bottom: 30 for bottom aligned component.

Javascript split regex question

Say your string is:

let str = `word1
word2;word3,word4,word5;word7
word8,word9;word10`;

You want to split the string by the following delimiters:

  • Colon
  • Semicolon
  • New line

You could split the string like this:

let rawElements = str.split(new RegExp('[,;\n]', 'g'));

Finally, you may need to trim the elements in the array:

let elements = rawElements.map(element => element.trim());

PHP: Read Specific Line From File

You could try looping until the line you want, not the EOF, and resetting the variable to the line each time (not adding to it). In your case, the 2nd line is the EOF. (A for loop is probably more appropriate in my code below).

This way the entire file is not in the memory; the drawback is it takes time to go through the file up to the point you want.

<?php 
$myFile = "4-24-11.txt";
$fh = fopen($myFile, 'r');
$i = 0;
while ($i < 2)
 {
  $theData = fgets($fh);
  $i++
 }
fclose($fh);
echo $theData;
?>

Find all elements on a page whose element ID contains a certain text using jQuery

Thanks to both of you. This worked perfectly for me.

$("input[type='text'][id*=" + strID + "]:visible").each(function() {
    this.value=strVal;
});

Prevent row names to be written to file when using write.csv

write.csv(t, "t.csv", row.names=FALSE)

From ?write.csv:

row.names: either a logical value indicating whether the row names of
          ‘x’ are to be written along with ‘x’, or a character vector
          of row names to be written.

JAVA Unsupported major.minor version 51.0

This is because of a higher JDK during compile time and lower JDK during runtime. So you just need to update your JDK version, possible to JDK 7

You may also check Unsupported major.minor version 51.0

mysql update multiple columns with same now()

You can put the following code on the default value of the timestamp column: CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, so on update the two columns take the same value.

Media Queries - In between two widths

just wanted to leave my .scss example here, I think its kinda best practice, especially I think if you do customization its nice to set the width only once! It is not clever to apply it everywhere, you will increase the human factor exponentially.

Im looking forward for your feedback!

// Set your parameters
$widthSmall: 768px;
$widthMedium: 992px;

// Prepare your "function"
@mixin in-between {
     @media (min-width:$widthSmall) and (max-width:$widthMedium) {
        @content;
     }
}


// Apply your "function"
main {
   @include in-between {
      //Do something between two media queries
      padding-bottom: 20px;
   }
}

What Are The Best Width Ranges for Media Queries

Try this one with retina display

/* Smartphones (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen 
and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen 
and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) {
/* Styles */
}

/* Desktops and laptops ----------- */
@media only screen 
and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen 
and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}

Update

/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) {
  /* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen and (min-width: 321px) {
  /* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen and (max-width: 320px) {
  /* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) {
  /* Styles */
}

/* iPads (landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) {
  /* Styles */
}

/* iPads (portrait) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: portrait) {
  /* Styles */
}

/* iPad 3 (landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPad 3 (portrait) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* Desktops and laptops ----------- */
@media only screen and (min-width: 1224px) {
  /* Styles */
}

/* Large screens ----------- */
@media only screen and (min-width: 1824px) {
  /* Styles */
}

/* iPhone 4 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: landscape) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 4 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 5 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 5 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6 (landscape) ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6 (portrait) ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6+ (landscape) ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6+ (portrait) ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S3 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S3 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S4 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S4 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S5 (landscape) ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S5 (portrait) ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

Clear text field value in JQuery

Instead of all those:

$('#doc_title').attr("value", "");

var self = this?

var functionX = function() {
  var self = this;
  var functionY = function(y) {
    // If we call "this" in here, we get a reference to functionY,
    // but if we call "self" (defined earlier), we get a reference to function X.
  }
}

edit: in spite of, nested functions within an object takes on the global window object rather than the surrounding object.

How to iterate over rows in a DataFrame in Pandas

The easiest way, use the apply function

def print_row(row):
   print row['c1'], row['c2']

df.apply(lambda row: print_row(row), axis=1)

Vertical alignment of text and icon in button

Just wrap the button label in an extra span and add class="align-middle" to both (the icon and the label). This will center your icon with text vertical.

<button id="edit-listing-form-house_Continue" 
    class="btn btn-large btn-primary"
    style=""
    value=""
    name="Continue"
    type="submit">
<span class="align-middle">Continue</span>
<i class="icon-ok align-middle" style="font-size:40px;"></i>

How to determine if object is in array

I used underscore javascript library to tweak this issue.

function containsObject(obj, list) {
 var res = _.find(list, function(val){ return _.isEqual(obj, val)});
 return (_.isObject(res))? true:false;
}

please refer to underscore.js documentation for the underscore functions used in the above example.

note: This is not a pure javascript solution. Shared for educational purposes.

Send a SMS via intent

/**
 * Intent to Send SMS
 * 
 *
 * Extras:
 *
 * "subject"
 *      A string for the message subject (usually for MMS only).
 * "sms_body"
 *      A string for the text message.
 *  EXTRA_STREAM
 *      A Uri pointing to the image or video to attach.
 *
 *  For More Info:
 *  https://developer.android.com/guide/components/intents-common#SendMessage
 *
 * @param phoneNumber on which SMS to send
 * @param message text Message to send with SMS
 */
public void startSMSIntent(String phoneNumber, String message) {
    Intent intent = new Intent(Intent.ACTION_SENDTO);
    // This ensures only SMS apps respond
    intent.setData(Uri.parse("smsto:"+phoneNumber));
    intent.putExtra("sms_body", message);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

Why is semicolon allowed in this python snippet?

Python does let you use a semi-colon to denote the end of a statement if you are including more than one statement on a line.

Enable CORS in Web API 2

For reference using the [EnableCors()] approach will not work if you intercept the Message Pipeline using a DelegatingHandler. In my case was checking for an Authorization header in the request and handling it accordingly before the routing was even invoked, which meant my request was getting processed earlier in the pipeline so the [EnableCors()] had no effect.

In the end found an example CrossDomainHandler class (credit to shaunxu for the Gist) which handles the CORS for me in the pipeline and to use it is as simple as adding another message handler to the pipeline.

public class CrossDomainHandler : DelegatingHandler
    {
        const string Origin = "Origin";
        const string AccessControlRequestMethod = "Access-Control-Request-Method";
        const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
        const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
        const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
        const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            bool isCorsRequest = request.Headers.Contains(Origin);
            bool isPreflightRequest = request.Method == HttpMethod.Options;
            if (isCorsRequest)
            {
                if (isPreflightRequest)
                {
                    return Task.Factory.StartNew(() =>
                    {
                        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                        response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());

                        string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
                        if (accessControlRequestMethod != null)
                        {
                            response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
                        }

                        string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
                        if (!string.IsNullOrEmpty(requestedHeaders))
                        {
                            response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
                        }

                        return response;
                    }, cancellationToken);
                }
                else
                {
                    return base.SendAsync(request, cancellationToken).ContinueWith(t =>
                    {
                        HttpResponseMessage resp = t.Result;
                        resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
                        return resp;
                    });
                }
            }
            else
            {
                return base.SendAsync(request, cancellationToken);
            }
        }
    }

To use it add it to the list of registered message handlers

config.MessageHandlers.Add(new CrossDomainHandler());

Any preflight requests by the Browser are handled and passed on, meaning I didn't need to implement an [HttpOptions] IHttpActionResult method on the Controller.

How to check if curl is enabled or disabled

Just return your existing check from a function.

function _isCurl(){
    return function_exists('curl_version');
}

TortoiseGit save user authentication / credentials

If you are a windows 10 + TortoiseGit 2.7 user:

  1. for the first time login, simply follow the prompts to enter your credentials and save password.
  2. If you ever need to update your credentials, don't waste your time at the TortoiseGit settings. Instead, windows search>Credential Manager> Windows Credentials > find your git entry > Edit.

Removing all line breaks and adding them after certain text

You can also go to Notepad++ and do the following steps:

Edit->LineOperations-> Remove Empty Lines or Remove Empty Lines(Containing blank characters)

C#: how to get first char of a string?

Following example for getting first character from a string might help someone

string anyNameForString = "" + stringVariableName[0];

Get Root Directory Path of a PHP project

For PHP >= 5.3.0 try

PHP magic constants.

__DIR__

And make your path relative.

For PHP < 5.3.0 try

dirname(__FILE__)

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

I prepared following commands to find concise information about a Linux system:

clear
echo "\n----------OS Information------------"
hostnamectl | grep "Static hostname:"
hostnamectl | tail -n 3
echo "\n----------Memory Information------------"
cat /proc/meminfo | grep MemTotal
echo "\n----------CPU Information------------"
echo -n "Number of core(s): "
cat /proc/cpuinfo | grep "processor" | wc -l
cat /proc/cpuinfo | grep "model name" | head -n 1
echo "\n----------Disk Information------------"
echo -n "Total Size: "
df -h --total | tail -n 1| awk '{print $2}'
echo -n "Used: "
df -h --total | tail -n 1| awk '{print $3}'
echo -n "Available: "
df -h --total | tail -n 1| awk '{print $4}'
echo "\n-------------------------------------\n"

Copy and paste in an sh file like info.sh and then run it using command sh info.sh

Convert hexadecimal string (hex) to a binary string

public static byte[] hexToBin(String str)
    {
        int len = str.length();
        byte[] out = new byte[len / 2];
        int endIndx;

        for (int i = 0; i < len; i = i + 2)
        {
            endIndx = i + 2;
            if (endIndx > len)
                endIndx = len - 1;
            out[i / 2] = (byte) Integer.parseInt(str.substring(i, endIndx), 16);
        }
        return out;
    }

Convert NULL to empty string - Conversion failed when converting from a character string to uniqueidentifier

Select ID, IsNull(Cast(ParentID as varchar(max)),'') from Patients

This is needed because field ParentID is not varchar/nvarchar type. This will do the trick:

Select ID, IsNull(ParentID,'') from Patients

How to remove all the occurrences of a char in c++ string

#include <string>
#include <algorithm>
std::string str = "YourString";
char chars[] = {'Y', 'S'};
str.erase (std::remove(str.begin(), str.end(), chars[i]), str.end());

Will remove capital Y and S from str, leaving "ourtring".

Note that remove is an algorithm and needs the header <algorithm> included.

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

If you want to have the filename with extension I use this function to get it. It also works with google drive file picks

public static String getFileName(Uri uri) {
    String result;

    //if uri is content
    if (uri.getScheme() != null && uri.getScheme().equals("content")) {
        Cursor cursor = global.getInstance().context.getContentResolver().query(uri, null, null, null, null);
        try {
            if (cursor != null && cursor.moveToFirst()) {
                //local filesystem
                int index = cursor.getColumnIndex("_data");
                if(index == -1)
                    //google drive
                    index = cursor.getColumnIndex("_display_name");
                result = cursor.getString(index);
                if(result != null)
                    uri = Uri.parse(result);
                else
                    return null;
            }
        } finally {
            cursor.close();
        }
    }

    result = uri.getPath();

    //get filename + ext of path
    int cut = result.lastIndexOf('/');
    if (cut != -1)
        result = result.substring(cut + 1);
    return result;
}

Is there a way to split a widescreen monitor in to two or more virtual monitors?

The next version of Windows (Windows 7) will be able to snap windows to the left or right half of the screen. Doesn't help right now, but it's something to look forward to.

http://arstechnica.com/news.ars/post/20081028-first-look-at-windows-7.html

Parsing a CSV file using NodeJS

I was using csv-parse but for larger files was running into performance issues one of the better libraries I have found is Papa Parse, docs are good, good support, lightweight, no dependencies.

Install papaparse

npm install papaparse

Usage:

  • async / await
const fs = require('fs');
const Papa = require('papaparse');

const csvFilePath = 'data/test.csv'

// Function to read csv which returns a promise so you can do async / await.

const readCSV = async (filePath) => {
  const csvFile = fs.readFileSync(filePath)
  const csvData = csvFile.toString()  
  return new Promise(resolve => {
    Papa.parse(csvData, {
      header: true,
      transformHeader: header => header.trim(),
      complete: results => {
        console.log('Complete', results.data.length, 'records.'); 
        resolve(results.data);
      }
    });
  });
};

const test = async () => {
  let parsedData = await readCSV(csvFilePath); 
}

test()
  • callback
const fs = require('fs');
const Papa = require('papaparse');

const csvFilePath = 'data/test.csv'

const file = fs.createReadStream(csvFilePath);

var csvData=[];
Papa.parse(file, {
  header: true,
  transformHeader: header => header.trim(),
  step: function(result) {
    csvData.push(result.data)
  },
  complete: function(results, file) {
    console.log('Complete', csvData.length, 'records.'); 
  }
});

Note header: true is an option on the config, see docs for other options

Explanation of 'String args[]' and static in 'public static void main(String[] args)'

If I were explaining this to someone I'd say we'll get to it later for now you need to know that the way to run your program is to use :

public static void main(String[] args) {
        ...
    }

Assuming he/she knows what an array is, I'd say the args is an argument array and you can show some cool examples.

Then after you've gone a bit about Java/JVM and that stuff, you'd get to modifiers eventually to static and public as well.

Then you can spend some time talking about meaning of these IMHO.

You could mention other "cool" stuff such as varargs that you can use this in later versions of Java.

public static void main(String ...args) {
        //...
    }

How do I make text bold in HTML?

Could someone tell me what I'm doing wrong?"

"bold" has never been an HTML element ("b" is the closest match).

HTML should contain structured content; publisher CSS should suggest styles for that content. That way user agents can expose the structured content with useful styling and navigational controls to users who can't see your suggested bold styling (e.g. users of search engines, totally blind users using screen readers, poorly sighted users using their own colors and fonts, geeky users using text browsers, users of voice-controlled, speaking browsers like Opera for Windows). Thus the right way to make text bold depends on why you want to style it bold. For example:

  • Want to distinguish headings from other text? Use heading elements ("h1" to "h6") and suggest a bold style for them within your CSS ("h1, h2, h3, h4, h5, h6 {font-weight: bold;}".

  • Want to embolden labels for form fields? Use a "label" element, programmatically associate it with the the relevant "select", "input" or "textarea" element by giving it a "for" attribute matching an "id" attribute on the target, and suggest a bold style for it within your CSS ("label {font-weight: bold;"}).

  • Want to embolden a heading for a group of related fields in a form, such as a group of radio choices? Surround them with a "fieldset" element, give it a "legend" element, and suggest a bold style for it within your CSS ("legend {font-weight: bold;}").

  • Want to distinguish a table caption from the table it captions? Use a "caption" element and suggest a bold style for it within your CSS ("caption {font-weight: bold;}").

  • Want to distinguish table headings from table data cells? Use a "th" element and suggest a bold style for it within your CSS ("th {font-weight: bold;}").

  • Want to distinguish the title of a referenced film or album from surrounding text? Use a "cite" element with a class ("cite class="movie-title"), and suggest a bold style for it within your CSS (".movie-title {font-weight: bold;}").

  • Want to distinguish a defined keyword from the surrounding text defining or explaining it? Use a "dfn" element and suggest a bold style for it within your CSS ("dfn {font-weight: bold;}").

  • Want to distinguish some computer code from surrounding text? Use a "code" element and suggest a bold style for it within your CSS ("code {font-weight: bold;}").

  • Want to distinguish a variable name from surrounding text? Use a "var" element and suggest a bold style for it within your CSS ("var {font-weight: bold;}").

  • Want to indicate that some text has been added as an update? Use an "ins" element and suggest a bold style for it within your CSS ("ins {font-weight: bold;}").

  • Want to lightly stress some text ("I love kittens!")? Use an "em" element and suggest a bold style for it within your CSS (e.g. "em {font-weight: bold;}").

  • Want to heavily stress some text, perhaps for a warning ("Beware the dog!")? Use a "strong" element and suggest a bold style for it within your CSS (e.g. "strong {font-weight: bold;}").

… You get the idea (hopefully).

Can't find an HTML element with the right semantics to express /why/ you want to make this particular text bold? Wrap it in a generic "span" element, give it a meaningful class name that expresses your rationale for distinguishing that text ("<span class="lede">Let me begin this news article with a sentence that summarizes it.</span>), and suggest a bold style for it within your CSS (".lede {font-weight: bold;"}. Before making up your own class names, you might want to check if there's a microformat (microformats.org) or common convention for what you want to express.

Why Local Users and Groups is missing in Computer Management on Windows 10 Home?

Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.

You can use User Accounts by pressing Window+R, typing netplwiz and pressing OK as described here.

jQuery UI Dialog Box - does not open after being closed

The jQuery documentation has a link to this article 'Basic usage of the jQuery UI dialog' that explains this situation and how to resolve it.

Spring Boot, Spring Data JPA with multiple DataSources

here is my solution. base on spring-boot.1.2.5.RELEASE.

application.properties

first.datasource.driver-class-name=com.mysql.jdbc.Driver
first.datasource.url=jdbc:mysql://127.0.0.1:3306/test
first.datasource.username=
first.datasource.password=
first.datasource.validation-query=select 1

second.datasource.driver-class-name=com.mysql.jdbc.Driver
second.datasource.url=jdbc:mysql://127.0.0.1:3306/test2
second.datasource.username=
second.datasource.password=
second.datasource.validation-query=select 1

DataSourceConfig.java

@Configuration
public class DataSourceConfig {
    @Bean
    @Primary
    @ConfigurationProperties(prefix="first.datasource")
    public DataSource firstDataSource() {
        DataSource ds =  DataSourceBuilder.create().build();
        return ds;
    }

    @Bean
    @ConfigurationProperties(prefix="second.datasource")
    public DataSource secondDataSource() {
        DataSource ds =  DataSourceBuilder.create().build();
        return ds;
    }
}

Passing variable from Form to Module in VBA

Don't declare the variable in the userform. Declare it as Public in the module.

Public pass As String

In the Userform

Private Sub CommandButton1_Click()
    pass = UserForm1.TextBox1
    Unload UserForm1
End Sub

In the Module

Public pass As String

Public Sub Login()
    '
    '~~> Rest of the code
    '
    UserForm1.Show
    driver.findElementByName("PASSWORD").SendKeys pass
    '
    '~~> Rest of the code
    '
End Sub

You might want to also add an additional check just before calling the driver.find... line?

If Len(Trim(pass)) <> 0 Then

This will ensure that a blank string is not passed.

How to window.scrollTo() with a smooth effect

2018 Update

Now you can use just window.scrollTo({ top: 0, behavior: 'smooth' }) to get the page scrolled with a smooth effect.

_x000D_
_x000D_
const btn = document.getElementById('elem');_x000D_
_x000D_
btn.addEventListener('click', () => window.scrollTo({_x000D_
  top: 400,_x000D_
  behavior: 'smooth',_x000D_
}));
_x000D_
#x {_x000D_
  height: 1000px;_x000D_
  background: lightblue;_x000D_
}
_x000D_
<div id='x'>_x000D_
  <button id='elem'>Click to scroll</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Older solutions

You can do something like this:

_x000D_
_x000D_
var btn = document.getElementById('x');_x000D_
_x000D_
btn.addEventListener("click", function() {_x000D_
  var i = 10;_x000D_
  var int = setInterval(function() {_x000D_
    window.scrollTo(0, i);_x000D_
    i += 10;_x000D_
    if (i >= 200) clearInterval(int);_x000D_
  }, 20);_x000D_
})
_x000D_
body {_x000D_
  background: #3a2613;_x000D_
  height: 600px;_x000D_
}
_x000D_
<button id='x'>click</button>
_x000D_
_x000D_
_x000D_

ES6 recursive approach:

_x000D_
_x000D_
const btn = document.getElementById('elem');_x000D_
_x000D_
const smoothScroll = (h) => {_x000D_
  let i = h || 0;_x000D_
  if (i < 200) {_x000D_
    setTimeout(() => {_x000D_
      window.scrollTo(0, i);_x000D_
      smoothScroll(i + 10);_x000D_
    }, 10);_x000D_
  }_x000D_
}_x000D_
_x000D_
btn.addEventListener('click', () => smoothScroll());
_x000D_
body {_x000D_
  background: #9a6432;_x000D_
  height: 600px;_x000D_
}
_x000D_
<button id='elem'>click</button>
_x000D_
_x000D_
_x000D_

How to properly add 1 month from now to current date in moment.js

According to the latest doc you can do the following-

Add a day

moment().add(1, 'days').calendar();

Add Year

moment().add(1, 'years').calendar();

Add Month

moment().add(1, 'months').calendar();

Invalid http_host header

settings.py

ALLOWED_HOSTS = ['*']

How to do paging in AngularJS?

There is my example. Selected button in the middle on the list Controller. config >>>

 $scope.pagination = {total: null, pages: [], config: {count: 10, page: 1, size: 7}};

Logic for pagination:

/*
     Pagination
     */
    $scope.$watch('pagination.total', function (total) {
        if(!total || total <= $scope.pagination.config.count) return;
        _setPaginationPages(total);
    });

    function _setPaginationPages(total) {
        var totalPages = Math.ceil(total / $scope.pagination.config.count);
        var pages = [];
        var start = $scope.pagination.config.page - Math.floor($scope.pagination.config.size/2);
        var finish = null;

        if((start + $scope.pagination.config.size - 1) > totalPages){
            start = totalPages - $scope.pagination.config.size;
        }
        if(start <= 0) {
            start = 1;
        }

       finish = start +  $scope.pagination.config.size - 1;
       if(finish > totalPages){
           finish = totalPages;
       }


        for (var i = start; i <= finish; i++) {
            pages.push(i);
        }

        $scope.pagination.pages = pages;
    }

    $scope.$watch("pagination.config.page", function(page){
        _setPaginationPages($scope.pagination.total);
        _getRespondents($scope.pagination.config);
    });

and my view on bootstap

<ul ng-class="{hidden: pagination.total == 0}" class="pagination">
        <li ng-click="pagination.config.page = pagination.config.page - 1"
            ng-class="{disabled: pagination.config.page == 1}" ><a href="#">&laquo;</a></li>
        <li ng-repeat="p in pagination.pages"
            ng-click="pagination.config.page = p"
            ng-class="{active: p == pagination.config.page}"><a href="#">{{p}}</a></li>
        <li ng-click="pagination.config.page = pagination.config.page + 1"
            ng-class="{disabled: pagination.config.page == pagination.pages.length}"><a href="#">&raquo;</a></li>
    </ul >

It is useful

Best way to implement keyboard shortcuts in a Windows Forms application?

In WinForm, we can always get the Control Key status by:

bool IsCtrlPressed = (Control.ModifierKeys & Keys.Control) != 0;

Create a map with clickable provinces/states using SVG, HTML/CSS, ImageMap

_x000D_
_x000D_
<script type="text/javascript">_x000D_
      jQuery(function($){_x000D_
        $('#map-country').cssMap({'size' : 810});_x000D_
       });_x000D_
    </script>
_x000D_
_x000D_
_x000D_

strong text

AngularJs: Reload page

This can be done by calling the reload() method in JavaScript.

location.reload();

get size of json object

try this

$.parseJSON(data).length

How can I make a DateTimePicker display an empty string?

Just set the property as follows:

When the user press "clear button" or "delete key" do

dtpData.CustomFormat = " "  'An empty SPACE
dtpData.Format = DateTimePickerFormat.Custom

On DateTimePicker1_ValueChanged event do

dtpData.CustomFormat = "dd/MM/yyyy hh:mm:ss"

Simple prime number generator in Python

re is powerful:

import re


def isprime(n):
    return re.compile(r'^1?$|^(11+)\1+$').match('1' * n) is None

print [x for x in range(100) if isprime(x)]

###########Output#############
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Remove duplicates from a dataframe in PySpark

if you have a data frame and want to remove all duplicates -- with reference to duplicates in a specific column (called 'colName'):

count before dedupe:

df.count()

do the de-dupe (convert the column you are de-duping to string type):

from pyspark.sql.functions import col
df = df.withColumn('colName',col('colName').cast('string'))

df.drop_duplicates(subset=['colName']).count()

can use a sorted groupby to check to see that duplicates have been removed:

df.groupBy('colName').count().toPandas().set_index("count").sort_index(ascending=False)

How to use a wildcard in the classpath to add multiple jars?

From: http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html

Class path entries can contain the basename wildcard character *, which is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR. For example, the class path entry foo/* specifies all JAR files in the directory named foo. A classpath entry consisting simply of * expands to a list of all the jar files in the current directory.

This should work in Java6, not sure about Java5

(If it seems it does not work as expected, try putting quotes. eg: "foo/*")

What is an 'undeclared identifier' error and how do I fix it?

one more case where this issue can occur,

if(a==b)
double c;
getValue(c);

here, the value is declared in a condition and then used outside it.

How to add MVC5 to Visual Studio 2013?

Also, while installing Visual Studio 2013, ensure that you have checked "Web Developer Tools"

Show a div as a modal pop up

A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:

  • 1. Create a div with semi transparent background & show it on top of your content page on click.
  • 2. Show your pop up div or alert div on top of the semi transparent dimming/hiding div.
  • So we need three divs:

  • content(main content of the site).
  • hider(To dim the content).
  • popup_box(the modal div to display).

    First let us define the CSS:

        #hider
        {
            position:absolute;
            top: 0%;
            left: 0%;
            width:1600px;
            height:2000px;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            /*
            z- index must be lower than pop up box
           */
            z-index: 99;
           background-color:Black;
           //for transparency
           opacity:0.6;
        }
    
        #popup_box  
        {
    
        position:absolute;
            top: 50%;
            left: 50%;
            width:10em;
            height:10em;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;
            z-index:100; 
    
        }
    

    It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
    Here comes the java Script:

            $(document).ready(function () {
            //hide hider and popup_box
            $("#hider").hide();
            $("#popup_box").hide();
    
            //on click show the hider div and the message
            $("#showpopup").click(function () {
                $("#hider").fadeIn("slow");
                $('#popup_box').fadeIn("slow");
            });
            //on click hide the message and the
            $("#buttonClose").click(function () {
    
                $("#hider").fadeOut("slow");
                $('#popup_box').fadeOut("slow");
            });
    
            });
    

    And finally the HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    </div>    
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>
    </div>
    

    I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.

  • How do I list all files of a directory?

    Using generators

    import os
    def get_files(search_path):
         for (dirpath, _, filenames) in os.walk(search_path):
             for filename in filenames:
                 yield os.path.join(dirpath, filename)
    list_files = get_files('.')
    for filename in list_files:
        print(filename)
    

    Are HTTPS headers encrypted?

    HTTPS (HTTP over SSL) sends all HTTP content over a SSL tunel, so HTTP content and headers are encrypted as well.

    How to implement WiX installer upgrade?

    I'm using the latest version of WiX (3.0) and couldn't get the above working. But this did work:

    <Product Id="*" UpgradeCode="PUT-GUID-HERE" ... >
    
    <Upgrade Id="PUT-GUID-HERE">
      <UpgradeVersion OnlyDetect="no" Property="PREVIOUSFOUND"
         Minimum="1.0.0.0"  IncludeMinimum="yes"
         Maximum="99.0.0.0" IncludeMaximum="no" />
    </Upgrade>
    

    Note that PUT-GUID-HERE should be the same as the GUID that you have defined in the UpgradeCode property of the Product.

    How to call function that takes an argument in a Django template?

    You cannot call a function that requires arguments in a template. Write a template tag or filter instead.

    How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

    u should add a theme to ur all activities (u should add theme for all application in ur <application> in ur manifest) but if u have set different theme to ur activity u can use :

     android:theme="@style/Theme.AppCompat"
    

    or each kind of AppCompat theme!

    Get the real width and height of an image with JavaScript? (in Safari/Chrome)

    Jquery has two properties called naturalWidth and naturalHeight, you can use in this way.

    $('.my-img')[0].naturalWidth 
    $('.my-img')[0].naturalHeight
    

    Where my-img is a class name used to select my image.

    java.lang.ClassNotFoundException: org.apache.log4j.Level

    You need to download log4j and add in your classpath.

    How to select last two characters of a string

    If it's an integer you need a part of....

    var result = number.toString().slice(-2);
    

    Python: Ignore 'Incorrect padding' error when base64 decoding

    It seems you just need to add padding to your bytes before decoding. There are many other answers on this question, but I want to point out that (at least in Python 3.x) base64.b64decode will truncate any extra padding, provided there is enough in the first place.

    So, something like: b'abc=' works just as well as b'abc==' (as does b'abc=====').

    What this means is that you can just add the maximum number of padding characters that you would ever need—which is three (b'===')—and base64 will truncate any unnecessary ones.

    This lets you write:

    base64.b64decode(s + b'===')
    

    which is simpler than:

    base64.b64decode(s + b'=' * (-len(s) % 4))
    

    How can I change the current URL?

    Simple assigning to window.location or window.location.href should be fine:

    window.location = newUrl;
    

    However, your new URL will cause the browser to load the new page, but it sounds like you'd like to modify the URL without leaving the current page. You have two options for this:

    1. Use the URL hash. For example, you can go from example.com to example.com#foo without loading a new page. You can simply set window.location.hash to make this easy. Then, you should listen to the HTML5 hashchange event, which will be fired when the user presses the back button. This is not supported in older versions of IE, but check out jQuery BBQ, which makes this work in all browsers.

    2. You could use HTML5 History to modify the path without reloading the page. This will allow you to change from example.com/foo to example.com/bar. Using this is easy:

      window.history.pushState("example.com/foo");

      When the user presses "back", you'll receive the window's popstate event, which you can easily listen to (jQuery):

      $(window).bind("popstate", function(e) { alert("location changed"); });

      Unfortunately, this is only supported in very modern browsers, like Chrome, Safari, and the Firefox 4 beta.

    Foreach loop in C++ equivalent of C#

    Something like:

    const char* strarr = {"ram","mohan","sita", 0L};
    
    for(int i = 0; strarr[i]; ++i)
    {
      listbox.items.add(strarr[i]);
    }
    

    Also works for standard C. Not sure in C++ how to detect the end of the strarr without having a null element, but the above should work.

    Create a List of primitive int?

    No there isn't any collection that can contain primitive types when Java Collection Framework is being used.

    However, there are other java collections which support primitive types, such as: Trove, Colt, Fastutil, Guava

    An example of how an arraylist with ints would be when Trove Library used is the following:

     TIntArrayList list= new TIntArrayList();
    

    The performance of this list, when compared with the ArrayList of Integers from Java Collections is much better as the autoboxing/unboxing to the corresponding Integer Wrapper Class is not needed.

    How to delete multiple rows in SQL where id = (x to y)

    Delete Id from table where Id in (select id from table)
    

    Invalid hook call. Hooks can only be called inside of the body of a function component

    Different versions of react between my shared libraries seemed to be the problem (16 and 17), changed both to 16.

    Split an integer into digits to compute an ISBN checksum

    On Older versions of Python...

    map(int,str(123))
    

    On New Version 3k

    list(map(int,str(123)))
    

    Eclipse Bug: Unhandled event loop exception No more handles

    Wow, what a variety of causes of these error messages! I'll throw one more out:

    In my case, Eclipse 4.17 on Ubuntu 16.04LTS was showing these messages for multiple operations. It turns out that 16.04LTS has GTK 3.18, but Eclipse 4.17 requires GTK 3.20. Updating GTK (https://askubuntu.com/questions/933010/how-to-upgrade-gtk-3-18-to-3-20-on-ubuntu-16-04) made the error messages go away.

    How to remove the hash from window.location (URL) with JavaScript without page refresh?

    Initial question:

    window.location.href.substr(0, window.location.href.indexOf('#'))
    

    or

    window.location.href.split('#')[0]
    

    both will return the URL without the hash or anything after it.

    With regards to your edit:

    Any change to window.location will trigger a page refresh. You can change window.location.hash without triggering the refresh (though the window will jump if your hash matches an id on the page), but you can't get rid of the hash sign. Take your pick for which is worse...

    MOST UP-TO-DATE ANSWER

    The right answer on how to do it without sacrificing (either full reload or leaving the hash sign there) is down here. Leaving this answer here though with respect to being the original one in 2009 whereas the correct one which leverages new browser APIs was given 1.5 years later.

    How to run Gradle from the command line on Mac bash

    ./gradlew

    Your directory with gradlew is not included in the PATH, so you must specify path to the gradlew. . means "current directory".

    How do I resolve this "ORA-01109: database not open" error?

    I was facing some problem from SQL PLUS Command Promt.
    
    So I resolve this issue from windows CMD ,I follow such steps--->
    
    1: open CMD (Windows)
    
    2: type show pdbs;
    
       now u have to unmount the data base which is mounted
    
    3: type alter pluggable database database_Name open;
    
    4: type show pdbs;(for cross check)
    

    It works for me

    How do I resolve `The following packages have unmet dependencies`

    This is a bug in the npm package regarding dependencies : https://askubuntu.com/questions/1088662/npm-depends-node-gyp-0-10-9-but-it-is-not-going-to-be-installed

    Bugs have been reported. The above may not work depending what you have installed already, at least it didn't for me on an up to date Ubuntu 18.04 LTS.

    I followed the suggested dependencies and installed them as the above link suggests:

    sudo apt-get install nodejs-dev node-gyp libssl1.0-dev
    

    and then

    sudo apt-get install npm
    

    Please subscribe to the bug if you're affected:

    bugs.launchpad.net/ubuntu/+source/npm/+bug/1517491
    bugs.launchpad.net/ubuntu/+source/npm/+bug/1809828

    Performing a Stress Test on Web Application?

    A little late to this party. I agree that Pylot is the best up-and-coming open source tool out there. It's simple to use and is actively worked on by a great guy (Corey Goldberg). As the founder of OpenQA, I'm also happy that Pylot now is listed on our home page and uses some of our infrastructure (namely the forums).

    However, I also recently decided that the entire concept of load testing was flawed: emulating HTTP traffic, with applications as complex as they have become, is a pain in the butt. That's why I created the commercial tool BrowserMob. It's an external load testing service that uses Selenium to control real web browsers when playing back load.

    The approach obviously requires a ton more hardware than normal load testing techniques, but hardware is actually pretty cheap when you are using cloud computing. And a nice side effect of this is that the scripting is much easier than normal load testing. You don't have to do any advanced regex matching (like JMeter requires) to extract out cookies, .NET session state, Ajax request parameters, etc. Since you're using real browsers, they just do what they are supposed to do.

    Sorry to blatantly pitch a commercial product, but hopefully the concept is interesting to some folks and at least gets them thinking about some new ways to deal with load testing when you have access to a bunch of extra hardware!

    How to convert dd/mm/yyyy string into JavaScript Date object?

    You can use toLocaleString(). This is a javascript method.

    _x000D_
    _x000D_
    var event = new Date("01/02/1993");_x000D_
    _x000D_
    var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };_x000D_
    _x000D_
    console.log(event.toLocaleString('en', options));_x000D_
    _x000D_
    // expected output: "Saturday, January 2, 1993"
    _x000D_
    _x000D_
    _x000D_

    Almost all formats supported. Have look on this link for more details.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

    Disable back button in android

    Simply override the onBackPressed() method.

    @Override
    public void onBackPressed() { }
    

    TypeScript error TS1005: ';' expected (II)

    If you're getting error TS1005: 'finally' expected., it means you forgot to implement catch after try. Generally, it means the syntax you attempted to use was incorrect.

    Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST

    IF you want to handle 'standard' JSON representation of the Date then better to use this pattern: "yyyy-MM-dd'T'HH:mm:ssX".

    Notice the X on the end. It will handle timezones in ISO 8601 standard, and ISO 8601 is exactly what produces this statement in Javascript new Date().toJSON()

    Comparing to other answers it has some benefits:

    1. You don't need to require your clients to send date in GMT
    2. You don't need to explicitly convert your Date object to GMT using this: sdf.setTimeZone(TimeZone.getTimeZone("GMT"));

    Eclipse - debugger doesn't stop at breakpoint

    Project -> Clean seemed to work for me on on JRE 8

    Find all zero-byte files in directory and subdirectories

    No, you don't have to bother grep.

    find $dir -size 0 ! -name "*.xml"
    

    Jenkins/Hudson - accessing the current build number?

    As per Jenkins Documentation,

    BUILD_NUMBER

    is used. This number is identify how many times jenkins run this build process $BUILD_NUMBER is general syntax for it.

    Display the current date and time using HTML and Javascript with scrollable effects in hta application

    Method 1:


    With marquee tag.

    HTML

    <marquee behavior="scroll" bgcolor="yellow" loop="-1" width="30%">
       <i>
          <font color="blue">
            Today's date is : 
            <strong>
             <span id="time"></span>
            </strong>           
          </font>
       </i>
    </marquee> 
    

    JS

    var today = new Date();
    document.getElementById('time').innerHTML=today;
    

    Fiddle demo here


    Method 2:


    Without marquee tag and with CSS.

    HTML

    <p class="marquee">
        <span id="dtText"></span>
    </p>
    

    CSS

    .marquee {
       width: 350px;
       margin: 0 auto;
       background:yellow;
       white-space: nowrap;
       overflow: hidden;
       box-sizing: border-box;
       color:blue;
       font-size:18px;
    }
    
    .marquee span {
       display: inline-block;
       padding-left: 100%;
       text-indent: 0;
       animation: marquee 15s linear infinite;
    }
    
    .marquee span:hover {
        animation-play-state: paused
    }
    
    @keyframes marquee {
        0%   { transform: translate(0, 0); }
        100% { transform: translate(-100%, 0); }
    }
    

    JS

    var today = new Date();
    document.getElementById('dtText').innerHTML=today;
    

    Fiddle demo here

    How to select bottom most rows?

    Logically,

    BOTTOM (x) is all the records except TOP (n - x), where n is the count; x <= n
    

    E.g. Select Bottom 1000 from Employee:

    In T-SQL,

    DECLARE 
    @bottom int,
    @count int
    
    SET @bottom = 1000 
    SET @count = (select COUNT(*) from Employee)
    
    select * from Employee emp where emp.EmployeeID not in 
    (
    SELECT TOP (@count-@bottom) Employee.EmployeeID FROM Employee
    )
    

    Can we have multiple "WITH AS" in single sql - Oracle SQL

    Aditya or others, can you join or match up t2 with t1 in your example, i.e. translated to my code,

    with t1 as (select * from AA where FIRSTNAME like 'Kermit'),
         t2 as (select * from BB B join t1 on t1.FIELD1 = B.FIELD1)
    

    I am not clear whether only WHERE is supported for joining, or what joining approach is supported within the 2nd WITH entity. Some of the examples have the WHERE A=B down in the body of the select "below" the WITH clauses.

    The error I'm getting following these WITH declarations is the identifiers (field names) in B are not recognized, down in the body of the rest of the SQL. So the WITH syntax seems to run OK, but cannot access the results from t2.

    Installation failed with message Invalid File

    1. Invalidate cache/restart
    2. Clean Project
    3. Rebuild Project
    4. Run your app / Build APK

    These steps are enough to solve most of the problems related to Gradle build in any way. These steps helped me solve this problem too.

    Is Google Play Store supported in avd emulators?

    Yes, you can enable/use Play Store on Android Emulator(AVD): Before that you have to set up some prerequisites:

    1. Start Android SDK Manager and select Google Play Intel x86 Atom System Image (Recomended: because it will work comparatively faster) of your required android version (For Example: Android 7.1.1 or API 25)

    [Note: Please keep all other thing as it is, if you are going to install it for first time] Or Install as the image below: enter image description here

    1. After download is complete Goto Tools->Manage AVDs...->Create from your Android SDK Manager

    2. enter image description here

    Check you have provided following option correctly. Not sure about internal and SD card storage. You can choose different. And Target must be your downloaded android version

    1. Also check Google Play Intel Atom (x86) in CPU/ABI is provided

    2. Click OK

    3. Then Start your Android Emulator. There you will see the Android Play Store. See --- enter image description here

    no suitable HttpMessageConverter found for response type

    This is not answering the problem but if anyone comes to this question when they stumble upon this exception of no suitable message converter found, here is my problem and solution.

    In Spring 4.0.9, we were able to send this

        JSONObject jsonCredential = new JSONObject();
        jsonCredential.put(APPLICATION_CREDENTIALS, data);
    
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
    
    ResponseEntity<String> res = restTemplate.exchange(myRestUrl), HttpMethod.POST,request, String.class);
    

    In Spring 4.3.5 release, we starting seeing errors with the message that converter was not found.

    The way Convertors work is that if you have it in your classpath, they get registered.

    Jackson-asl was still in classpath but was not being recognized by spring. We replaced Jackson-asl with faster-xml jackson core.

    Once we added I could see the converter being registered.

    enter image description here

    How do I POST JSON data with cURL?

    I am using the below format to test with a web server.

    use -F 'json data'
    

    Let's assume this JSON dict format:

    {
        'comment': {
            'who':'some_one',
            'desc' : 'get it'
        }
    }
    

    Full example

    curl -XPOST your_address/api -F comment='{"who":"some_one", "desc":"get it"}'
    

    Decode UTF-8 with Javascript

    This should work:

    // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
    
    /* utf.js - UTF-8 <=> UTF-16 convertion
     *
     * Copyright (C) 1999 Masanao Izumo <[email protected]>
     * Version: 1.0
     * LastModified: Dec 25 1999
     * This library is free.  You can redistribute it and/or modify it.
     */
    
    function Utf8ArrayToStr(array) {
        var out, i, len, c;
        var char2, char3;
    
        out = "";
        len = array.length;
        i = 0;
        while(i < len) {
        c = array[i++];
        switch(c >> 4)
        { 
          case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
            // 0xxxxxxx
            out += String.fromCharCode(c);
            break;
          case 12: case 13:
            // 110x xxxx   10xx xxxx
            char2 = array[i++];
            out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
            break;
          case 14:
            // 1110 xxxx  10xx xxxx  10xx xxxx
            char2 = array[i++];
            char3 = array[i++];
            out += String.fromCharCode(((c & 0x0F) << 12) |
                           ((char2 & 0x3F) << 6) |
                           ((char3 & 0x3F) << 0));
            break;
        }
        }
    
        return out;
    }
    

    Check out the JSFiddle demo.

    Also see the related questions: here and here

    How to open maximized window with Javascript?

    Checkout this jquery window plugin: http://fstoke.me/jquery/window/

    // create a window
    sampleWnd = $.window({
       .....
    });
    
    // resize the window by passed w,h parameter
    sampleWnd.resize(screen.width, screen.height);
    

    Oracle "(+)" Operator

    That's Oracle specific notation for an OUTER JOIN, because the ANSI-89 format (using a comma in the FROM clause to separate table references) didn't standardize OUTER joins.

    The query would be re-written in ANSI-92 syntax as:

       SELECT ...
         FROM a
    LEFT JOIN b ON b.id = a.id
    

    This link is pretty good at explaining the difference between JOINs.


    It should also be noted that even though the (+) works, Oracle recommends not using it:

    Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions, which do not apply to the FROM clause OUTER JOIN syntax:

    How to connect SQLite with Java?

    Hey i have posted a video tutorial on youtube about this, you can check that and you can find here the sample code :

    http://myfundatimemachine.blogspot.in/2012/06/database-connection-to-java-application.html

    How do I to insert data into an SQL table using C# as well as implement an upload function?

    You should use parameters in your query to prevent attacks, like if someone entered '); drop table ArticlesTBL;--' as one of the values.

    string query = "INSERT INTO ArticlesTBL (ArticleTitle, ArticleContent, ArticleType, ArticleImg, ArticleBrief,  ArticleDateTime, ArticleAuthor, ArticlePublished, ArticleHomeDisplay, ArticleViews)";
    query += " VALUES (@ArticleTitle, @ArticleContent, @ArticleType, @ArticleImg, @ArticleBrief, @ArticleDateTime, @ArticleAuthor, @ArticlePublished, @ArticleHomeDisplay, @ArticleViews)";
    
    SqlCommand myCommand = new SqlCommand(query, myConnection);
    myCommand.Parameters.AddWithValue("@ArticleTitle", ArticleTitleTextBox.Text);
    myCommand.Parameters.AddWithValue("@ArticleContent", ArticleContentTextBox.Text);
    // ... other parameters
    myCommand.ExecuteNonQuery();
    

    Exploits of a Mom

    (xkcd)

    Make footer stick to bottom of page correctly

    I would like to share how I solved mine using Javascript function that is called on page load. This solution positions the footer at the bottom of the screen when the height of the page content is less than the height of the screen.

    _x000D_
    _x000D_
    function fix_layout(){_x000D_
      //increase content div length by uncommenting below line_x000D_
      //expandContent();_x000D_
      _x000D_
        var wraph = document.getElementById('wrapper').offsetHeight;_x000D_
        if(wraph<window.innerHeight){ //if content is less than screenheight_x000D_
            var headh   = document.getElementById('header').offsetHeight;_x000D_
            var conth   = document.getElementById('content').offsetHeight;_x000D_
            var footh   = document.getElementById('footer').offsetHeight;_x000D_
            //var foottop = window.innerHeight - (headh + conth + footh);_x000D_
            var foottop = window.innerHeight - (footh);_x000D_
            $("#footer").css({top:foottop+'px'});_x000D_
        }_x000D_
    }_x000D_
    _x000D_
    function expandContent(){_x000D_
      $('#content').append('<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed at ante. Mauris eleifend, quam a vulputate dictum, massa quam dapibus leo, eget vulputate orci purus ut lorem. In fringilla mi in ligula. Pellentesque aliquam quam vel dolor. Nunc adipiscing. Sed quam odio, tempus ac, aliquam molestie, varius ac, tellus. Vestibulum ut nulla aliquam risus rutrum interdum. Pellentesque lorem. Curabitur sit amet erat quis risus feugiat viverra. Pellentesque augue justo, sagittis et, lacinia at, venenatis non, arcu. Nunc nec libero. In cursus dictum risus. Etiam tristique nisl a nulla. Ut a orci. Curabitur dolor nunc, egestas at, accumsan at, malesuada nec, magna.</p>'+_x000D_
    _x000D_
    '<p>Nulla facilisi. Nunc volutpat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Ut sit amet orci vel mauris blandit vehicula. Nullam quis enim. Integer dignissim viverra velit. Curabitur in odio. In hac habitasse platea dictumst. Ut consequat, tellus eu volutpat varius, justo orci elementum dolor, sed imperdiet nulla tellus ut diam. Vestibulum ipsum ante, malesuada quis, tempus ac, placerat sit amet, elit.</p>'+_x000D_
    _x000D_
    '<p>Sed eget turpis a pede tempor malesuada. Vivamus quis mi at leo pulvinar hendrerit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Pellentesque aliquet lacus vitae pede. Nullam mollis dolor ac nisi. Phasellus sit amet urna. Praesent pellentesque sapien sed lacus. Donec lacinia odio in odio. In sit amet elit. Maecenas gravida interdum urna. Integer pretium, arcu vitae imperdiet facilisis, elit tellus tempor nisi, vel feugiat ante velit sit amet mauris. Vivamus arcu. Integer pharetra magna ac lacus. Aliquam vitae sapien in nibh vehicula auctor. Suspendisse leo mauris, pulvinar sed, tempor et, consequat ac, lacus. Proin velit. Nulla semper lobortis mauris. Duis urna erat, ornare et, imperdiet eu, suscipit sit amet, massa. Nulla nulla nisi, pellentesque at, egestas quis, fringilla eu, diam.</p>'+_x000D_
    _x000D_
    '<p>Donec semper, sem nec tristique tempus, justo neque commodo nisl, ut gravida sem tellus suscipit nunc. Aliquam erat volutpat. Ut tincidunt pretium elit. Aliquam pulvinar. Nulla cursus. Suspendisse potenti. Etiam condimentum hendrerit felis. Duis iaculis aliquam enim. Donec dignissim augue vitae orci. Curabitur luctus felis a metus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In varius neque at enim. Suspendisse massa nulla, viverra in, bibendum vitae, tempor quis, lorem.</p>'+_x000D_
    _x000D_
    '<p>Donec dapibus orci sit amet elit. Maecenas rutrum ultrices lectus. Aliquam suscipit, lacus a iaculis adipiscing, eros orci pellentesque nisl, non pharetra dolor urna nec dolor. Integer cursus dolor vel magna. Integer ultrices feugiat sem. Proin nec nibh. Duis eu dui quis nunc sagittis lobortis. Fusce pharetra, enim ut sodales luctus, lectus arcu rhoncus purus, in fringilla augue elit vel lacus. In hac habitasse platea dictumst. Aliquam erat volutpat. Fusce iaculis elit id tellus. Ut accumsan malesuada turpis. Suspendisse potenti. Vestibulum lacus augue, lobortis mattis, laoreet in, varius at, nisi. Nunc gravida. Phasellus faucibus. In hac habitasse platea dictumst. Integer tempor lacus eget lectus. Praesent fringilla augue fringilla dui.</p>');_x000D_
    }
    _x000D_
    /*sample CSS*/_x000D_
    body{ background: black; margin: 0; }_x000D_
    #header{ background: grey; }_x000D_
    #content{background: yellow; }_x000D_
    #footer{ background: red; position: absolute; }_x000D_
    _x000D_
    #header, #content, #footer{ display: inline-block; width: 100vw; }
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    <body onload="fix_layout()">_x000D_
            <div id="wrapper">_x000D_
                <div id="header" class="navbar navbar-inverse navbar-fixed-top" role="navigation">_x000D_
                    [some header elements here]_x000D_
                </div>_x000D_
                <div id="content" class="container">_x000D_
                  [some content elements here]_x000D_
                  _x000D_
                  _x000D_
                </div>_x000D_
                <div id="footer" class="footer">_x000D_
                    [some footer elements here]_x000D_
                </div>_x000D_
            </div>_x000D_
        </body>
    _x000D_
    _x000D_
    _x000D_

    Hope that helps.

    How to vertical align an inline-block in a line of text?

    display: inline-block is your friend you just need all three parts of the construct - before, the "block", after - to be one, then you can vertically align them all to the middle:

    Working Example

    (it looks like your picture anyway ;))

    CSS:

    p, div {
      display: inline-block; 
      vertical-align: middle;
    }
    p, div {
      display: inline !ie7; /* hack for IE7 and below */
    }
    
    table {
      background: #000; 
      color: #fff; 
      font-size: 16px; 
      font-weight: bold; margin: 0 10px;
    }
    
    td {
      padding: 5px; 
      text-align: center;
    }
    

    HTML:

    <p>some text</p> 
    <div>
      <table summary="">
      <tr><td>A</td></tr>
      <tr><td>B</td></tr>
      <tr><td>C</td></tr>
      <tr><td>D</td></tr>
      </table>
    </div> 
    <p>continues afterwards</p>
    

    How to cherry-pick from a remote branch?

    I had this error returned after using the commit id from a pull request commit id tab. That commit was subsequently squashed and merged. In the github pull request, look for this text: "merged commit xxxxxxx into..." instead of attempting to use the commit ids from the commits tab.

    Oracle PL Sql Developer cannot find my tnsnames.ora file

    Which Oracle client are you using?

    Oracle 64bit 11g client isn't support in PLSQL Developer. Try to install 32bits client.

    Linker command failed with exit code 1 - duplicate symbol __TMRbBp

    Don't double click Project.xcodeproj to start your xcode project. Instead, close your project and open the xcworkspace.

    File -> Close Workspace
    
    File -> Open -> Search your project folder for Project.xcworkspace
    

    All my errors are gone.

    How do I export html table data as .csv file?

    I've briefly covered a simple way to do this with Google Spreadsheets (importHTML) and in Python (Pandas read_html and to_csv) as well as an example Python script in my SO answer here: https://stackoverflow.com/a/28083469/1588795.

    How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu

    At each point in these instructions, check to see if the problem is fixed. If so, great! Otherwise, continue.

    1. Get to Services. (I was able to right click the Apache launch icon to get there.)
    2. Scroll down to MySQL. Click to start. This will get rid of the #2002 error. Now you'll have a new error:

    #1045 - Access denied for user 'root'@'localhost' (using password: NO)

    1. Edit the C:\wamp\apps\phpmyadmin3.5.1\config.inc.php file, changing $cfg['Servers'][$i]['extension'] = 'mysqli'; to instead be= 'mysql'
    2. Open Services again and Stop MySQL
    3. While in Services, Start wampmysqld

    This is convoluted, I know, but that's what worked for me. Some posts may say you need a password in the config file, but you don't. Mine is still ""

    Hope this helps.

    How do ports work with IPv6?

    I would say the best reference is Format for Literal IPv6 Addresses in URL's where usage of [] is defined.

    Also, if it is for programming and code, specifically Java, I would suggest this readsClass for Inet6Address java/net/URL definition where usage of Inet4 address in Inet6 connotation and other cases are presented in details. For my case, IPv4-mapped address Of the form::ffff:w.x.y.z, for IPv6 address is used to represent an IPv4 address also solved my problem. It allows the native program to use the same address data structure and also the same socket when communicating with both IPv4 and IPv6 nodes. This is the case on Amazon cloud Linux boxes default setup.

    Prevent direct access to a php include file

    Add this to the page that you want to only be included

    <?php
    if(!defined('MyConst')) {
       die('Direct access not permitted');
    }
    ?>
    

    then on the pages that include it add

    <?php
    define('MyConst', TRUE);
    ?>
    

    docker entrypoint running bash script gets "permission denied"

    If you do not use DockerFile, you can simply add permission as command line argument of the bash:

    docker run -t <image>  /bin/bash -c "chmod +x /usr/src/app/docker-entrypoint.sh; /usr/src/app/docker-entrypoint.sh"
    

    How to pause javascript code execution for 2 seconds

    You can use setTimeout to do this

    function myFunction() {
        // your code to run after the timeout
    }
    
    // stop for sometime if needed
    setTimeout(myFunction, 5000);
    

    How to Import .bson file format on mongodb

    I have used this:

    mongorestore -d databasename -c file.bson fullpath/file.bson
    

    1.copy the file path and file name from properties (try to put all bson files in different folder), 2.use this again and again with changing file name only.

    How to bind event listener for rendered elements in Angular 2?

    @HostListener('window:click', ['$event']) onClick(event){ }
    

    check this below link to detect CapsLock on click, keyup and keydown on current window. No need to add any event in html doc

    Detect and warn users about caps lock is on

    Using git commit -a with vim

    The better question is: How do I interrupt the commit when I quit vim?

    There are 2 ways:

    1. :cq or :cquit
    2. Delete all lines of the commit message, including comments, and then :wq

    Either way will give git an error code, so it will not proceed with the commit. This is particularly useful with git commit --amend.

    How to copy a file to a remote server in Python using SCP or SSH?

    Using the external resource paramiko;

        from paramiko import SSHClient
        from scp import SCPClient
        import os
    
        ssh = SSHClient() 
        ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
        ssh.connect(server, username='username', password='password')
        with SCPClient(ssh.get_transport()) as scp:
                scp.put('test.txt', 'test2.txt')
    

    How do I read the first line of a file using cat?

    I'm surprised that this question has been around as long as it has, and nobody has provided the pre-mapfile built-in approach yet.

    IFS= read -r first_line <file
    

    ...puts the first line of the file in the variable expanded by "$first_line", easy as that.

    Moreover, because read is built into bash and this usage requires no subshell, it's significantly more efficient than approaches involving subprocesses such as head or awk.

    What is @RenderSection in asp.net MVC

    If you have a _Layout.cshtml view like this

    <html>
        <body>
            @RenderBody()
            @RenderSection("scripts", required: false)
        </body>
    </html>
    

    then you can have an index.cshtml content view like this

    @section scripts {
         <script type="text/javascript">alert('hello');</script>
    }
    

    the required indicates whether or not the view using the layout page must have a scripts section

    S3 - Access-Control-Allow-Origin Header

    The accepted answer works, but it seems that if you go to the resource directly, then there are no cross-origin headers. If you are using cloudfront, this will cause cloudfront to cache the version without headers.When you then go to a different url that loads this resource, you will get this cross-origin issue.

    ggplot combining two plots from different data.frames

    As Baptiste said, you need to specify the data argument at the geom level. Either

    #df1 is the default dataset for all geoms
    (plot1 <- ggplot(df1, aes(v, p)) + 
        geom_point() +
        geom_step(data = df2)
    )
    

    or

    #No default; data explicitly specified for each geom
    (plot2 <- ggplot(NULL, aes(v, p)) + 
          geom_point(data = df1) +
          geom_step(data = df2)
    )
    

    how to remove untracked files in Git?

    The command for your rescue is git clean.

    Javascript + Regex = Nothing to repeat error?

    Firstly, in a character class [...] most characters don't need escaping - they are just literals.

    So, your regex should be:

    "[\[\]?*+|{}\\()@.\n\r]"
    

    This compiles for me.

    Clone contents of a GitHub repository (without the folder itself)

    If the folder is not empty, a slightly modified version of @JohnLittle's answer worked for me:

    git init
    git remote add origin https://github.com/me/name.git
    git pull origin master
    

    As @peter-cordes pointed out, the only difference is using https protocol instead of git, for which you need to have SSH keys configured.

    C# getting the path of %AppData%

    The BEST way to use the AppData directory, IS to use Environment.ExpandEnvironmentVariable method.

    Reasons:

    • it replaces parts of your string with valid directories or whatever
    • it is case-insensitive
    • it is easy and uncomplicated
    • it is a standard
    • good for dealing with user input

    Examples:

    string path;
    path = @"%AppData%\stuff";
    path = @"%aPpdAtA%\HelloWorld";
    path = @"%progRAMfiLES%\Adobe;%appdata%\FileZilla"; // collection of paths
    
    path = Environment.ExpandEnvironmentVariables(path);
    Console.WriteLine(path);
    

    More info:

    %ALLUSERSPROFILE%   C:\ProgramData
    %APPDATA%   C:\Users\Username\AppData\Roaming
    %COMMONPROGRAMFILES%    C:\Program Files\Common Files
    %COMMONPROGRAMFILES(x86)%   C:\Program Files (x86)\Common Files
    %COMSPEC%   C:\Windows\System32\cmd.exe
    %HOMEDRIVE% C:
    %HOMEPATH%  C:\Users\Username
    %LOCALAPPDATA%  C:\Users\Username\AppData\Local
    %PROGRAMDATA%   C:\ProgramData
    %PROGRAMFILES%  C:\Program Files
    %PROGRAMFILES(X86)% C:\Program Files (x86) (only in 64-bit version)
    %PUBLIC%    C:\Users\Public
    %SystemDrive%   C:
    %SystemRoot%    C:\Windows
    %TEMP% and %TMP%    C:\Users\Username\AppData\Local\Temp
    %USERPROFILE%   C:\Users\Username
    %WINDIR%    C:\Windows
    

    How to get multiple counts with one SQL query?

    I think this can also works for you select count(*) as anc,(select count(*) from Patient where sex='F')as patientF,(select count(*) from Patient where sex='M') as patientM from anc

    and also you can select and count related tables like this select count(*) as anc,(select count(*) from Patient where Patient.Id=anc.PatientId)as patientF,(select count(*) from Patient where sex='M') as patientM from anc

    Generate table relationship diagram from existing schema (SQL Server)

    Visio Professional has a database reverse-engineering feature if yiu create a database diagram. It's not free but is fairly ubiquitous in most companies and should be fairly easy to get.

    Note that Visio 2003 does not play nicely with SQL2005 or SQL2008 for reverse engineering - you will need to get 2007.

    Create timestamp variable in bash script

    DATE=`date "+%Y%m%d"`
    
    DATE_WITH_TIME=`date "+%Y%m%d-%H%M%S"` #add %3N as we want millisecond too
    

    How do I syntax check a Bash script without running it?

    I actually check all bash scripts in current dir for syntax errors WITHOUT running them using find tool:

    Example:

    find . -name '*.sh' -exec bash -n {} \;

    If you want to use it for a single file, just edit the wildcard with the name of the file.

    Understanding Bootstrap's clearfix class

    The :before pseudo element isn't needed for the clearfix hack itself.

    It's just an additional nice feature helping to prevent margin-collapsing of the first child element. Thus the top margin of an child block element of the "clearfixed" element is guaranteed to be positioned below the top border of the clearfixed element.

    display:table is being used because display:block doesn't do the trick. Using display:block margins will collapse even with a :before element.

    There is one caveat: if vertical-align:baseline is used in table cells with clearfixed <div> elements, Firefox won't align well. Then you might prefer using display:block despite loosing the anti-collapsing feature. In case of further interest read this article: Clearfix interfering with vertical-align.

    How to start http-server locally

    When you're running npm install in the project's root, it installs all of the npm dependencies into the project's node_modules directory.

    If you take a look at the project's node_modules directory, you should see a directory called http-server, which holds the http-server package, and a .bin folder, which holds the executable binaries from the installed dependencies. The .bin directory should have the http-server binary (or a link to it).

    So in your case, you should be able to start the http-server by running the following from your project's root directory (instead of npm start):

    ./node_modules/.bin/http-server -a localhost -p 8000 -c-1
    

    This should have the same effect as running npm start.

    If you're running a Bash shell, you can simplify this by adding the ./node_modules/.bin folder to your $PATH environment variable:

    export PATH=./node_modules/.bin:$PATH
    

    This will put this folder on your path, and you should be able to simply run

    http-server -a localhost -p 8000 -c-1
    

    Text Editor For Linux (Besides Vi)?

    I use joe for simple (and not so simple) editing when I'm away from Eclipse.

    It uses the classic Wordstar keybindings- although I've never used Wordstar, it's a selling point for many people.

    It's easy, well-supported, light-weight and it has binaries available for everything.

    How do I use properly CASE..WHEN in MySQL

    I think part of it is that you're stating the value you're selecting after CASE, and then using WHEN x = y syntax afterward, which is a combination of two different methods of using CASE. It should either be

    CASE X
      WHEN a THEN ...
      WHEN b THEN ...
    

    or

    CASE
      WHEN x = a THEN ...
      WHEN x = b THEN ...