Programs & Examples On #Custom data type

SQL server query to get the list of columns in a table along with Data types, NOT NULL, and PRIMARY KEY constraints

IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES 
     WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = 'Table')
      BEGIN
        SELECT COLS.COLUMN_NAME, COLS.DATA_TYPE, COLS.CHARACTER_MAXIMUM_LENGTH, 
              (SELECT 'Yes' FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU
                              ON COLS.TABLE_NAME = TC.TABLE_NAME 
                             AND TC.CONSTRAINT_TYPE = 'PRIMARY KEY'
                             AND KCU.TABLE_NAME = TC.TABLE_NAME
                             AND KCU.CONSTRAINT_NAME = TC.CONSTRAINT_NAME
                             AND KCU.COLUMN_NAME = COLS.COLUMN_NAME) AS KeyX
        FROM INFORMATION_SCHEMA.COLUMNS COLS WHERE TABLE_NAME = 'Table' ORDER BY KeyX DESC, COLUMN_NAME
      END

How to change the buttons text using javascript

You can toggle filterstatus value like this

filterstatus ^= 1;

So your function looks like

function showFilterItem(objButton) {
if (filterstatus == 0) {
    $find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().showFilterItem();
    objButton.value = "Hide Filter";
}
else {
    $find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().hideFilterItem();
    objButton.value = "Show filter";
}
  filterstatus ^= 1;    
}

Violation Long running JavaScript task took xx ms

This was added in the Chrome 56 beta, even though it isn't on this changelog from the Chromium Blog: Chrome 56 Beta: “Not Secure” warning, Web Bluetooth, and CSS position: sticky

You can hide this in the filter bar of the console with the Hide violations checkbox.

How to display and hide a div with CSS?

You need

.abc,.ab {
    display: none;
}

#f:hover ~ .ab {
    display: block;
}

#s:hover ~ .abc {
    display: block;
}

#s:hover ~ .a,
#f:hover ~ .a{
    display: none;
}

Updated demo at http://jsfiddle.net/gaby/n5fzB/2/


The problem in your original CSS was that the , in css selectors starts a completely new selector. it is not combined.. so #f:hover ~ .abc,.a means #f:hover ~ .abc and .a. You set that to display:none so it was always set to be hidden for all .a elements.

What are the applications of binary trees?

One of the most common application is to efficiently store data in sorted form in order to access and search stored elements quickly. For instance, std::map or std::set in C++ Standard Library.

Binary tree as data structure is useful for various implementations of expression parsers and expression solvers.

It may also be used to solve some of database problems, for example, indexing.

Generally, binary tree is a general concept of particular tree-based data structure and various specific types of binary trees can be constructed with different properties.

How to show x and y axes in a MATLAB graph?

I know this is coming a bit late, but a colleague of mine figured something out:

figure, plot ((1:10),cos(rand(1,10))-0.75,'*-')
hold on
plot ((1:10),zeros(1,10),'k+-')
text([1:10]-0.09,ones(1,10).*-0.015,[{'0' '1'  '2' '3' '4' '5' '6' '7' '8' '9'}])
set(gca,'XTick',[], 'XColor',[1 1 1])
box off

How to copy a folder via cmd?

xcopy "%userprofile%\Desktop\?????????" "D:\Backup\" /s/h/e/k/f/c

should work, assuming that your language setting allows Cyrillic (or you use Unicode fonts in the console).

For reference about the arguments: http://ss64.com/nt/xcopy.html

jQuery: Check if special characters exists in string

If you really want to check for all those special characters, it's easier to use a regular expression:

var str = $('#Search').val();
if(/^[a-zA-Z0-9- ]*$/.test(str) == false) {
    alert('Your search string contains illegal characters.');
}

The above will only allow strings consisting entirely of characters on the ranges a-z, A-Z, 0-9, plus the hyphen an space characters. A string containing any other character will cause the alert.

How to pass 2D array (matrix) in a function in C?

Easiest Way in Passing A Variable-Length 2D Array

Most clean technique for both C & C++ is: pass 2D array like a 1D array, then use as 2D inside the function.

#include <stdio.h>

void func(int row, int col, int* matrix){
    int i, j;
    for(i=0; i<row; i++){
        for(j=0; j<col; j++){
            printf("%d ", *(matrix + i*col + j)); // or better: printf("%d ", *matrix++);
        }
        printf("\n");
    }
}

int main(){
    int matrix[2][3] = { {0, 1, 2}, {3, 4, 5} };
    func(2, 3, matrix[0]);

    return 0;
}

Internally, no matter how many dimensions an array has, C/C++ always maintains a 1D array. And so, we can pass any multi-dimensional array like this.

Finalize vs Dispose

As we know dispose and finalize both are used to free unmanaged resources.. but the difference is finalize uses two cycle to free the resources , where as dispose uses one cycle..

the MySQL service on local computer started and then stopped

Delete or rename the 2 following files from "C:\ProgramData\MySQL\MySQL Server 5.7\Data": ib_logfile0 ib_logfile1

How do I call a function inside of another function?

_x000D_
_x000D_
function function_one()_x000D_
{_x000D_
    alert("The function called 'function_one' has been called.")_x000D_
    //Here u would like to call function_two._x000D_
    function_two(); _x000D_
}_x000D_
_x000D_
function function_two()_x000D_
{_x000D_
    alert("The function called 'function_two' has been called.")_x000D_
}
_x000D_
_x000D_
_x000D_

Cannot get OpenCV to compile because of undefined references?

follow this tutorial. i ran the install-opencv.sh file in bash. its in the tutorial

read the example from openCV

CMakeLists.txt

cmake_minimum_required(VERSION 3.7)
project(openCVTest)
# cmake needs this line
cmake_minimum_required(VERSION 2.8)

# Define project name
project(opencv_example_project)

# Find OpenCV, you may need to set OpenCV_DIR variable
# to the absolute path to the directory containing OpenCVConfig.cmake file
# via the command line or GUI
find_package(OpenCV REQUIRED)

# If the package has been found, several variables will
# be set, you can find the full list with descriptions
# in the OpenCVConfig.cmake file.
# Print some message showing some of them
message(STATUS "OpenCV library status:")
message(STATUS "    version: ${OpenCV_VERSION}")
message(STATUS "    libraries: ${OpenCV_LIBS}")
message(STATUS "    include path: ${OpenCV_INCLUDE_DIRS}")

if(CMAKE_VERSION VERSION_LESS "2.8.11")
    # Add OpenCV headers location to your include paths
    include_directories(${OpenCV_INCLUDE_DIRS})
endif()

# Declare the executable target built from your sources
add_executable(main main.cpp)

# Link your application with OpenCV libraries
target_link_libraries(main ${OpenCV_LIBS})

main.cpp

/**
 * @file LinearBlend.cpp
 * @brief Simple linear blender ( dst = alpha*src1 + beta*src2 )
 * @author OpenCV team
 */

#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <stdio.h>

using namespace cv;

/** Global Variables */
const int alpha_slider_max = 100;
int alpha_slider;
double alpha;
double beta;

/** Matrices to store images */
Mat src1;
Mat src2;
Mat dst;

//![on_trackbar]
/**
 * @function on_trackbar
 * @brief Callback for trackbar
 */
static void on_trackbar( int, void* )
{
    alpha = (double) alpha_slider/alpha_slider_max ;

    beta = ( 1.0 - alpha );

    addWeighted( src1, alpha, src2, beta, 0.0, dst);

    imshow( "Linear Blend", dst );
}
//![on_trackbar]

/**
 * @function main
 * @brief Main function
 */
int main( void )
{
    //![load]
    /// Read images ( both have to be of the same size and type )
    src1 = imread("../data/LinuxLogo.jpg");
    src2 = imread("../data/WindowsLogo.jpg");
    //![load]

    if( src1.empty() ) { printf("Error loading src1 \n"); return -1; }
    if( src2.empty() ) { printf("Error loading src2 \n"); return -1; }

    /// Initialize values
    alpha_slider = 0;

    //![window]
    namedWindow("Linear Blend", WINDOW_AUTOSIZE); // Create Window
    //![window]

    //![create_trackbar]
    char TrackbarName[50];
    sprintf( TrackbarName, "Alpha x %d", alpha_slider_max );
    createTrackbar( TrackbarName, "Linear Blend", &alpha_slider, alpha_slider_max, on_trackbar );
    //![create_trackbar]

    /// Show some stuff
    on_trackbar( alpha_slider, 0 );

    /// Wait until user press some key
    waitKey(0);
    return 0;
}

Tested in linux mint 17

A JRE or JDK must be available in order to run Eclipse. No JVM was found after searching the following locations

Here is how I fixed mine:

  1. find the location where your jre is installed. in my case, it was located at C:\Program Files\Java\jdk1.7.0_10

  2. copy the jre folder and paste it where your eclipse files are located (where eclipse.exe is located).

when you download eclipse, you get a .zip package containing eclipse.exe and all the other files needed to run eclipse but it is missing the jre files. so all you need to do is to find where jre folder is located on your hard drive and add it to the rest of the eclipse package.

Most pythonic way to delete a file which may not exist

A KISS offering:

def remove_if_exists(filename):
  if os.path.exists(filename):
    os.remove(filename)

And then:

remove_if_exists("my.file")

Set transparent background of an imageview on Android

In xml

@android:color/transparent

In code

mComponentName.setBackgroundResource(android.R.color.transparent);

keycode and charcode

I (being people myself) wrote this statement because I wanted to detect the key which the user typed on the keyboard across different browsers.

In firefox for example, characters have > 0 charCode and 0 keyCode, and keys such as arrows & backspace have > 0 keyCode and 0 charCode.

However, using this statement can be problematic as "collisions" are possible. For example, if you want to distinguish between the Delete and the Period keys, this won't work, as the Delete has keyCode = 46 and the Period has charCode = 46.

Capture iframe load complete event

Step 1: Add iframe in template.

<iframe id="uvIFrame" src="www.google.com"></iframe>

Step 2: Add load listener in Controller.

document.querySelector('iframe#uvIFrame').addEventListener('load', function () {
  $scope.loading = false;
  $scope.$apply();
});

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

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

Don't use "source", it's designed to run a small number of sql queries and display the output, not to import large databases.

I use Wamp Developer (not XAMPP) but it should be the same.

What you want to do is use the MySQL Client to do the work for you.

  1. Make sure MySQL is running.
  2. Create your database via phpMyAdmin or the MySQL shell.
  3. Then, run cmd.exe, and change to the directory your sql file is located in.
  4. Execute: mysql -u root -p database_name_here < dump_file_name_here.sql
  5. Substitute in your database name and dump file name.
  6. Enter your MySQL root account password when prompted (if no password set, remove the "-p" switch).

This assumes that mysql.exe can be located via the environmental path, and that sql file is located in the directory you are running this from. Otherwise, use full paths.

How should I log while using multiprocessing in Python?

The only way to deal with this non-intrusively is to:

  1. Spawn each worker process such that its log goes to a different file descriptor (to disk or to pipe.) Ideally, all log entries should be timestamped.
  2. Your controller process can then do one of the following:
    • If using disk files: Coalesce the log files at the end of the run, sorted by timestamp
    • If using pipes (recommended): Coalesce log entries on-the-fly from all pipes, into a central log file. (E.g., Periodically select from the pipes' file descriptors, perform merge-sort on the available log entries, and flush to centralized log. Repeat.)

How do I exit from the text window in Git?

Since you are learning Git, know that this has little to do with git but with the text editor configured for use. In vim, you can press i to start entering text and save by pressing esc and :wq and enter, this will commit with the message you typed. In your current state, to just come out without committing, you can do :q instead of the :wq as mentioned above.

Alternatively, you can just do git commit -m '<message>' instead of having git open the editor to type the message.

Note that you can also change the editor and use something you are comfortable with ( like notepad) - How can I set up an editor to work with Git on Windows?

how to remove only one style property with jquery

The documentation for css() says that setting the style property to the empty string will remove that property if it does not reside in a stylesheet:

Setting the value of a style property to an empty string — e.g. $('#mydiv').css('color', '') — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's .css() method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or <style> element.

Since your styles are inline, you can write:

$(selector).css("-moz-user-select", "");

Can I do Android Programming in C++, C?

You should look at MoSync too, MoSync gives you standard C/C++, easy-to-use well-documented APIs, and a full-featured Eclipse-based IDE. Its now a open sourced IDE still pretty cool but not maintained anymore.

Set up Python simpleHTTPserver on Windows

From Stack Overflow question What is the Python 3 equivalent of "python -m SimpleHTTPServer":

The following works for me:

python -m http.server [<portNo>]

Because I am using Python 3 the module SimpleHTTPServer has been replaced by http.server, at least in Windows.

Mongoimport of json file

Number of answer have been given even though I would like to give mine command . I used to frequently. It may help to someone.

mongoimport original.json -d databaseName -c yourcollectionName --jsonArray --drop

How to prevent auto-closing of console after the execution of batch file

Depends on the exact question!

Normally pause does the job within a .bat file.

If you want cmd.exe not to close to be able to remain typing, use cmd /k command at the end of the file.

How to trigger an event after using event.preventDefault()

It is possible to use currentTarget of the event. Example shows how to proceed with form submit. Likewise you could get function from onclick attribute etc.

$('form').on('submit', function(event) {
  event.preventDefault();

  // code

  event.currentTarget.submit();
});

What does OpenCV's cvWaitKey( ) function do?

Note for anybody who may have had problems with the cvWaitKey( ) function. If you are finding that cvWaitKey(x) is not waiting at all, make sure you actually have a window open (i.e. cvNamedWindow(...)). Put the cvNamedWindow(...) declaration BEFORE any cvWaitKey() function calls.

How to get a resource id with a known resource name?

I have found this class very helpful to handle with resources. It has some defined methods to deal with dimens, colors, drawables and strings, like this one:

public static String getString(Context context, String stringId) {
    int sid = getStringId(context, stringId);
    if (sid > 0) {
        return context.getResources().getString(sid);
    } else {
        return "";
    }
}

How to open a new HTML page using jQuery?

use window.open("file2.html"); to open on new window,

or use window.location.href = "file2.html" to open on same window.

(SC) DeleteService FAILED 1072

In Windows 7, make sure Event Viewer closed before deleting.

SQL - IF EXISTS UPDATE ELSE INSERT INTO

Try this:

INSERT INTO `center_course_fee` (`fk_course_id`,`fk_center_code`,`course_fee`) VALUES ('69', '4920153', '6000') ON DUPLICATE KEY UPDATE `course_fee` = '6000';

Java - removing first character of a string

In Java, remove leading character only if it is a certain character

Use the Java ternary operator to quickly check if your character is there before removing it. This strips the leading character only if it exists, if passed a blank string, return blankstring.

String header = "";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);

header = "foobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);

header = "#moobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);

Prints:

blankstring
foobar
moobar

Java, remove all the instances of a character anywhere in a string:

String a = "Cool";
a = a.replace("o","");
//variable 'a' contains the string "Cl"

Java, remove the first instance of a character anywhere in a string:

String b = "Cool";
b = b.replaceFirst("o","");
//variable 'b' contains the string "Col"

Add object to ArrayList at specified index

If you are using the Android flavor of Java, might I suggest using a SparseArray. It's a more memory efficient mapping of integers to objects and easier to iterate over than a Map

How do I do base64 encoding on iOS?

I have done it using the following class..

@implementation Base64Converter
static char base64EncodingTable[64] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',  'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',    '8', '9', '+', '/'
};
+ (NSString *) base64StringFromData: (NSData *)data length: (int)length {

unsigned long ixtext, lentext;

long ctremaining;

unsigned char input[3], output[4];

short i, charsonline = 0, ctcopy;

const unsigned char *raw;

NSMutableString *result;

lentext = [data length];

if (lentext < 1)
    return @"";

result = [NSMutableString stringWithCapacity: lentext];

raw = [data bytes];

ixtext = 0;

while (true) {

    ctremaining = lentext - ixtext;

    if (ctremaining <= 0)
        break;

    for (i = 0; i < 3; i++) {
        unsigned long ix = ixtext + i;
        if (ix < lentext)
            input[i] = raw[ix];
        else
            input[i] = 0;
    }

    output[0] = (input[0] & 0xFC) >> 2;

    output[1] = ((input[0] & 0x03) << 4) | ((input[1] & 0xF0) >> 4);

    output[2] = ((input[1] & 0x0F) << 2) | ((input[2] & 0xC0) >> 6);

    output[3] = input[2] & 0x3F;

    ctcopy = 4;

    switch (ctremaining) {
        case 1:
            ctcopy = 2;
            break;

        case 2:
            ctcopy = 3;
            break;
    }

    for (i = 0; i < ctcopy; i++)
        [result appendString: [NSString stringWithFormat: @"%c", base64EncodingTable[output[i]]]];

    for (i = ctcopy; i < 4; i++)
        [result appendString: @"="];

    ixtext += 3;

    charsonline += 4;

    if ((length > 0) && (charsonline >= length))
        charsonline = 0;
}
return result;
}
@end

While calling call

 [Base64Converter base64StringFromData:dataval length:lengthval];

That's it...

Byte[] to InputStream or OutputStream

I do realize that my answer is way late for this question but I think the community would like a newer approach to this issue.

What are Transient and Volatile Modifiers?

volatile and transient keywords

1) transient keyword is used along with instance variables to exclude them from serialization process. If a field is transient its value will not be persisted.

On the other hand, volatile keyword is used to mark a Java variable as "being stored in main memory".

Every read of a volatile variable will be read from the computer's main memory, and not from the CPU cache, and that every write to a volatile variable will be written to main memory, and not just to the CPU cache.

2) transient keyword cannot be used along with static keyword but volatile can be used along with static.

3) transient variables are initialized with default value during de-serialization and there assignment or restoration of value has to be handled by application code.

For more information, see my blog:
http://javaexplorer03.blogspot.in/2015/07/difference-between-volatile-and.html

Npm install failed with "cannot run in wd"

The only thing that worked for me was adding a .npmrc file containing:

unsafe-perm = true

Adding the same config to package.json didn't have any effect.

Creating a BAT file for python script

Similar to npocmaka's solution, if you are having more than one line of batch code in your batch file besides the python code, check this out: http://lallouslab.net/2017/06/12/batchography-embedding-python-scripts-in-your-batch-file-script/

@echo off
rem = """
echo some batch commands
echo another batch command
python -x "%~f0" %*
echo some more batch commands
goto :eof

"""
# Anything here is interpreted by Python
import platform
import sys
print("Hello world from Python %s!\n" % platform.python_version())
print("The passed arguments are: %s" % sys.argv[1:])

What this code does is it runs itself as a python file by putting all the batch code into a multiline string. The beginning of this string is in a variable called rem, to make the batch code read it as a comment. The first line containing @echo off is ignored in the python code because of the -x parameter.

it is important to mention that if you want to use \ in your batch code, for example in a file path, you'll have to use r"""...""" to surround it to use it as a raw string without escape sequences.

@echo off
rem = r"""
...
"""

Adding a color background and border radius to a Layout

background.xml in drawable folder.

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid android:color="#FFFFFF"/>    
    <stroke
        android:width="3dp"
        android:color="#0FECFF" />

    //specify gradient
    <gradient
        android:startColor="#ffffffff" 
        android:endColor="#110000FF" 
        android:angle="90"/> 

    <padding
        android:left="5dp"
        android:top="5dp"
        android:right="5dp"
        android:bottom="5dp"/> 
    <corners
        android:bottomRightRadius="7dp"
        android:bottomLeftRadius="7dp" 
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp"/> 
</shape>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="210dp"
    android:orientation="vertical"
    android:layout_marginBottom="10dp"        
    android:background="@drawable/background">

Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject

To get around sandboxing of SCM stored Groovy scripts, I recommend to run the script as Groovy Command (instead of Groovy Script file):

import hudson.FilePath
final GROOVY_SCRIPT = "workspace/relative/path/to/the/checked/out/groovy/script.groovy"

evaluate(new FilePath(build.workspace, GROOVY_SCRIPT).read().text)

in such case, the groovy script is transferred from the workspace to the Jenkins Master where it can be executed as a system Groovy Script. The sandboxing is suppressed as long as the Use Groovy Sandbox is not checked.

Get week number (in the year) from a date PHP

try this solution

date( 'W', strtotime( "2017-01-01 + 1 day" ) );

How can I remove item from querystring in asp.net using c#?

Try this ...

PropertyInfo isreadonly   =typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);    

isreadonly.SetValue(this.Request.QueryString, false, null);
this.Request.QueryString.Remove("foo");

Evaluate empty or null JSTL c tags

In this step I have Set the variable first:

<c:set var="structureId" value="<%=article.getStructureId()%>" scope="request"></c:set>

In this step I have checked the variable empty or not:

 <c:if test="${not empty structureId }">
    <a href="javascript:void(0);">Change Design</a>
 </c:if>

How do I make an input field accept only letters in javaScript?

If you want only letters - so from a to z, lower case or upper case, excluding everything else (numbers, blank spaces, symbols), you can modify your function like this:

function validate() {
    if (document.myForm.name.value == "") {
        alert("Enter a name");
        document.myForm.name.focus();
        return false;
    }
    if (!/^[a-zA-Z]*$/g.test(document.myForm.name.value)) {
        alert("Invalid characters");
        document.myForm.name.focus();
        return false;
    }
}

Angular JS: Full example of GET/POST/DELETE/PUT client for a REST/CRUD backend?

I'm the creator of Restangular.

You can take a look at this CRUD example to see how you can PUT/POST/GET elements without all that URL configuration and $resource configuration that you need to do. Besides it, you can then use nested resources without any configuration :).

Check out this plunkr example:

http://plnkr.co/edit/d6yDka?p=preview

You could also see the README and check the documentation here https://github.com/mgonto/restangular

If you need some feature that's not there, just create an issue. I usually add features asked within a week, as I also use this library for all my AngularJS projects :)

Hope it helps!

How to upgrade glibc from version 2.13 to 2.15 on Debian?

Your script contains errors as well, for example if you have dos2unix installed your install works but if you don't like I did then it will fail with dependency issues.

I found this by accident as I was making a script file of this to give to my friend who is new to Linux and because I made the scripts on windows I directed him to install it, at the time I did not have dos2unix installed thus I got errors.

here is a copy of the script I made for your solution but have dos2unix installed.

#!/bin/sh
echo "deb http://ftp.debian.org/debian sid main" >> /etc/apt/sources.list
apt-get update
apt-get -t sid install libc6 libc6-dev libc6-dbg
echo "Please remember to hash out sid main from your sources list. /etc/apt/sources.list"

this script has been tested on 3 machines with no errors.

In React Native, how do I put a view on top of another view, with part of it lying outside the bounds of the view behind?

You can use react-native-view-overflow plugin for placing a view on top of another. It works like the CSS z-index property.

import ViewOverflow from 'react-native-view-overflow';

<ViewOverflow />
    <View style={[styles2.cardBox, { marginTop: 50 }]}>
    <View style={[styles2.cardItem]} >
      <Text style={styles2.cardHeader}>userList</Text>
    </View>
      <View style={[styles2.cardContent]}>
        <Text style={styles2.text}>overflow: "visible"</Text>
      </View>
      <View style={[styles2.cardItemFooter]} >
        <Text style={styles2.cardTextFooter}>...</Text>
      </View>
    </View>
  </ViewOverflow>

const styles2 = StyleSheet.create({
  cardBox: {
    borderLeftWidth: 0,
    borderTopWidth: 0,
    backgroundColor: "transparent",
    borderWidth: 1,
    borderColor: "#d0d0d0",
    width: '94%',
    alignSelf: 'center',
    height: 200,
    position: "relative",
    borderRadius: 15,
    overflow: "visible" // doesn't do anything
  },
  cardContent: {
    textAlign: "right",
    backgroundColor: "transparent",
    marginTop: 15,
    alignSelf: 'flex-end',
    padding: 5,
  },
  cardHeader: {
    color: '#fff',
    fontFamily: 'Vazir',
    fontSize: 12
  },
  cardItem: {
    backgroundColor: "#3c4252",
    borderRadius: 3,
    position: "absolute",
    top: -10,
    right: -5,
    width: 50,
    height: 20,
    paddingRight: 5,
  },
})

How to split a string, but also keep the delimiters?

I don't know of an existing function in the Java API that does this (which is not to say it doesn't exist), but here's my own implementation (one or more delimiters will be returned as a single token; if you want each delimiter to be returned as a separate token, it will need a bit of adaptation):

static String[] splitWithDelimiters(String s) {
    if (s == null || s.length() == 0) {
        return new String[0];
    }
    LinkedList<String> result = new LinkedList<String>();
    StringBuilder sb = null;
    boolean wasLetterOrDigit = !Character.isLetterOrDigit(s.charAt(0));
    for (char c : s.toCharArray()) {
        if (Character.isLetterOrDigit(c) ^ wasLetterOrDigit) {
            if (sb != null) {
                result.add(sb.toString());
            }
            sb = new StringBuilder();
            wasLetterOrDigit = !wasLetterOrDigit;
        }
        sb.append(c);
    }
    result.add(sb.toString());
    return result.toArray(new String[0]);
}

This view is not constrained

When creating a layout, it's easier to work with one control at a time, instead of adding them all at once.

From the Layouts Palette, drag a ConstraintLayout to the screen.

Move your desired controls inside the ConstraintLayout.

So the ConstraintLayout will now be the control's parents, and if you switch to the xml code, the controls will be nested under the ConstraintLayout.

Right click on your control, select Constraint from the menu, and select how you want to align it to the parent ConstraintLayout, top, start, etc.

If you need to align two controls relative to each other, select both controls at the same time with the Ctrl key, then right click to open the constrain menu.

More info: https://developer.android.com/training/constraint-layout

enter image description here

enter image description here You can specify the constraint separation distance in the Constraint Layout tab:

enter image description here

When should I use File.separator and when File.pathSeparator?

You use separator when you are building a file path. So in unix the separator is /. So if you wanted to build the unix path /var/temp you would do it like this:

String path = File.separator + "var"+ File.separator + "temp"

You use the pathSeparator when you are dealing with a list of files like in a classpath. For example, if your app took a list of jars as argument the standard way to format that list on unix is: /path/to/jar1.jar:/path/to/jar2.jar:/path/to/jar3.jar

So given a list of files you would do something like this:

String listOfFiles = ...
String[] filePaths = listOfFiles.split(File.pathSeparator);

How to install wkhtmltopdf on a linux based (shared hosting) web server

Shared hosting no ssh or shell access?

Here is how i did it;

  1. Visit https://wkhtmltopdf.org/downloads.html and download the appropriate stable release for Linux. For my case I chose 32-bit which is wkhtmltox-0.12.4_linux-generic-i386.tar.xz
  2. Unzip to a folder on your local drive.
  3. Upload the folder to public_html (or whichever location fits your need) using an FTP program just like any other file(s)
  4. Change the binary paths in snappy.php file to point the appropriate files in the folder you just uploaded. Bingo! there you have it. You should be able to generate PDF files.

How do I connect to mongodb with node.js (and authenticate)?

I find using a Mongo url handy. I store the URL in an environment variable and use that to configure servers whilst the development version uses a default url with no password.

The URL has the form:

export MONGODB_DATABASE_URL=mongodb://USERNAME:PASSWORD@DBHOST:DBPORT/DBNAME

Code to connect this way:

var DATABASE_URL = process.env.MONGODB_DATABASE_URL || mongodb.DEFAULT_URL;

mongo_connect(DATABASE_URL, mongodb_server_options, 
      function(err, db) { 

          if(db && !err) {
          console.log("connected to mongodb" + " " + lobby_db);
          }
          else if(err) {
          console.log("NOT connected to mongodb " + err + " " + lobby_db);
          }
      });    

The page cannot be displayed because an internal server error has occurred on server

For those of you who hit this stackoverflow entry because it ranks high for the phrase:

The page cannot be displayed because an internal server error has occurred.

In my personal situation with this exact error message, I had turned on python 2.7 thinking I could use some python with my .NET API. I then had that exact error message when I attempted to deploy a vanilla version of the API or MVC from visual studio pro 2013. I was deploying to an azure cloud webapp.

Hope this helps anyone with my same experience. I didn't even think to turn off python until I found this suggestion.

Simple export and import of a SQLite database on Android

If you want this in kotlin . And perfectly working

 private fun exportDbFile() {

    try {

        //Existing DB Path
        val DB_PATH = "/data/packagename/databases/mydb.db"
        val DATA_DIRECTORY = Environment.getDataDirectory()
        val INITIAL_DB_PATH = File(DATA_DIRECTORY, DB_PATH)

        //COPY DB PATH
        val EXTERNAL_DIRECTORY: File = Environment.getExternalStorageDirectory()
        val COPY_DB = "/mynewfolder/mydb.db"
        val COPY_DB_PATH = File(EXTERNAL_DIRECTORY, COPY_DB)

        File(COPY_DB_PATH.parent!!).mkdirs()
        val srcChannel = FileInputStream(INITIAL_DB_PATH).channel

        val dstChannel = FileOutputStream(COPY_DB_PATH).channel
        dstChannel.transferFrom(srcChannel,0,srcChannel.size())
        srcChannel.close()
        dstChannel.close()

    } catch (excep: Exception) {
        Toast.makeText(this,"ERROR IN COPY $excep",Toast.LENGTH_LONG).show()
        Log.e("FILECOPYERROR>>>>",excep.toString())
        excep.printStackTrace()
    }

}

Image re-size to 50% of original size in HTML

You did not do anything wrong here, it will any other thing that is overriding the image size.

You can check this working fiddle.

And in this fiddle I have alter the image size using %, and it is working.

Also try using this code:

<img src="image.jpg" style="width: 50%; height: 50%"/>?

Here is the example fiddle.

ruby 1.9: invalid byte sequence in UTF-8

Before you use scan, make sure that the requested page's Content-Type header is text/html, since there can be links to things like images which are not encoded in UTF-8. The page could also be non-html if you picked up a href in something like a <link> element. How to check this varies on what HTTP library you are using. Then, make sure the result is only ascii with String#ascii_only? (not UTF-8 because HTML is only supposed to be using ascii, entities can be used otherwise). If both of those tests pass, it is safe to use scan.

Traversing text in Insert mode

To have a little better navigation in insert mode, why not map some keys?

imap <C-b> <Left>
imap <C-f> <Right>
imap <C-e> <End>
imap <C-a> <Home>
" <C-a> is used to repeat last entered text. Override it, if its not needed

If you can work around making the Meta key work in your terminal, you can mock emacs mode even better. The navigation in normal-mode is way better, but for shorter movements it helps to stay in insert mode.

For longer jumps, I prefer the following default translation:

<Meta-b>    maps to     <Esc><C-left>

This shifts to normal-mode and goes back a word

How does the Python's range function work?

It is looping, probably the problem is in the part of the print...

If you can't find the logic where the system prints, just add the folling where you want the content out:

for i in range(len(vs)):
    print vs[i]
    print fs[i]
    print rs[i]

Is there any way to set environment variables in Visual Studio Code?

Assuming you mean for a debugging session(?) then you can include a env property in your launch configuration.

If you open the .vscode/launch.json file in your workspace or select Debug > Open Configurations then you should see a set of launch configurations for debugging your code. You can then add to it an env property with a dictionary of string:string.

Here is an example for an ASP.NET Core app from their standard web template setting the ASPNETCORE_ENVIRONMENT to Development :

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": ".NET Core Launch (web)",
      "type": "coreclr",
      "request": "launch",
      "preLaunchTask": "build",
      // If you have changed target frameworks, make sure to update the program path.
      "program": "${workspaceFolder}/bin/Debug/netcoreapp2.0/vscode-env.dll",
      "args": [],
      "cwd": "${workspaceFolder}",
      "stopAtEntry": false,
      "internalConsoleOptions": "openOnSessionStart",
      "launchBrowser": {
        "enabled": true,
        "args": "${auto-detect-url}",
        "windows": {
          "command": "cmd.exe",
          "args": "/C start ${auto-detect-url}"
        },
        "osx": {
          "command": "open"
        },
        "linux": {
          "command": "xdg-open"
        }
      },
      "env": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "sourceFileMap": {
        "/Views": "${workspaceFolder}/Views"
      }
    },
    {
      "name": ".NET Core Attach",
      "type": "coreclr",
      "request": "attach",
      "processId": "${command:pickProcess}"
    }
  ]
}

How to set ObjectId as a data type in mongoose

The solution provided by @dex worked for me. But I want to add something else that also worked for me: Use

let UserSchema = new Schema({
   username: {
     type: String
   },
   events: [{
     type: ObjectId,
     ref: 'Event' // Reference to some EventSchema
   }]
})

if what you want to create is an Array reference. But if what you want is an Object reference, which is what I think you might be looking for anyway, remove the brackets from the value prop, like this:

let UserSchema = new Schema({
   username: {
     type: String
   },
   events: {
     type: ObjectId,
     ref: 'Event' // Reference to some EventSchema
   }
})

Look at the 2 snippets well. In the second case, the value prop of key events does not have brackets over the object def.

HTML table with fixed headers and a fixed column?

In this answer there is also the best answer I found to your question:

HTML table with fixed headers?

and based on pure CSS.

Unable to compile simple Java 10 / Java 11 project with Maven

Boosting your maven-compiler-plugin to 3.8.0 seems to be necessary but not sufficient. If you're still having problems, you should also make sure your JAVA_HOME environment variable is set to Java 10 (or 11) if you're running from the command line. (The error message you get won't tell you this.) Or if you're running from an IDE, you need to make sure it is set to run maven with your current JDK.

How to set dialog to show in full screen?

dialog = new Dialog(getActivity(),android.R.style.Theme_Translucent_NoTitleBar);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.loading_screen);
    Window window = dialog.getWindow();
    WindowManager.LayoutParams wlp = window.getAttributes();

    wlp.gravity = Gravity.CENTER;
    wlp.flags &= ~WindowManager.LayoutParams.FLAG_BLUR_BEHIND;
    window.setAttributes(wlp);
    dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    dialog.show();

try this.

HTML5 placeholder css padding

Removing the line-height indeed makes your text align with your placeholder-text, but it doesn't properly solve your problem since you need to adapt your design to this flaw (it's not a bug). Adding vertical-align won't do the deal either. I haven't tried in all browsers, but it doesn't work in Safari 5.1.4 for sure.

I have heard of a jQuery fix for this, that is not cross-browser placeholder support (jQuery.placeholder), but for styling placeholders, but I haven't found it yet.

In the meantime, you can resolve to the table on this page which shows different browser support for different styles.

Edit: Found the plugin! jquery.placeholder.min.js provides you with both full styling capabilities and cross-browser support into the bargain.

Set timeout for ajax (jQuery)

Please read the $.ajax documentation, this is a covered topic.

$.ajax({
    url: "test.html",
    error: function(){
        // will fire when timeout is reached
    },
    success: function(){
        //do something
    },
    timeout: 3000 // sets timeout to 3 seconds
});

You can get see what type of error was thrown by accessing the textStatus parameter of the error: function(jqXHR, textStatus, errorThrown) option. The options are "timeout", "error", "abort", and "parsererror".

How to print formatted BigDecimal values?

BigDecimal(19.0001).setScale(2, BigDecimal.RoundingMode.DOWN)

TSQL select into Temp table from dynamic sql

declare @sql varchar(100);

declare @tablename as varchar(100);

select @tablename = 'your_table_name';

create table #tmp 
    (col1 int, col2 int, col3 int);

set @sql = 'select aa, bb, cc from ' + @tablename;

insert into #tmp(col1, col2, col3) exec( @sql );

select * from #tmp;

How can I merge the columns from two tables into one output?

I guess that what you want to do is an UNION of both tables.

If both tables have the same columns then you can just do

SELECT category_id, col1, col2, col3
  FROM items_a
UNION 
SELECT category_id, col1, col2, col3 
  FROM items_b

Else, you might have to do something like

SELECT category_id, col1, col2, col3
  FROM items_a 
UNION 
SELECT category_id, col_1 as col1, col_2 as col2, col_3 as col3
  FROM items_b

Finding length of char array

If anyone is looking for a quick fix for this, here's how you do it.

while (array[i] != '\0') i++;

The variable i will hold the used length of the array, not the entire initialized array. I know it's a late post, but it may help someone.

BACKUP LOG cannot be performed because there is no current database backup

I just deleted the existing DB that i wanted to override with the backup and restored it from backup and it worked without the error.

Is putting a div inside an anchor ever correct?

If you change it to a block-style element, then no, it's no longer 'wrong', but it probably won't validate. But it doesn't make much sense to do what you're doing. You should either just keep the anchor tag as a block level element with no inner div, or put the div on the outside.

Excel Validation Drop Down list using VBA

You are defining your array as xlValidateList(), so when you try to assign the type, it gets confused as to what you are trying to assign to the type.

Instead, try this:

Dim MyList(5) As String
MyList(0) = 1
MyList(1) = 2
MyList(2) = 3
MyList(3) = 4
MyList(4) = 5
MyList(5) = 6

With Range("A1").Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
         Operator:=xlBetween, Formula1:=Join(MyList, ",")
End With

String to LocalDate

DateTimeFormatter has in-built formats that can directly be used to parse a character sequence. It is case Sensitive, Nov will work however nov and NOV wont work:

DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MMM-dd");

try {
    LocalDate datetime = LocalDate.parse(oldDate, pattern);
    System.out.println(datetime); 
} catch (DateTimeParseException e) {
    // DateTimeParseException - Text '2019-nov-12' could not be parsed at index 5
    // Exception handling message/mechanism/logging as per company standard
}

DateTimeFormatterBuilder provides custom way to create a formatter. It is Case Insensitive, Nov , nov and NOV will be treated as same.

DateTimeFormatter f = new DateTimeFormatterBuilder().parseCaseInsensitive()
        .append(DateTimeFormatter.ofPattern("yyyy-MMM-dd")).toFormatter();
try {
    LocalDate datetime = LocalDate.parse(oldDate, f);
    System.out.println(datetime); // 2019-11-12
} catch (DateTimeParseException e) {
     // Exception handling message/mechanism/logging as per company standard
}

Programmatically find the number of cores on a machine

This functionality is part of the C++11 standard.

#include <thread>

unsigned int nthreads = std::thread::hardware_concurrency();

For older compilers, you can use the Boost.Thread library.

#include <boost/thread.hpp>

unsigned int nthreads = boost::thread::hardware_concurrency();

In either case, hardware_concurrency() returns the number of threads that the hardware is capable of executing concurrently based on the number of CPU cores and hyper-threading units.

PHP fwrite new line

Use PHP_EOL which produces \r\n or \n

$data = 'my data' . PHP_EOL . 'my data';
$fp = fopen('my_file', 'a');
fwrite($fp, $data);
fclose($fp);

// File output

my data
my data

Remove all multiple spaces in Javascript and replace with single space

You can also replace without a regular expression.

while(str.indexOf('  ')!=-1)str.replace('  ',' ');

The listener supports no services

You need to add your ORACLE_HOME definition in your listener.ora file. Right now its not registered with any ORACLE_HOME.

Sample listener.ora

abc =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = abc.kma.com)(PORT = 1521))
    )
  )

SID_LIST_abc =
  (SID_LIST =
    (SID_DESC =
      (ORACLE_HOME= /abc/DbTier/11.2.0)
      (SID_NAME = abc)
    )
  )

The ResourceConfig instance does not contain any root resource classes

I had the same issue, testing a bunch of different examples, and tried all the possible solutions. What finally got it working for me was when I added a @Path("") over the class line, I had left that out.

How to hide TabPage from TabControl

private System.Windows.Forms.TabControl _tabControl;
private System.Windows.Forms.TabPage _tabPage1;
private System.Windows.Forms.TabPage _tabPage2;

...
// Initialise the controls
...

// "hides" tab page 2
_tabControl.TabPages.Remove(_tabPage2);

// "shows" tab page 2
// if the tab control does not contain tabpage2
if (! _tabControl.TabPages.Contains(_tabPage2))
{
    _tabControl.TabPages.Add(_tabPage2);
}

Using --add-host or extra_hosts with docker-compose

Basic docker-compose.yml with extra hosts:

version: '3'
services:
api:
    build: .
    ports:
        - "5003:5003"
    extra_hosts:
        - "your-host.name.com:162.242.195.82" #host and ip
        - "your-host--1.name.com your-host--2.name.com:50.31.209.229" #multiple hostnames with same ip
        

The content in the /etc/hosts file in the created container:

162.242.195.82  your-host.name.com
50.31.209.229   your-host--1.name.com your-host--2.name.com

You can check the /etc/hosts file with the following commands:

$ docker-compose -f path/to/file/docker-compose.yml run api bash  # 'api' is service name
#then inside container bash
root@f7c436910676:/app# cat /etc/hosts

What does Include() do in LINQ?

Think of it as enforcing Eager-Loading in a scenario where you sub-items would otherwise be lazy-loading.

The Query EF is sending to the database will yield a larger result at first, but on access no follow-up queries will be made when accessing the included items.

On the other hand, without it, EF would execute separte queries later, when you first access the sub-items.

Understanding the ngRepeat 'track by' expression

a short summary:

track by is used in order to link your data with the DOM generation (and mainly re-generation) made by ng-repeat.

when you add track by you basically tell angular to generate a single DOM element per data object in the given collection

this could be useful when paging and filtering, or any case where objects are added or removed from ng-repeat list.

usually, without track by angular will link the DOM objects with the collection by injecting an expando property - $$hashKey - into your JavaScript objects, and will regenerate it (and re-associate a DOM object) with every change.

full explanation:

http://www.bennadel.com/blog/2556-using-track-by-with-ngrepeat-in-angularjs-1-2.htm

a more practical guide:

http://www.codelord.net/2014/04/15/improving-ng-repeat-performance-with-track-by/

(track by is available in angular > 1.2 )

R data formats: RData, Rda, Rds etc

In addition to @KenM's answer, another important distinction is that, when loading in a saved object, you can assign the contents of an Rds file. Not so for Rda

> x <- 1:5
> save(x, file="x.Rda")
> saveRDS(x, file="x.Rds")
> rm(x)

## ASSIGN USING readRDS
> new_x1 <- readRDS("x.Rds")
> new_x1
[1] 1 2 3 4 5

## 'ASSIGN' USING load -- note the result
> new_x2 <- load("x.Rda")
loading in to  <environment: R_GlobalEnv> 
> new_x2
[1] "x"
# NOTE: `load()` simply returns the name of the objects loaded. Not the values. 
> x
[1] 1 2 3 4 5

Set default syntax to different filetype in Sublime Text 2

In ST2 there's a package you can install called Default FileType which does just that.

More info here.

Updating an object with setState in React

this is another solution using immer immutabe utility, very suited for deeply nested objects with ease, and you should not care about mutation

this.setState(
    produce(draft => {
       draft.jasper.name = 'someothername'
    })
)

Print very long string completely in pandas dataframe

The way I often deal with the situation you describe is to use the .to_csv() method and write to stdout:

import sys

df.to_csv(sys.stdout)

Update: it should now be possible to just use None instead of sys.stdout with similar effect!

This should dump the whole dataframe, including the entirety of any strings. You can use the to_csv parameters to configure column separators, whether the index is printed, etc. It will be less pretty than rendering it properly though.

I posted this originally in answer to the somewhat-related question at Output data from all columns in a dataframe in pandas

How to sort in mongoose?

This is what i did, it works fine.

User.find({name:'Thava'}, null, {sort: { name : 1 }})

Simplest way to have a configuration file in a Windows Forms C# application

You should create an App.config file (very similar to web.config).

You should right click on your project, add new item, and choose new "Application Configuration File".

Ensure that you add using System.Configuration in your project.

Then you can add values to it:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="setting1" value="key"/>
  </appSettings>
  <connectionStrings>
    <add name="prod" connectionString="YourConnectionString"/>
  </connectionStrings>
</configuration>

    private void Form1_Load(object sender, EventArgs e)
    {
        string setting = ConfigurationManager.AppSettings["setting1"];
        string conn = ConfigurationManager.ConnectionStrings["prod"].ConnectionString;
    }

Just a note: According to Microsoft, you should use ConfigurationManager instead of ConfigurationSettings (see the remarks section):

"The ConfigurationSettings class provides backward compatibility only. For new applications you should use the ConfigurationManager class or WebConfigurationManager class instead. "

How to highlight cell if value duplicate in same column for google spreadsheet?

Answer of @zolley is right. Just adding a Gif and steps for the reference.

  1. Goto menu Format > Conditional formatting..
  2. Find Format cells if..
  3. Add =countif(A:A,A1)>1 in field Custom formula is
    • Note: Change the letter A with your own column.

enter image description here

Using 24 hour time in bootstrap timepicker

if you are using bootstrap time picker. use showMeridian property to make the time picker 24 hours format.

$('.time-picker').timepicker({
            showMeridian: false     
        });

Get the difference between dates in terms of weeks, months, quarters, and years

Here the still lacking lubridate answer (although Gregor's function is built on this package)

The lubridate timespan documentation is very helpful for understanding the difference between periods and duration. I also like the lubridate cheatsheet and this very useful thread

library(lubridate)

dates <- c(dmy('14.01.2013'), dmy('26.03.2014'))

span <- dates[1] %--% dates[2] #creating an interval object

#creating period objects 
as.period(span, unit = 'year') 
#> [1] "1y 2m 12d 0H 0M 0S"
as.period(span, unit = 'month')
#> [1] "14m 12d 0H 0M 0S"
as.period(span, unit = 'day')
#> [1] "436d 0H 0M 0S"

Periods do not accept weeks as units. But you can convert durations to weeks:

as.duration(span)/ dweeks(1)
#makes duration object (in seconds) and divides by duration of a week (in seconds)
#> [1] 62.28571

Created on 2019-11-04 by the reprex package (v0.3.0)

Hive External Table Skip First Row

Just append below property in your query and the first header or line int the record will not load or it will be skipped.

Try this

tblproperties ("skip.header.line.count"="1");

How to read Data from Excel sheet in selenium webdriver

Your problem is that log4j has not been initialized. It does not affect the outcome of you application in any way, so it's safe to ignore or just initialize Log4J, see: How to initialize log4j properly?

Font Awesome 5 font-family issue

Since FontAwesome 5, you have to enable a new "searchPseudoElements" option to use FontAwesome icons this way:

<script>
  window.FontAwesomeConfig = {
    searchPseudoElements: true
  }
</script>

See also this question: Font awesome 5 on pseudo elements and the new Font Awesome API: https://fontawesome.com/how-to-use/font-awesome-api

Additionaly, change font-family in your CSS code to

font-family: "Font Awesome 5 Regular";

How to parse JSON boolean value?

A boolean is not an integer; 1 and 0 are not boolean values in Java. You'll need to convert them explicitly:

boolean multipleContacts = (1 == jsonObject.getInt("MultipleContacts"));

or serialize the ints as booleans from the start.

How can I capture packets in Android?

Option 1 - Android PCAP

Limitation

Android PCAP should work so long as:

Your device runs Android 4.0 or higher (or, in theory, the few devices which run Android 3.2). Earlier versions of Android do not have a USB Host API

Option 2 - TcpDump

Limitation

Phone should be rooted

Option 3 - bitshark (I would prefer this)

Limitation

Phone should be rooted

Reason - the generated PCAP files can be analyzed in WireShark which helps us in doing the analysis.

Other Options without rooting your phone

  1. tPacketCapture

https://play.google.com/store/apps/details?id=jp.co.taosoftware.android.packetcapture&hl=en

Advantages

Using tPacketCapture is very easy, captured packet save into a PCAP file that can be easily analyzed by using a network protocol analyzer application such as Wireshark.

  1. You can route your android mobile traffic to PC and capture the traffic in the desktop using any network sniffing tool.

http://lifehacker.com/5369381/turn-your-windows-7-pc-into-a-wireless-hotspot

How do you write multiline strings in Go?

Use raw string literals for multi-line strings:

func main(){
    multiline := `line 
by line
and line
after line`
}

Raw string literals

Raw string literals are character sequences between back quotes, as in `foo`. Within the quotes, any character may appear except back quote.

A significant part is that is raw literal not just multi-line and to be multi-line is not the only purpose of it.

The value of a raw string literal is the string composed of the uninterpreted (implicitly UTF-8-encoded) characters between the quotes; in particular, backslashes have no special meaning...

So escapes will not be interpreted and new lines between ticks will be real new lines.

func main(){
    multiline := `line 
by line \n
and line \n
after line`

    // \n will be just printed. 
    // But new lines are there too.
    fmt.Print(multiline)
}

Concatenation

Possibly you have long line which you want to break and you don't need new lines in it. In this case you could use string concatenation.

func main(){
    multiline := "line " +
            "by line " +
            "and line " +
            "after line"

    fmt.Print(multiline) // No new lines here
}

Since " " is interpreted string literal escapes will be interpreted.

func main(){
    multiline := "line " +
            "by line \n" +
            "and line \n" +
            "after line"

    fmt.Print(multiline) // New lines as interpreted \n
}

Hibernate: flush() and commit()

One common case for explicitly flushing is when you create a new persistent entity and you want it to have an artificial primary key generated and assigned to it, so that you can use it later on in the same transaction. In that case calling flush would result in your entity being given an id.

Another case is if there are a lot of things in the 1st-level cache and you'd like to clear it out periodically (in order to reduce the amount of memory used by the cache) but you still want to commit the whole thing together. This is the case that Aleksei's answer covers.

Node.js Hostname/IP doesn't match certificate's altnames

I was getting this when streaming to ElasticSearch from a Lambda function in AWS. Smashed my head a against a wall trying to figure it out. In the end when setting the request.headers['Host'] I was adding in the https:// to the domain for ES - changing this to [es-domain-name].eu-west-1.es.amazonaws.com (without https://) worked straight away. Below is the code I used to get it working, hopefully save anyone else smashing their head against a wall...

import path from 'path';
import AWS from 'aws-sdk';

const { region, esEndpoint } = process.env;
const endpoint = new AWS.Endpoint(esEndpoint);
const httpClient = new AWS.HttpClient();
const credentials = new AWS.EnvironmentCredentials('AWS');

/**
 * Sends a request to Elasticsearch
 *
 * @param {string} httpMethod - The HTTP method, e.g. 'GET', 'PUT', 'DELETE', etc
 * @param {string} requestPath - The HTTP path (relative to the Elasticsearch domain), e.g. '.kibana'
 * @param {string} [payload] - An optional JavaScript object that will be serialized to the HTTP request body
 * @returns {Promise} Promise - object with the result of the HTTP response
 */
export function sendRequest ({ httpMethod, requestPath, payload }) {
    const request = new AWS.HttpRequest(endpoint, region);

    request.method = httpMethod;
    request.path = path.join(request.path, requestPath);
    request.body = payload;
    request.headers['Content-Type'] = 'application/json';
    request.headers['Host'] = '[es-domain-name].eu-west-1.es.amazonaws.com';
    request.headers['Content-Length'] = Buffer.byteLength(request.body);
    const signer = new AWS.Signers.V4(request, 'es');
    signer.addAuthorization(credentials, new Date());

    return new Promise((resolve, reject) => {
        httpClient.handleRequest(
            request,
            null,
            response => {
                const { statusCode, statusMessage, headers } = response;
                let body = '';
                response.on('data', chunk => {
                    body += chunk;
                });
                response.on('end', () => {
                    const data = {
                        statusCode,
                        statusMessage,
                        headers
                    };
                    if (body) {
                        data.body = JSON.parse(body);
                    }
                    resolve(data);
                });
            },
            err => {
                reject(err);
            }
        );
    });
}

When to use in vs ref vs out

You should use out unless you need ref.

It makes a big difference when the data needs to be marshalled e.g. to another process, which can be costly. So you want to avoid marshalling the initial value when the method doesn't make use of it.

Beyond that, it also shows the reader of the declaration or the call whether the initial value is relevant (and potentially preserved), or thrown away.

As a minor difference, an out parameter needs not be initialized.

Example for out:

string a, b;
person.GetBothNames(out a, out b);

where GetBothNames is a method to retrieve two values atomically, the method won't change behavior whatever a and b are. If the call goes to a server in Hawaii, copying the initial values from here to Hawaii is a waste of bandwidth. A similar snippet using ref:

string a = String.Empty, b = String.Empty;
person.GetBothNames(ref a, ref b);

could confuse readers, because it looks like the initial values of a and b are relevant (though the method name would indicate they are not).

Example for ref:

string name = textbox.Text;
bool didModify = validator.SuggestValidName(ref name);

Here the initial value is relevant to the method.

How to specify different Debug/Release output directories in QMake .pro file

The short answer is: you don't.

You should run qmake followed by make in whatever build directory you want to build in. So, run it once in a debug directory, once in a release directory.

That's how anyone building your project would expect it to work, and that's how Qt itself is set up to build, that's also how Qt Creator expects your .pro file to behave: it simply starts qmake and then make in the build folder for your target's chosen configuration.

If you wish to create these folders and perform the two (or more) builds in them, you'll need a top-level makefile, possibly created from a top-level project file via qmake.

It's not uncommon to have more than two build configurations, so you're unnecessarily committing yourself to only differentiating between a build and a release; you might have builds with different optimization levels, etc. The debug/release dichotomy is best left to rest in peace.

jQuery validation: change default error message

@Josh: You can expand your solution with translated Message from your resource bundle

<script type="text/javascript">
    $.validator.messages.number = '@Html.Raw(@Resources.General.ErrorMessageNotANumber)';
</script>

If you put this code part into your _Layout.cshtml (MVC) it's available for all your views

java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

I had to delete Tomcat's work directory as it had cached previously generated files. To do this:

  1. Stop Tomcat
  2. Delete the 'work' directory
  3. Start Tomcat

This will cause the work directory to be newly generated.

Entity Framework Queryable async

Long story short,
IQueryable is designed to postpone RUN process and firstly build the expression in conjunction with other IQueryable expressions, and then interprets and runs the expression as a whole.
But ToList() method (or a few sort of methods like that), are ment to run the expression instantly "as is".
Your first method (GetAllUrlsAsync), will run imediately, because it is IQueryable followed by ToListAsync() method. hence it runs instantly (asynchronous), and returns a bunch of IEnumerables.
Meanwhile your second method (GetAllUrls), won't get run. Instead, it returns an expression and CALLER of this method is responsible to run the expression.

How does Google calculate my location on a desktop?

I am currently in Tokyo, and I used to be in Switzerland. Yet, my location until some days ago was not pinpinted exactly, except in the broad Tokyo area. Today I tried, and I appear to be in Switzerland. How?

Well the secret is that I am now connected through wireless, and my wireless router has been identified (thanks to association to other wifis around me at that time) in a very accurate area in Switzerland. Now, my wifi moved to Tokyo, but the queried system still thinks the wifi router is in Switzerland, because either it has no information about the additional wifis surrounding me right now, or it cannot sort out the conflicting info (namely, the specific info about my wifi router against my ip geolocation, which pinpoints me in the far east).

So, to answer your question, google, or someone for him, did "wardriving" around, mapping the wifi presence. Every time a query is performed to the system (probably in compliance with the W3C draft for the geolocation API) your computer sends the wifi identifiers it sees, and the system does two things:

  1. queries its database if geolocation exists for some of the wifis you passed, and returns the "wardrived" position if found, eventually with triangulation if intensities are present. The more wifi networks around, the higher is the accuracy of the positioning.
  2. adds additional networks you see that are currently not in the database to their database, so they can be reused later.

As you see, the system builds up by itself. The only thing you need is good seeding. After that, it extends in "50 meters chunks" (the range of a newly found wifi connection).

Of course, if you really want the system go banana, you can start exchanging wifi routers around the globe with fellow revolutionaries of the no-global-positioning movement.

How to get all files under a specific directory in MATLAB?

This answer does not directly answer the question but may be a good solution outside of the box.

I upvoted gnovice's solution, but want to offer another solution: Use the system dependent command of your operating system:

tic
asdfList = getAllFiles('../TIMIT_FULL/train');
toc
% Elapsed time is 19.066170 seconds.

tic
[status,cmdout] = system('find ../TIMIT_FULL/train/ -iname "*.wav"');
C = strsplit(strtrim(cmdout));
toc
% Elapsed time is 0.603163 seconds.

Positive:

  • Very fast (in my case for a database of 18000 files on linux).
  • You can use well tested solutions.
  • You do not need to learn or reinvent a new syntax to select i.e. *.wav files.

Negative:

  • You are not system independent.
  • You rely on a single string which may be hard to parse.

static linking only some libraries

Some loaders (linkers) provide switches for turning dynamic loading on and off. If GCC is running on such a system (Solaris - and possibly others), then you can use the relevant option.

If you know which libraries you want to link statically, you can simply specify the static library file in the link line - by full path.

Update or Insert (multiple rows and columns) from subquery in PostgreSQL

UPDATE table1 SET (col1, col2) = (col2, col3) FROM othertable WHERE othertable.col1 = 123;

JQuery add class to parent element

$(this.parentNode).addClass('newClass');

Spring @Transactional - isolation, propagation

You almost never want to use Read Uncommited since it's not really ACID compliant. Read Commmited is a good default starting place. Repeatable Read is probably only needed in reporting, rollup or aggregation scenarios. Note that many DBs, postgres included don't actually support Repeatable Read, you have to use Serializable instead. Serializable is useful for things that you know have to happen completely independently of anything else; think of it like synchronized in Java. Serializable goes hand in hand with REQUIRES_NEW propagation.

I use REQUIRES for all functions that run UPDATE or DELETE queries as well as "service" level functions. For DAO level functions that only run SELECTs, I use SUPPORTS which will participate in a TX if one is already started (i.e. being called from a service function).

What’s the best RESTful method to return total number of items in an object?

What about a new end point > /api/members/count which just calls Members.Count() and returns the result

Determine which MySQL configuration file is being used

If you run mysql --verbose --help | less it will tell you about line 11 which .cnf files it will look for.

You can also do mysql --print-defaults to show you how the configuration values it will use. This can also be useful in identifying just which config file it is loading.

Spring MVC - How to get all request params in a map in Spring controller?

While the other answers are correct it certainly is not the "Spring way" to use the HttpServletRequest object directly. The answer is actually quite simple and what you would expect if you're familiar with Spring MVC.

@RequestMapping(value = {"/search/", "/search"}, method = RequestMethod.GET)
public String search(
@RequestParam Map<String,String> allRequestParams, ModelMap model) {
   return "viewName";
}

What's the default password of mariadb on fedora?

just switch your current logged-in user to the root and login without password mysql -uroot

jquery $(window).width() and $(window).height() return different values when viewport has not been resized

I was having a very similar problem. I was getting inconsistent height() values when I refreshed my page. (It wasn't my variable causing the problem, it was the actual height value.)

I noticed that in the head of my page I called my scripts first, then my css file. I switched so that the css file is linked first, then the script files and that seems to have fixed the problem so far.

Hope that helps.

Add key value pair to all objects in array

Simply you can add that way. see below the console image

enter image description here

Java Reflection Performance

Yes, it is significantly slower. We were running some code that did that, and while I don't have the metrics available at the moment, the end result was that we had to refactor that code to not use reflection. If you know what the class is, just call the constructor directly.

Infinite Recursion with Jackson JSON and Hibernate JPA issue

You may use @JsonIgnore to break the cycle (reference).

You need to import org.codehaus.jackson.annotate.JsonIgnore (legacy versions) or com.fasterxml.jackson.annotation.JsonIgnore (current versions).

jQuery: how to get which button was clicked upon form submission?

As I can't comment on the accepted answer, I bring here a modified version that should take into account elements that are outside the form (ie: attached to the form using the form attribute). This is for modern browser: http://caniuse.com/#feat=form-attribute . The closest('form') is used as a fallback for unsupported form attribute

$(document).on('click', '[type=submit]', function() {
    var form = $(this).prop('form') || $(this).closest('form')[0];
    $(form.elements).filter('[type=submit]').removeAttr('clicked')
    $(this).attr('clicked', true);
});

$('form').on('submit', function() {
    var submitter = $(this.elements).filter('[clicked]');
})

Does swift have a trim method on String?

Here's how you remove all the whitespace from the beginning and end of a String.

(Example tested with Swift 2.0.)

let myString = "  \t\t  Let's trim all the whitespace  \n \t  \n  "
let trimmedString = myString.stringByTrimmingCharactersInSet(
    NSCharacterSet.whitespaceAndNewlineCharacterSet()
)
// Returns "Let's trim all the whitespace"

(Example tested with Swift 3+.)

let myString = "  \t\t  Let's trim all the whitespace  \n \t  \n  "
let trimmedString = myString.trimmingCharacters(in: .whitespacesAndNewlines)
// Returns "Let's trim all the whitespace"

python for increment inner loop

You might just be better of using while loops rather than for loops for this. I translated your code directly from the java code.

str1 = "ababa"
str2 = "aba"
i = 0

while i < len(str1):
  j = 0
  while j < len(str2):
    if not str1[i+j] == str1[j]:
      break
    if j == (len(str2) -1):
      i += len(str2)
    j+=1  
  i+=1

What's the point of 'meta viewport user-scalable=no' in the Google Maps API

You should not use the viewport meta tag at all if your design is not responsive. Misusing this tag may lead to broken layouts. You may read this article for documentation about why you should'n use this tag unless you know what you're doing. http://blog.javierusobiaga.com/stop-using-the-viewport-tag-until-you-know-ho

"user-scalable=no" also helps to prevent the zoom-in effect on iOS input boxes.

Scala how can I count the number of occurrences in a list

It is interesting to note that the map with default 0 value, intentionally designed for this case demonstrates the worst performance (and not as concise as groupBy)

    type Word = String
    type Sentence = Seq[Word]
    type Occurrences = scala.collection.Map[Char, Int]

  def woGrouped(w: Word): Occurrences = {
        w.groupBy(c => c).map({case (c, list) => (c -> list.length)})
  }                                               //> woGrouped: (w: forcomp.threadBug.Word)forcomp.threadBug.Occurrences

  def woGetElse0Map(w: Word): Occurrences = {
        val map = Map[Char, Int]()
        w.foldLeft(map)((m, c) => m + (c -> (m.getOrElse(c, 0) + 1)) )
  }                                               //> woGetElse0Map: (w: forcomp.threadBug.Word)forcomp.threadBug.Occurrences

  def woDeflt0Map(w: Word): Occurrences = {
        val map = Map[Char, Int]().withDefaultValue(0)
        w.foldLeft(map)((m, c) => m + (c -> (m(c) + 1)) )
  }                                               //> woDeflt0Map: (w: forcomp.threadBug.Word)forcomp.threadBug.Occurrences

  def dfltHashMap(w: Word): Occurrences = {
        val map = scala.collection.immutable.HashMap[Char, Int]().withDefaultValue(0)
        w.foldLeft(map)((m, c) => m + (c -> (m(c) + 1)) )
    }                                             //> dfltHashMap: (w: forcomp.threadBug.Word)forcomp.threadBug.Occurrences

    def mmDef(w: Word): Occurrences = {
        val map = scala.collection.mutable.Map[Char, Int]().withDefaultValue(0)
        w.foldLeft(map)((m, c) => m += (c -> (m(c) + 1)) )
  }                                               //> mmDef: (w: forcomp.threadBug.Word)forcomp.threadBug.Occurrences

    val functions = List("grp" -> woGrouped _, "mtbl" -> mmDef _, "else" -> woGetElse0Map _
    , "dfl0" -> woDeflt0Map _, "hash" -> dfltHashMap _
    )                                  //> functions  : List[(String, String => scala.collection.Map[Char,Int])] = Lis
                                                  //| t((grp,<function1>), (mtbl,<function1>), (else,<function1>), (dfl0,<functio
                                                  //| n1>), (hash,<function1>))


    val len = 100 * 1000                      //> len  : Int = 100000
    def test(len: Int) {
        val data: String = scala.util.Random.alphanumeric.take(len).toList.mkString
        val firstResult = functions.head._2(data)

        def run(f: Word => Occurrences): Int = {
            val time1 = System.currentTimeMillis()
            val result= f(data)
            val time2 = (System.currentTimeMillis() - time1)
            assert(result.toSet == firstResult.toSet)
            time2.toInt
        }

        def log(results: Seq[Int]) = {
                 ((functions zip results) map {case ((title, _), r) => title + " " + r} mkString " , ")
        }

        var groupResults = List.fill(functions.length)(1)

        val integrals = for (i <- (1 to 10)) yield {
            val results = functions map (f => (1 to 33).foldLeft(0) ((acc,_) => run(f._2)))
            println (log (results))
                groupResults = (results zip groupResults) map {case (r, gr) => r + gr}
                log(groupResults).toUpperCase
        }

        integrals foreach println

    }                                         //> test: (len: Int)Unit


    test(len)
    test(len * 2)
// GRP 14 , mtbl 11 , else 31 , dfl0 36 , hash 34
// GRP 91 , MTBL 111

    println("Done")
    def main(args: Array[String]) {
    }

produces

grp 5 , mtbl 5 , else 13 , dfl0 17 , hash 17
grp 3 , mtbl 6 , else 14 , dfl0 16 , hash 16
grp 3 , mtbl 6 , else 13 , dfl0 17 , hash 15
grp 4 , mtbl 5 , else 13 , dfl0 15 , hash 16
grp 23 , mtbl 6 , else 14 , dfl0 15 , hash 16
grp 5 , mtbl 5 , else 13 , dfl0 16 , hash 17
grp 4 , mtbl 6 , else 13 , dfl0 16 , hash 16
grp 4 , mtbl 6 , else 13 , dfl0 17 , hash 15
grp 3 , mtbl 5 , else 14 , dfl0 16 , hash 16
grp 3 , mtbl 6 , else 14 , dfl0 16 , hash 16
GRP 5 , MTBL 5 , ELSE 13 , DFL0 17 , HASH 17
GRP 8 , MTBL 11 , ELSE 27 , DFL0 33 , HASH 33
GRP 11 , MTBL 17 , ELSE 40 , DFL0 50 , HASH 48
GRP 15 , MTBL 22 , ELSE 53 , DFL0 65 , HASH 64
GRP 38 , MTBL 28 , ELSE 67 , DFL0 80 , HASH 80
GRP 43 , MTBL 33 , ELSE 80 , DFL0 96 , HASH 97
GRP 47 , MTBL 39 , ELSE 93 , DFL0 112 , HASH 113
GRP 51 , MTBL 45 , ELSE 106 , DFL0 129 , HASH 128
GRP 54 , MTBL 50 , ELSE 120 , DFL0 145 , HASH 144
GRP 57 , MTBL 56 , ELSE 134 , DFL0 161 , HASH 160
grp 7 , mtbl 11 , else 28 , dfl0 31 , hash 31
grp 7 , mtbl 10 , else 28 , dfl0 32 , hash 31
grp 7 , mtbl 11 , else 28 , dfl0 31 , hash 32
grp 7 , mtbl 11 , else 28 , dfl0 31 , hash 33
grp 7 , mtbl 11 , else 28 , dfl0 32 , hash 31
grp 8 , mtbl 11 , else 28 , dfl0 31 , hash 33
grp 8 , mtbl 11 , else 29 , dfl0 38 , hash 35
grp 7 , mtbl 11 , else 28 , dfl0 32 , hash 33
grp 8 , mtbl 11 , else 32 , dfl0 35 , hash 41
grp 7 , mtbl 13 , else 28 , dfl0 33 , hash 35
GRP 7 , MTBL 11 , ELSE 28 , DFL0 31 , HASH 31
GRP 14 , MTBL 21 , ELSE 56 , DFL0 63 , HASH 62
GRP 21 , MTBL 32 , ELSE 84 , DFL0 94 , HASH 94
GRP 28 , MTBL 43 , ELSE 112 , DFL0 125 , HASH 127
GRP 35 , MTBL 54 , ELSE 140 , DFL0 157 , HASH 158
GRP 43 , MTBL 65 , ELSE 168 , DFL0 188 , HASH 191
GRP 51 , MTBL 76 , ELSE 197 , DFL0 226 , HASH 226
GRP 58 , MTBL 87 , ELSE 225 , DFL0 258 , HASH 259
GRP 66 , MTBL 98 , ELSE 257 , DFL0 293 , HASH 300
GRP 73 , MTBL 111 , ELSE 285 , DFL0 326 , HASH 335
Done

It is curious that most concise groupBy is faster than even mutable map!

How to check if a file exists from inside a batch file

C:\>help if

Performs conditional processing in batch programs.

IF [NOT] ERRORLEVEL number command

IF [NOT] string1==string2 command

IF [NOT] EXIST filename command

How to create EditText with cross(x) button at end of it?

If you are in frame layout or you can create a frame layout I tried another approach....

<TextView
    android:id="@+id/inputSearch"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:drawableRight="@drawable/ic_actionbar"
    android:layout_alignParentBottom="true"
    android:layout_toRightOf="@+id/back_button"/>

<Button
    android:id="@+id/clear_text_invisible_button"
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:layout_gravity="right|center_vertical"
    android:background="@color/transparent"
    android:layout_alignBaseline="@+id/inputSearch"
    android:layout_alignBottom="@+id/inputSearch"
    android:layout_alignRight="@+id/inputSearch"
    android:layout_alignEnd="@+id/inputSearch"
    android:layout_marginRight="13dp"
    />

This is an edit text where I put a cross icon as a right drawable and than UPON it I put a transparent button which clears text.

How to get child element by ID in JavaScript?

(Dwell in atom)

<div id="note">

   <textarea id="textid" class="textclass">Text</textarea>

</div>

<script type="text/javascript">

   var note = document.getElementById('textid').value;

   alert(note);

</script>

failed to open stream: HTTP wrapper does not support writeable connections

May this code help you. It works in my case.

$filename = "D:\xampp\htdocs\wordpress/wp-content/uploads/json/2018-10-25.json";
    $fileUrl = "http://localhost/wordpress/wp-content/uploads/json/2018-10-25.json";
    if(!file_exists($filename)):
        $handle = fopen( $filename, 'a' ) or die( 'Cannot open file:  ' . $fileUrl ); //implicitly creates file
        fwrite( $handle, json_encode(array()));
        fclose( $handle );
    endif;
    $response = file_get_contents($filename);
    $tempArray = json_decode($response);
    if(!empty($tempArray)):
        $count = count($tempArray) + 1;
    else:
        $count = 1;
    endif;
    $tempArray[] = array_merge(array("sn." => $count), $data);
    $jsonData = json_encode($tempArray);
    file_put_contents($filename, $jsonData);

Failed to find Build Tools revision 23.0.1

Nothing helped until I found this solution : https://stackoverflow.com/a/39068538/3995091

In Android SDK, the build tools with the correct version where shown as installed, but still I got the same error saying they couldn't be found. When I used the above solution, I found out they were indeed not installed, although Android SDK thought they were. Installing them solved it for me.

How to do error logging in CodeIgniter (PHP)

Also make sure that you have allowed codeigniter to log the type of messages you want in a config file.

i.e $config['log_threshold'] = [log_level ranges 0-4];

Unknown version of Tomcat was specified in Eclipse

Probably, you are trying to point the tomcat directory having the source folder. Please download the tomcat binary version from here .For Linux environments, there you can find .zip and .tar.gz files under core section. Please download and extract them. after that, if you point this extracted directory, eclipse will be able to identify the tomcat version. Eclipse was not able to find the version of tomcat, since the directory you pointed out didn't contain the conf folder. Hope this helps!

IE throws JavaScript Error: The value of the property 'googleMapsQuery' is null or undefined, not a Function object (works in other browsers)

Just a few minutes ago i was facing the same problem. I got the problem that is after just placing your jQuery start the other jQuery scripting. After all it will work fine.

What's the difference between returning value or Promise.resolve from then()

You already got a good formal answer. I figured I should add a short one.

The following things are identical with Promises/A+ promises:

  • Calling Promise.resolve (In your Angular case that's $q.when)
  • Calling the promise constructor and resolving in its resolver. In your case that's new $q.
  • Returning a value from a then callback.
  • Calling Promise.all on an array with a value and then extract that value.

So the following are all identical for a promise or plain value X:

Promise.resolve(x);
new Promise(function(resolve, reject){ resolve(x); });
Promise.resolve().then(function(){ return x; });
Promise.all([x]).then(function(arr){ return arr[0]; });

And it's no surprise, the promises specification is based on the Promise Resolution Procedure which enables easy interoperation between libraries (like $q and native promises) and makes your life overall easier. Whenever a promise resolution might occur a resolution occurs creating overall consistency.

How to add a boolean datatype column to an existing table in sql?

The answer given by P????? creates a nullable bool, not a bool, which may be fine for you. For example in C# it would create: bool? AdminApprovednot bool AdminApproved.

If you need to create a bool (defaulting to false):

    ALTER TABLE person
    ADD AdminApproved BIT
    DEFAULT 0 NOT NULL;

How to change MySQL column definition?

Do you mean altering the table after it has been created? If so you need to use alter table, in particular:

ALTER TABLE tablename MODIFY COLUMN new-column-definition

e.g.

ALTER TABLE test MODIFY COLUMN locationExpect VARCHAR(120);

Removing duplicates in the lists

Test = [1,8,2,7,3,4,5,1,2,3,6]
Test.sort()
i=1
while i< len(Test):
  if Test[i] == Test[i-1]:
    Test.remove(Test[i])
  i= i+1
print(Test)

INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server

Parent table data missing causes the problem. In your problem non availability of data in "dbo.Sup_Item_Cat" causes the problem

How do I do an initial push to a remote repository with Git?

I am aware there are existing answers which solves the problem. For those who are new to git, As of 02/11/2021, The default branch in git is "main" not "master" branch, The command will be

git push -u origin main

Can't access RabbitMQ web management interface after fresh install

If on Windows and installed using chocolatey make sure firewall is allowing the default ports for it:

netsh advfirewall firewall add rule name="RabbitMQ Management" dir=in action=allow protocol=TCP localport=15672
netsh advfirewall firewall add rule name="RabbitMQ" dir=in action=allow protocol=TCP localport=5672

for the remote access.

source of historical stock data

Let me add a source I just discovered, found here.

It has lots of historical stock data in csv format and was gathered by Andy Pavlo, who according to his homepage is an "Assistant Professor in the Computer Science Department at Carnegie Mellon University".

Filtering DataGridView without changing datasource

I just spent an hour on a similar problem. For me the answer turned out to be embarrassingly simple.

(dataGridViewFields.DataSource as DataTable).DefaultView.RowFilter = string.Format("Field = '{0}'", textBoxFilter.Text);

What is float in Java?

In Java, when you type a decimal number as 3.6, its interpreted as a double. double is a 64-bit precision IEEE 754 floating point, while floatis a 32-bit precision IEEE 754 floating point. As a float is less precise than a double, the conversion cannot be performed implicitly.

If you want to create a float, you should end your number with f (i.e.: 3.6f).

For more explanation, see the primitive data types definition of the Java tutorial.

Date minus 1 year?

On my website, to check if registering people is 18 years old, I simply used the following :

$legalAge = date('Y-m-d', strtotime('-18 year'));

After, only compare the the two dates.

Hope it could help someone.

jquery datatables default sort

There are a couple of options:

  1. Just after initialising DataTables, remove the sorting classes on the TD element in the TBODY.

  2. Disable the sorting classes using http://datatables.net/ref#bSortClasses . Problem with this is that it will disable the sort classes for user sort requests - which might or might not be what you want.

  3. Have your server output the table in your required sort order, and don't apply a default sort on the table (aaSorting:[]).

How to center a button within a div?

You could just make:

_x000D_
_x000D_
<div style="text-align: center; border: 1px solid">_x000D_
  <input type="button" value="button">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Or you could do it like this instead:

_x000D_
_x000D_
<div style="border: 1px solid">_x000D_
  <input type="button" value="button" style="display: block; margin: 0 auto;">_x000D_
</div>
_x000D_
_x000D_
_x000D_

The first one will center align everything inside the div. The other one will center align just the button.

python modify item in list, save back in list

You could do this:

for idx, item in enumerate(list):
   if 'foo' in item:
       item = replace_all(...)
       list[idx] = item

How to hide scrollbar in Firefox?

I tried everything and what worked best for my solution was to always have the vertical scrollbar show, and then add some negative margin to hide it.

This worked for IE11, FF60.9 and Chrome 80

body {
  -ms-overflow-style: none; /** IE11 */
  overflow-y: scroll;
  overflow-x: hidden;
  margin-right: -20px;
}

How to check if a value exists in an object using JavaScript

You can try this:

function checkIfExistingValue(obj, key, value) {
    return obj.hasOwnProperty(key) && obj[key] === value;
}
var test = [{name : "jack", sex: F}, {name: "joe", sex: M}]
console.log(test.some(function(person) { return checkIfExistingValue(person, "name", "jack"); }));

Find all special characters in a column in SQL Server 2008

select count(*) from dbo.tablename where address_line_1 LIKE '%[\'']%' {eSCAPE'\'}

Abstract Class vs Interface in C++

I assume that with interface you mean a C++ class with only pure virtual methods (i.e. without any code), instead with abstract class you mean a C++ class with virtual methods that can be overridden, and some code, but at least one pure virtual method that makes the class not instantiable. e.g.:

class MyInterface
{
public:
  // Empty virtual destructor for proper cleanup
  virtual ~MyInterface() {}

  virtual void Method1() = 0;
  virtual void Method2() = 0;
};


class MyAbstractClass
{
public:
  virtual ~MyAbstractClass();

  virtual void Method1();
  virtual void Method2();
  void Method3();

  virtual void Method4() = 0; // make MyAbstractClass not instantiable
};

In Windows programming, interfaces are fundamental in COM. In fact, a COM component exports only interfaces (i.e. pointers to v-tables, i.e. pointers to set of function pointers). This helps defining an ABI (Application Binary Interface) that makes it possible to e.g. build a COM component in C++ and use it in Visual Basic, or build a COM component in C and use it in C++, or build a COM component with Visual C++ version X and use it with Visual C++ version Y. In other words, with interfaces you have high decoupling between client code and server code.

Moreover, when you want to build DLL's with a C++ object-oriented interface (instead of pure C DLL's), as described in this article, it's better to export interfaces (the "mature approach") instead of C++ classes (this is basically what COM does, but without the burden of COM infrastructure).

I'd use an interface if I want to define a set of rules using which a component can be programmed, without specifying a concrete particular behavior. Classes that implement this interface will provide some concrete behavior themselves.

Instead, I'd use an abstract class when I want to provide some default infrastructure code and behavior, and make it possible to client code to derive from this abstract class, overriding the pure virtual methods with some custom code, and complete this behavior with custom code. Think for example of an infrastructure for an OpenGL application. You can define an abstract class that initializes OpenGL, sets up the window environment, etc. and then you can derive from this class and implement custom code for e.g. the rendering process and handling user input:

// Abstract class for an OpenGL app.
// Creates rendering window, initializes OpenGL; 
// client code must derive from it 
// and implement rendering and user input.
class OpenGLApp
{
public:
  OpenGLApp();
  virtual ~OpenGLApp();
  ...

  // Run the app    
  void Run();


  // <---- This behavior must be implemented by the client ---->

  // Rendering
  virtual void Render() = 0;

  // Handle user input
  // (returns false to quit, true to continue looping)
  virtual bool HandleInput() = 0;

  // <--------------------------------------------------------->


private:
  //
  // Some infrastructure code
  //
  ... 
  void CreateRenderingWindow();
  void CreateOpenGLContext();
  void SwapBuffers();
};


class MyOpenGLDemo : public OpenGLApp
{
public:
  MyOpenGLDemo();
  virtual ~MyOpenGLDemo();

  // Rendering
  virtual void Render();  // implements rendering code

  // Handle user input
  virtual bool HandleInput(); // implements user input handling


  //  ... some other stuff
};

How can I get column names from a table in Oracle?

SELECT COLUMN_NAME 'all_columns' 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME='user';

How to trigger the window resize event in JavaScript?

window.resizeBy() will trigger window's onresize event. This works in both Javascript or VBScript.

window.resizeBy(xDelta, yDelta) called like window.resizeBy(-200, -200) to shrink page 200px by 200px.

Java: get greatest common divisor

/*
import scanner and instantiate scanner class;
declare your method with two parameters
declare a third variable;
set condition;
swap the parameter values if condition is met;
set second conditon based on result of first condition;
divide and assign remainder to the third variable;
swap the result;
in the main method, allow for user input;
Call the method;

*/
public class gcf {
    public static void main (String[]args){//start of main method
        Scanner input = new Scanner (System.in);//allow for user input
        System.out.println("Please enter the first integer: ");//prompt
        int a = input.nextInt();//initial user input
        System.out.println("Please enter a second interger: ");//prompt
        int b = input.nextInt();//second user input


       Divide(a,b);//call method
    }
   public static void Divide(int a, int b) {//start of your method

    int temp;
    // making a greater than b
    if (b > a) {
         temp = a;
         a = b;
         b = temp;
    }

    while (b !=0) {
        // gcd of b and a%b
        temp = a%b;
        // always make a greater than b
        a =b;
        b =temp;

    }
    System.out.println(a);//print to console
  }
}

Inserting string at position x of another string

var array = a.split(' '); 
array.splice(position, 0, b);
var output = array.join(' ');

This would be slower, but will take care of the addition of space before and after the an Also, you'll have to change the value of position ( to 2, it's more intuitive now)

HTTP post XML data in C#

AlliterativeAlice's example helped me tremendously. In my case, though, the server I was talking to didn't like having single quotes around utf-8 in the content type. It failed with a generic "Server Error" and it took hours to figure out what it didn't like:

request.ContentType = "text/xml; encoding=utf-8";

How to distinguish mouse "click" and "drag"

If just to filter out the drag case, do it like this:

var moved = false;
$(selector)
  .mousedown(function() {moved = false;})
  .mousemove(function() {moved = true;})
  .mouseup(function(event) {
    if (!moved) {
        // clicked without moving mouse
    }
  });

Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib

I just ran into this annoying problem today. We use SmartAssembly to pack/obfuscate our .NET assemblies, but suddenly the final product wasn't working on our test systems. I didn't even think I had .NET 4.5, but apparently something installed it about a month ago.

I uninstalled 4.5 and reinstalled 4.0, and now everything is working again. Not too impressed with having blown an afternoon on this.

@Autowired and static method

You have to workaround this via static application context accessor approach:

@Component
public class StaticContextAccessor {

    private static StaticContextAccessor instance;

    @Autowired
    private ApplicationContext applicationContext;

    @PostConstruct
    public void registerInstance() {
        instance = this;
    }

    public static <T> T getBean(Class<T> clazz) {
        return instance.applicationContext.getBean(clazz);
    }

}

Then you can access bean instances in a static manner.

public class Boo {

    public static void randomMethod() {
         StaticContextAccessor.getBean(Foo.class).doStuff();
    }

}

Specifying onClick event type with Typescript and React.Konva

As posted in my update above, a potential solution would be to use Declaration Merging as suggested by @Tyler-sebastion. I was able to define two additional interfaces and add the index property on the EventTarget in this way.

interface KonvaTextEventTarget extends EventTarget {
  index: number
}

interface KonvaMouseEvent extends React.MouseEvent<HTMLElement> {
  target: KonvaTextEventTarget
}

I then can declare the event as KonvaMouseEvent in my onclick MouseEventHandler function.

onClick={(event: KonvaMouseEvent) => {
          makeMove(ownMark, event.target.index)
}}

I'm still not 100% if this is the best approach as it feels a bit Kludgy and overly verbose just to get past the tslint error.

iPad/iPhone hover problem causes the user to double click a link

MacFreak's answer was extremely helpful to me. Here's some hands-on code in case it helps you.

PROBLEM - applying touchend means every time you scroll your finger over an element, it responds as if you've pressed it, even if you were just trying to scroll past.

I'm creating an effect with jQuery which fades up a line under some buttons to "highlight" the hovered button. I do not want this to mean you have to press the button twice on touch devices to follow the link.

Here are the buttons:

<a class="menu_button" href="#">
    <div class="menu_underline"></div>
</a>

I want the "menu_underline" div to fade up on mouseover and fade out on mouseout. BUT I want touch devices to be able to follow the link on one single click, not two.

SOLUTION - Here's the jQuery to make it work:

//Mouse Enter
$('.menu_button').bind('touchstart mouseenter', function(){
    $(this).find(".menu_underline").fadeIn();
});

//Mouse Out   
$('.menu_button').bind('mouseleave touchmove click', function(){
    $(this).find(".menu_underline").fadeOut();
});

Many thanks for your help on this MacFreak.

Math.random() versus Random.nextInt(int)

Here is the detailed explanation of why "Random.nextInt(n) is both more efficient and less biased than Math.random() * n" from the Sun forums post that Gili linked to:

Math.random() uses Random.nextDouble() internally.

Random.nextDouble() uses Random.next() twice to generate a double that has approximately uniformly distributed bits in its mantissa, so it is uniformly distributed in the range 0 to 1-(2^-53).

Random.nextInt(n) uses Random.next() less than twice on average- it uses it once, and if the value obtained is above the highest multiple of n below MAX_INT it tries again, otherwise is returns the value modulo n (this prevents the values above the highest multiple of n below MAX_INT skewing the distribution), so returning a value which is uniformly distributed in the range 0 to n-1.

Prior to scaling by 6, the output of Math.random() is one of 2^53 possible values drawn from a uniform distribution.

Scaling by 6 doesn't alter the number of possible values, and casting to an int then forces these values into one of six 'buckets' (0, 1, 2, 3, 4, 5), each bucket corresponding to ranges encompassing either 1501199875790165 or 1501199875790166 of the possible values (as 6 is not a disvisor of 2^53). This means that for a sufficient number of dice rolls (or a die with a sufficiently large number of sides), the die will show itself to be biased towards the larger buckets.

You will be waiting a very long time rolling dice for this effect to show up.

Math.random() also requires about twice the processing and is subject to synchronization.

DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server

The use of the deprecated new Buffer() constructor (i.E. as used by Yarn) can cause deprecation warnings. Therefore one should NOT use the deprecated/unsafe Buffer constructor.

According to the deprecation warning new Buffer() should be replaced with one of:

  • Buffer.alloc()
  • Buffer.allocUnsafe() or
  • Buffer.from()

Another option in order to avoid this issue would be using the safe-buffer package instead.

You can also try (when using yarn..):

yarn global add yarn

as mentioned here: Link

Another suggestion from the comments (thx to gkiely): self-update

Note: self-update is not available. See policies for enforcing versions within a project

In order to update your version of Yarn, run

curl --compressed -o- -L https://yarnpkg.com/install.sh | bash

MVC 4 Razor adding input type date

The input date value format needs the date specified as per http://tools.ietf.org/html/rfc3339#section-5.6 full-date.

So I've ended up doing:

<input type="date" id="last-start-date" value="@string.Format("{0:yyyy-MM-dd}", Model.LastStartDate)" />

I did try doing it "properly" using:

[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime LastStartDate
{
    get { return lastStartDate; }
    set { lastStartDate = value; }
}

with

@Html.TextBoxFor(model => model.LastStartDate, 
    new { type = "date" })

Unfortunately that always seemed to set the value attribute of the input to a standard date time so I've ended up applying the formatting directly as above.

Edit:

According to Jorn if you use

@Html.EditorFor(model => model.LastStartDate)

instead of TextBoxFor it all works fine.

How to get list of dates between two dates in mysql select query

Try:

select * from 
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'

-for date ranges up to nearly 300 years in the future.

[Corrected following a suggested edit by UrvishAtSynapse.]

Java for loop multiple variables

Only two Semicolons are allowed to be used in for loop.

  1. Before first semicolon is the initialization part.
  2. After first semicolon and before second semicolon is condition part (must result in boolean).
  3. After second semicolon is variable manipulation part (increment/decrement part).

If you have do initialization of multiple variables or manipulation of multiple variables, you can achieve it by separating them with comma(,).

for(int i=0, j=5; i < 5; i++, j--)

NOTE: Multiple conditions separated by comma are NOT allowed.

for(int i=0, j=5; i < 5, j > 5; i++, j--) // This is NOT allowed.

Merging two CSV files using Python

You need to store all of the extra rows in the files in your dictionary, not just one of them:

dict1 = {row[0]: row[1:] for row in r}
...
dict2 = {row[0]: row[1:] for row in r}

Then, since the values in the dictionaries are lists, you need to just concatenate the lists together:

w.writerows([[key] + dict1.get(key, []) + dict2.get(key, []) for key in keys])

How can I extract a predetermined range of lines from a text file on Unix?

Since we are talking about extracting lines of text from a text file, I will give an special case where you want to extract all lines that match a certain pattern.

myfile content:
=====================
line1 not needed
line2 also discarded
[Data]
first data line
second data line
=====================
sed -n '/Data/,$p' myfile

Will print the [Data] line and the remaining. If you want the text from line1 to the pattern, you type: sed -n '1,/Data/p' myfile. Furthermore, if you know two pattern (better be unique in your text), both the beginning and end line of the range can be specified with matches.

sed -n '/BEGIN_MARK/,/END_MARK/p' myfile

Convert Uppercase Letter to Lowercase and First Uppercase in Sentence using CSS

You can't do that purely with CSS. There is a text-transform attribute, but it only accepts none, capitalize, uppercase, lowercase and inherit.

You might want to look into either a JS solution or a server-side solution for that.

pass array to method Java

public static void main(String[] args) {

    int[] A=new int[size];
      //code for take input in array
      int[] C=sorting(A); //pass array via method
      //and then print array

    }
public static int[] sorting(int[] a) {
     //code for work with array 
     return a; //retuen array
}

Set a div width, align div center and text align left

Use auto margins.

div {
   margin-left: auto;
   margin-right: auto;
   width: NNNpx;

   /* NOTE: Only works for non-floated block elements */
   display: block;
   float: none;
}

Further reading at SimpleBits CSS Centering 101

Set Font Color, Font Face and Font Size in PHPExcel

I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray() According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.

This will work for you:

$phpExcel = new PHPExcel();

$styleArray = array(
    'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));

$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);

To apply font style to complete excel document:

 $styleArray = array(
   'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));      
 $phpExcel->getDefaultStyle()
    ->applyFromArray($styleArray);

How to uninstall jupyter

When you $ pip install jupyter several dependencies are installed. The best way to uninstall it completely is by running:

  1. $ pip install pip-autoremove
  2. $ pip-autoremove jupyter -y

Kindly refer to this related question.

pip-autoremove removes a package and its unused dependencies. Here are the docs.

How to call code behind server method from a client side JavaScript function?

Ajax is the way to go. The easiest (and probably the best) approach is jQuery ajax()

You'll end up writing something like this:

$.ajax({
  url: "test.html",
  context: document.body,
  success: function(){
    // do something when done
  }
});

How to convert decimal to hexadecimal in JavaScript

Here's my solution:

hex = function(number) {
  return '0x' + Math.abs(number).toString(16);
}

The question says: "How to convert decimal to hexadecimal in JavaScript". While, the question does not specify that the hexadecimal string should begin with a 0x prefix, anybody who writes code should know that 0x is added to hexadecimal codes to distinguish hexadecimal codes from programmatic identifiers and other numbers (1234 could be hexadecimal, decimal, or even octal).

Therefore, to correctly answer this question, for the purpose of script-writing, you must add the 0x prefix.

The Math.abs(N) function converts negatives to positives, and as a bonus, it doesn't look like somebody ran it through a wood-chipper.

The answer I wanted, would have had a field-width specifier, so we could for example show 8/16/32/64-bit values the way you would see them listed in a hexadecimal editing application. That, is the actual, correct answer.

Read a file in Node.js

Use path.join(__dirname, '/start.html');

var fs = require('fs'),
    path = require('path'),    
    filePath = path.join(__dirname, 'start.html');

fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
    if (!err) {
        console.log('received data: ' + data);
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.write(data);
        response.end();
    } else {
        console.log(err);
    }
});

check all socket opened in linux OS

/proc/net/tcp -a list of open tcp sockets

/proc/net/udp -a list of open udp sockets

/proc/net/raw -a list all the 'raw' sockets

These are the files, use cat command to view them. For example:

cat /proc/net/tcp

You can also use the lsof command.

lsof is a command meaning "list open files", which is used in many Unix-like systems to report a list of all open files and the processes that opened them.

Django MEDIA_URL and MEDIA_ROOT

This if for Django 1.10:

 if settings.DEBUG:
    urlpatterns += staticfiles_urlpatterns()
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Creating a range of dates in Python

I thought I'd throw in my two cents with a simple (and not complete) implementation of a date range:

from datetime import date, timedelta, datetime

class DateRange:
    def __init__(self, start, end, step=timedelta(1)):
        self.start = start
        self.end = end
        self.step = step

    def __iter__(self):
        start = self.start
        step = self.step
        end = self.end

        n = int((end - start) / step)
        d = start

        for _ in range(n):
            yield d
            d += step

    def __contains__(self, value):
        return (
            (self.start <= value < self.end) and 
            ((value - self.start) % self.step == timedelta(0))
        )

Split string using a newline delimiter with Python

If you want to split only by newlines, you can use str.splitlines():

Example:

>>> data = """a,b,c
... d,e,f
... g,h,i
... j,k,l"""
>>> data
'a,b,c\nd,e,f\ng,h,i\nj,k,l'
>>> data.splitlines()
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

With str.split() your case also works:

>>> data = """a,b,c
... d,e,f
... g,h,i
... j,k,l"""
>>> data
'a,b,c\nd,e,f\ng,h,i\nj,k,l'
>>> data.split()
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

However if you have spaces (or tabs) it will fail:

>>> data = """
... a, eqw, qwe
... v, ewr, err
... """
>>> data
'\na, eqw, qwe\nv, ewr, err\n'
>>> data.split()
['a,', 'eqw,', 'qwe', 'v,', 'ewr,', 'err']

What is WEB-INF used for in a Java EE web application?

This convention is followed for security reasons. For example if unauthorized person is allowed to access root JSP file directly from URL then they can navigate through whole application without any authentication and they can access all the secured data.

SSH configuration: override the default username

You can use a shortcut. Create a .bashrc file in your home directory. In there, you can add the following:

alias sshb="ssh buck@host"

To make the alias available in your terminal, you can either close and open your terminal, or run

source ~/.bashrc

Then you can connect by just typing in:

sshb

How do I find the current executable filename?

In addition to the answers above.

I wrote following test.exe as console application

static void Main(string[] args) {
  Console.WriteLine(
    System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
  Console.WriteLine(
    System.Reflection.Assembly.GetEntryAssembly().Location);
  Console.WriteLine(
    System.Reflection.Assembly.GetExecutingAssembly().Location);
  Console.WriteLine(
    System.Reflection.Assembly.GetCallingAssembly().Location);
}

Then I compiled the project and renamed its output to the test2.exe file. The output lines were correct and the same.

But, if I start it in the Visual Studio, the result is:

d:\test2.vhost.exe

d:\test2.exe

d:\test2.exe

C:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll

The ReSharper plug-in to the Visual Studio has underlined the

System.Diagnostics.Process.GetCurrentProcess().MainModule

as possible System.NullReferenceException. If you look into documentation of the MainModule you will find that this property can throw also NotSupportedException, PlatformNotSupportedException and InvalidOperationException.

The GetEntryAssembly method is also not 100% "safe". MSDN:

The GetEntryAssembly method can return null when a managed assembly has been loaded from an unmanaged application. For example, if an unmanaged application creates an instance of a COM component written in C#, a call to the GetEntryAssembly method from the C# component returns null, because the entry point for the process was unmanaged code rather than a managed assembly.

For my solutions, I prefer the Assembly.GetEntryAssembly().Location.

More interest is if need to solve the problem for the virtualization. For example, we have a project, where we use a Xenocode Postbuild to link the .net code into one executable. This executable must be renamed. So all the methods above didn't work, because they only gets the information for the original assembly or inner process.

The only solution I found is

var location = System.Reflection.Assembly.GetEntryAssembly().Location;
var directory = System.IO.Path.GetDirectoryName(location);
var file = System.IO.Path.Combine(directory, 
  System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe");

Split string with delimiters in C

My version:

int split(char* str, const char delimeter, char*** args) {
    int cnt = 1;
    char* t = str;

    while (*t == delimeter) t++;

    char* t2 = t;
    while (*(t2++))
        if (*t2 == delimeter && *(t2 + 1) != delimeter && *(t2 + 1) != 0) cnt++;

    (*args) = malloc(sizeof(char*) * cnt);

    for(int i = 0; i < cnt; i++) {
        char* ts = t;
        while (*t != delimeter && *t != 0) t++;

        int len = (t - ts + 1);
        (*args)[i] = malloc(sizeof(char) * len);
        memcpy((*args)[i], ts, sizeof(char) * (len - 1));
        (*args)[i][len - 1] = 0;

        while (*t == delimeter) t++;
    }

    return cnt;
}

What is RSS and VSZ in Linux memory management

RSS is Resident Set Size (physically resident memory - this is currently occupying space in the machine's physical memory), and VSZ is Virtual Memory Size (address space allocated - this has addresses allocated in the process's memory map, but there isn't necessarily any actual memory behind it all right now).

Note that in these days of commonplace virtual machines, physical memory from the machine's view point may not really be actual physical memory.

How to set up Android emulator proxy settings

On Android Studio:

Click on Edit Configuration under App Menu

enter image description here

  1. Go to App or Android App (as default settings)
  2. tap on Debugger
  3. Tap on LLDB startup command
  4. Tap +
  5. Add you command -http-proxy http://168.192.1.2:3300

enter image description here

that`s it.

More cool stuff if you wanna use your PC IP, use this command:

  • -http-proxy "$(ipconfig getifaddr en0)":8888 on MacOS
  • -http-proxy "$(hostname -i)":8888 on Linux

Javascript add leading zeroes to date

You could use ternary operator to format the date like an "if" statement.

For example:

var MyDate = new Date();
MyDate.setDate(MyDate.getDate()+10);
var MyDateString = (MyDate.getDate() < 10 ? '0' + MyDate.getDate() : MyDate.getDate()) + '/' + ((d.getMonth()+1) < 10 ? '0' + (d.getMonth()+1) : (d.getMonth()+1)) + '/' + MyDate.getFullYear();

So

(MyDate.getDate() < 10 ? '0' + MyDate.getDate() : MyDate.getDate())

would be similar to an if statement, where if the getDate() returns a value less than 10, then return a '0' + the Date, or else return the date if greater than 10 (since we do not need to add the leading 0). Same for the month.

Edit: Forgot that getMonth starts with 0, so added the +1 to account for it. Of course you could also just say d.getMonth() < 9 :, but I figured using the +1 would help make it easier to understand.

How to mark-up phone numbers?

The best bet is to start off with tel: which works on all mobiles

Then put in this code, which will only run when on a desktop, and only when a link is clicked.

I'm using http://detectmobilebrowsers.com/ to detect mobile browsers, you can use whatever method you prefer

if (!jQuery.browser.mobile) {
    jQuery('body').on('click', 'a[href^="tel:"]', function() {
            jQuery(this).attr('href', 
                jQuery(this).attr('href').replace(/^tel:/, 'callto:'));
    });
}

So basically you cover all your bases.

tel: works on all phones to open the dialer with the number

callto: works on your computer to connect to skype from firefox, chrome

BAT file: Open new cmd window and execute a command in there

You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.

What I found out was to use the K switch like this:

start cmd /k echo Hello, World!

start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.

You can also use the /C switch for something similar.

start cmd /C pause

This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.


Use the following in your batch file:

start cmd.exe /c "more-batch-commands-here"

or

start cmd.exe /k "more-batch-commands-here"

/c Carries out the command specified by string and then terminates

/k Carries out the command specified by string but remains

The /c and /k options controls what happens once your command finishes running. With /c the terminal window will close automatically, leaving your desktop clean. With /k the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.

Consult the cmd.exe documentation using cmd /? for more details.

Escaping Commands with White Spaces

The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.

Examples:

Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt

Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"

Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""

Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""

Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""

Source: http://ss64.com/nt/cmd.html

A message body writer for Java type, class myPackage.B, and MIME media type, application/octet-stream, was not found

Make sure that all these libs are in your class path:

compile(group: 'com.sun.jersey', name: 'jersey-core',        version: '1.19.4') 
compile(group: 'com.sun.jersey', name: 'jersey-server',      version: '1.19.4') 
compile(group: 'com.sun.jersey', name: 'jersey-servlet',     version: '1.19.4')
compile(group: 'com.sun.jersey', name: 'jersey-json',        version: '1.19.4')
compile(group: 'com.sun.jersey', name: 'jersey-client',      version: '1.19.4')
compile(group: 'javax.ws.rs', name: 'jsr311-api', version: '1.1.1')
compile(group: 'org.codehaus.jackson', name: 'jackson-core-asl', version: '1.9.2')
compile(group: 'org.codehaus.jackson', name: 'jackson-mapper-asl', version: '1.9.2')
compile(group: 'org.codehaus.jackson', name: 'jackson-core-asl',   version: '1.9.2')
compile(group: 'org.codehaus.jackson', name: 'jackson-jaxrs',      version: '1.9.2')
compile(group: 'org.codehaus.jackson', name: 'jackson-xc',         version: '1.9.2')

Add "Pojo Mapping" and "Jackson Provider" to the jersey client config:

ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
clientConfig.getClasses().add(JacksonJsonProvider.class);

This solve to me!

ClientResponse response = null;

response = webResource
        .type(MediaType.APPLICATION_JSON)
        .accept(MediaType.APPLICATION_JSON)
        .get(ClientResponse.class);


if (response.getStatus() == Response.Status.OK.getStatusCode()) {

    MyClass myclass = response.getEntity(MyClass.class);
    System.out.println(myclass);
}

How can I reference a commit in an issue comment on GitHub?

To reference a commit, simply write its SHA-hash, and it'll automatically get turned into a link.

See also:

Call fragment from fragment

I think now Fragment nesting is available just update the back computability jar

now lets dig in the problem it self .

public void onClick2(View view) {
    Fragment2 fragment2 = new Fragment2();
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.fragment1, fragment2);
    fragmentTransaction.commit();
}

I think the R.id.fragment1 belongs to a TextView which is not a good place to include child views in because its not a ViewGroup, you can remove the textView from the xml and replace it with a LinearLayout lets say and it will work , if not tell me what the error .

fragment1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f0f0f0"
android:orientation="vertical" >

<LinearLayout 
    android:id="@+id/fragment1"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    />

<Button 
    android:id="@+id/btn_frag2"
    android:text="Call Fragment 2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
</LinearLayout>

Update for the error in the comment

public class Fragment1 extends Fragment implements OnClickListener{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment1, container, false);
((Button) v.findViewById(R.id.btn_frag2)).setOnClickListener(this);
    return v;
}

public void onClick(View view) {
    Fragment2 fragment2 = new Fragment2();
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction =        fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.container, fragment2);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
}

}

Cmake doesn't find Boost

I struggled with this problem for a while myself. It turned out that cmake was looking for Boost library files using Boost's naming convention, in which the library name is a function of the compiler version used to build it. Our Boost libraries were built using GCC 4.9.1, and that compiler version was in fact present on our system; however, GCC 4.4.7 also happened to be installed. As it happens, cmake's FindBoost.cmake script was auto-detecting the GCC 4.4.7 installation instead of the GCC 4.9.1 one, and thus was looking for Boost library files with "gcc44" in the file names, rather than "gcc49".

The simple fix was to force cmake to assume that GCC 4.9 was present, by setting Boost_COMPILER to "-gcc49" in CMakeLists.txt. With this change, FindBoost.cmake looked for, and found, my Boost library files.

HTML Form: Select-Option vs Datalist-Option

To specifically answer a part of your question "Is there any situation in which it would be better to use one or the other?", consider a form with repeating sections. If the repeating section contains many select tags, then the options must be rendered for each select, for every row.

In such a case, I would consider using datalist with input, because the same datalist can be used for any number of inputs. This could potentially save a large amount of rendering time on the server, and would scale much better to any number of rows.

Gradle failed to resolve library in Android Studio

You go File->Settings->Gradle Look at the "Offline work" inbox, if it's checked u uncheck and try to sync again I have the same problem and i try this , the problem resolved. Good luck !

Android WebView progress bar

It's true, there are also more complete option, like changing the name of the app for a sentence you want. Check this tutorial it can help:

http://www.firstdroid.com/2010/08/04/adding-progress-bar-on-webview-android-tutorials/

In that tutorial you have a complete example how to use the progressbar in a webview app.

Adrian.

Java ElasticSearch None of the configured nodes are available

I spend days together to figure out this issue. I know its late but this might be helpful:

I resolved this issue by changing the compatible/stable version of:

Spring boot: 2.1.1
Spring Data Elastic: 2.1.4
Elastic: 6.4.0 (default)

Maven:

<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>

<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
</dependency>

You don't need to mention Elastic version. By default it is 6.4.0. But if you want to add a specific verison. Use below snippet inside properties tag and use the compatible version of Spring Boot and Spring Data(if required)

<properties>
<elasticsearch.version>6.8.0</elasticsearch.version>
</properties>

Also, I used the Rest High Level client in ElasticConfiguration :

@Value("${elasticsearch.host}")
public String host;

@Value("${elasticsearch.port}")
public int port;

@Bean(destroyMethod = "close")
public RestHighLevelClient restClient1() {
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    RestClientBuilder builder = RestClient.builder(new HttpHost(host, port));
    RestHighLevelClient client = new RestHighLevelClient(builder);
    return client;
    }
}

Important Note: Elastic use 9300 port to communicate between nodes and 9200 as HTTP client. In application properties:

elasticsearch.host=10.40.43.111
elasticsearch.port=9200

spring.data.elasticsearch.cluster-nodes=10.40.43.111:9300 (customized Elastic server)
spring.data.elasticsearch.cluster-name=any-cluster-name (customized cluster name)

From Postman, you can use: http://10.40.43.111:9200/[indexname]/_search

Happy coding :)

MVC pattern on Android

MVC- Architecture on Android Its Better to Follow Any MVP instead MVC in android. But still according to the answer to the question this can be solution

Enter image description here

Description and Guidelines

     Controller -
        Activity can play the role.
        Use an application class to write the
        global methods and define, and avoid
        static variables in the controller label
    Model -
        Entity like - user, Product, and Customer class.
    View -
        XML layout files.
    ViewModel -
        Class with like CartItem and owner
        models with multiple class properties
    Service -
        DataService- All the tables which have logic
        to get the data to bind the models - UserTable,
        CustomerTable
        NetworkService - Service logic binds the
        logic with network call - Login Service
Helpers -
        StringHelper, ValidationHelper static
        methods for helping format and validation code.
SharedView - fragmets or shared views from the code
        can be separated here

AppConstant -
        Use the Values folder XML files
        for constant app level

NOTE 1:

Now here is the piece of magic you can do. Once you have classified the piece of code, write a base interface class like, IEntity and IService. Declare common methods. Now create the abstract class BaseService and declare your own set of methods and have separation of code.

NOTE 2: If your activity is presenting multiple models then rather than writing the code/logic in activity, it is better to divide the views in fragments. Then it's better. So in the future if any more model is needed to show up in the view, add one more fragment.

NOTE 3: Separation of code is very important. Every component in the architecture should be independent not having dependent logic. If by chance if you have something dependent logic, then write a mapping logic class in between. This will help you in the future.

How to specify names of columns for x and y when joining in dplyr?

This feature has been added in dplyr v0.3. You can now pass a named character vector to the by argument in left_join (and other joining functions) to specify which columns to join on in each data frame. With the example given in the original question, the code would be:

left_join(test_data, kantrowitz, by = c("first_name" = "name"))

Meaning of end='' in the statement print("\t",end='')?

The default value of end is \n meaning that after the print statement it will print a new line. So simply stated end is what you want to be printed after the print statement has been executed

Eg: - print ("hello",end=" +") will print hello +

How to print to stderr in Python?

For Python 2 my choice is: print >> sys.stderr, 'spam' Because you can simply print lists/dicts etc. without convert it to string. print >> sys.stderr, {'spam': 'spam'} instead of: sys.stderr.write(str({'spam': 'spam'}))