Programs & Examples On #Auto close

Autocomplete syntax for HTML or PHP in Notepad++. Not auto-close, autocompelete

In Notepad++ v. 6.4.1 is this possibility in:Settings->Preferences->Auto-Completion and there check Enable auto-completion on each input.

For auto-complete in code press Ctrl + Enter.

Group By Multiple Columns

C# 7.1 or greater using Tuples and Inferred tuple element names (currently it works only with linq to objects and it is not supported when expression trees are required e.g. someIQueryable.GroupBy(...). Github issue):

// declarative query syntax
var result = 
    from x in inMemoryTable
    group x by (x.Column1, x.Column2) into g
    select (g.Key.Column1, g.Key.Column2, QuantitySum: g.Sum(x => x.Quantity));

// or method syntax
var result2 = inMemoryTable.GroupBy(x => (x.Column1, x.Column2))
    .Select(g => (g.Key.Column1, g.Key.Column2, QuantitySum: g.Sum(x => x.Quantity)));

C# 3 or greater using anonymous types:

// declarative query syntax
var result3 = 
    from x in table
    group x by new { x.Column1, x.Column2 } into g
    select new { g.Key.Column1, g.Key.Column2, QuantitySum = g.Sum(x => x.Quantity) };

// or method syntax
var result4 = table.GroupBy(x => new { x.Column1, x.Column2 })
    .Select(g => 
      new { g.Key.Column1, g.Key.Column2 , QuantitySum= g.Sum(x => x.Quantity) });

What does "commercial use" exactly mean?

I suggest this discriminative question:

Is the open-source tool necessary in your process of making money?

  • a blog engine on your commercial web site is necessary: commercial use.
  • winamp for listening to music is not necessary: non-commercial use.

How can I convert integer into float in Java?

You shouldn't use float unless you have to. In 99% of cases, double is a better choice.

int x = 1111111111;
int y = 10000;
float f = (float) x / y;
double d = (double) x / y;
System.out.println("f= "+f);
System.out.println("d= "+d);

prints

f= 111111.12
d= 111111.1111

Following @Matt's comment.

float has very little precision (6-7 digits) and shows significant rounding error fairly easily. double has another 9 digits of accuracy. The cost of using double instead of float is notional in 99% of cases however the cost of a subtle bug due to rounding error is much higher. For this reason, many developers recommend not using floating point at all and strongly recommend BigDecimal.

However I find that double can be used in most cases provided sensible rounding is used.

In this case, int x has 32-bit precision whereas float has a 24-bit precision, even dividing by 1 could have a rounding error. double on the other hand has 53-bit of precision which is more than enough to get a reasonably accurate result.

How do you make an array of structs in C?

That error means that the compiler is not able to find the definition of the type of your struct before the declaration of the array of structs, since you're saying you have the definition of the struct in a header file and the error is in nbody.c then you should check if you're including correctly the header file. Check your #include's and make sure the definition of the struct is done before declaring any variable of that type.

Saving numpy array to txt file row wise

I found that the first solution in the accepted answer to be problematic for cases where the newline character is still required. The easiest solution to the problem was doing this:

numpy.savetxt(filename, [a], delimiter='\t')

Java Could not reserve enough space for object heap error

Double click Liferay CE Server -> add -XX:MaxHeapSize=512m to Memory args -> Start server! Enjoy...

It's work for me!

MySQL: ignore errors when importing?

Use the --force (-f) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.

For example:

mysql -u userName -p -f -D dbName < script.sql

Which are more performant, CTE or temporary tables?

I'd say they are different concepts but not too different to say "chalk and cheese".

  • A temp table is good for re-use or to perform multiple processing passes on a set of data.

  • A CTE can be used either to recurse or to simply improved readability.
    And, like a view or inline table valued function can also be treated like a macro to be expanded in the main query

  • A temp table is another table with some rules around scope

I have stored procs where I use both (and table variables too)

How to make the HTML link activated by clicking on the <li>?

Just add wrap the link text in a 'p' tag or something similar and add margin and padding to that element, this way it wont affect the settings that MiffTheFox gave you, i.e.

<li> <a href="#"> <p>Link Text </p> </a> </li>

C# : 'is' keyword and checking for Not

You can do it this way:

object a = new StreamWriter("c:\\temp\\test.txt");

if (a is TextReader == false)
{
   Console.WriteLine("failed");
}

What do I use on linux to make a python program executable

If you want to obtain a stand-alone binary application in Python try to use a tool like py2exe or PyInstaller.

Edit In Place Content Editing

I've modified your plunker to get it working via angular-xeditable:

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

It is common solution for inline editing - you creale hyperlinks with editable-text directive that toggles into <input type="text"> tag:

<a href="#" editable-text="bday.name" ng-click="myform.$show()" e-placeholder="Name">
    {{bday.name || 'empty'}}
</a>

For date I used editable-date directive that toggles into html5 <input type="date">.

C# naming convention for constants?

Actually, it is

private const int TheAnswer = 42;

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

How to create named and latest tag in Docker?

Once you have your image, you can use

$ docker tag <image> <newName>/<repoName>:<tagName>
  1. Build and tag the image with creack/node:latest

    $ ID=$(docker build -q -t creack/node .)
    
  2. Add a new tag

    $ docker tag $ID creack/node:0.10.24
    
  3. You can use this and skip the -t part from build

    $ docker tag $ID creack/node:latest
    

Angular: Cannot Get /

For me the issue was with @Component Selector path was pointing to wrong path. After changing it solved the issue.

@Component({
selector: 'app-fetch-data',
templateUrl: './fetch-data.component.html',
providers: [ToolbarService, GroupService, FilterService, PageService, ExcelExportService, PdfExportService]
})

ArrayAdapter in android to create simple listview

The TextView resource id it needs is for a TextView layout file, so it won't be in the same activity.

You can create it by going to File > New > XML > XML Layout File, and enter the widget type, which is 'TextView' in the root tag field.

Source: https://www.kompulsa.com/the-simplest-way-to-implement-an-android-listview/

How to paginate with Mongoose in Node.js?

After taking a closer look at the Mongoose API with the information provided by Rodolphe, I figured out this solution:

MyModel.find(query, fields, { skip: 10, limit: 5 }, function(err, results) { ... });

Java - Including variables within strings?

Since Java 15, you can use a non-static string method called String::formatted(Object... args)

Example:

String foo = "foo";
String bar = "bar";

String str = "First %s, then %s".formatted(foo, bar);     

Output:

"First foo, then bar"

What's the best way to get the last element of an array without deleting it?

I think this is a slight improvement on all the existing answers:

$lastElement = count($array) > 0 ? array_values(array_slice($array, -1))[0] : null;
  • Performs better than end() or solutions using array_keys(), especially with large arrays
  • Won't modify the array's internal pointer
  • Won't try to access an undefined offset for empty arrays
  • Will work as expected for empty arrays, indexed arrays, mixed arrays, and associative arrays

password for postgres

Set the default password in the .pgpass file. If the server does not save the password, it is because it is not set in the .pgpass file, or the permissions are open and the file is therefore ignored.

Read more about the password file here.

Also, be sure to check the permissions: on *nix systems the permissions on .pgpass must disallow any access to world or group; achieve this by the command chmod 0600 ~/.pgpass. If the permissions are less strict than this, the file will be ignored.

Have you tried logging-in using PGAdmin? You can save the password there, and modify the pgpass file.

Windows error 2 occured while loading the Java VM

I got the same problem after upgrading java from 1.8.0_202 to 1.8.0_211

Problem:

Here are directories where new version of 1.8.0_211 of Java installed:

Directory of c:\Program Files\Java\jre1.8.0_211\bin Directory of c:\Program Files (x86)\Common Files\Oracle\Java\javapath

So one is located in 32 bit and second is in 64 bit Program files folder. The one that is specified in the PATH is 32 bit version (c:\Program Files (x86)\Common Files\Oracle\Java\javapath), even though it was 64 bit version of the Java that was installed.

Solution:

Change system environments variable PATH from c:\Program Files (x86)\Common Files\Oracle\Java\javapath to c:\Program Files\Java\jre1.8.0_211\bin

How to get the correct range to set the value to a cell?

The following code does what is required

function doTest() {
  SpreadsheetApp.getActiveSheet().getRange('F2').setValue('Hello');
}

What is the official "preferred" way to install pip and virtualenv systemwide?

There is no preferred method - everything depends on your needs. Often you need to have different Python interpreters on the system for whatever reason. In this case you need to install the stuff individually for each interpreter. Apart from that: I prefer installing stuff myself instead of depending of pre-packaged stuff sometimes causing issues - but that's only one possible opionion.

How to redirect the output of a PowerShell to a file during its execution

If you want a straight redirect of all output to a file, try using *>>:

# You'll receive standard output for the first command, and an error from the second command.
mkdir c:\temp -force *>> c:\my.log ;
mkdir c:\temp *>> c:\my.log ;

Since this is a straight redirect to file, it won't output to the console (often helpful). If you desire the console output, combined all output with *&>1, and then pipe with Tee-Object:

mkdir c:\temp -force *>&1 | Tee-Object -Append -FilePath c:\my.log ;
mkdir c:\temp *>&1 | Tee-Object -Append -FilePath c:\my.log ;

# Shorter aliased version
mkdir c:\temp *>&1 | tee -Append c:\my.log ;

I believe these techniques are supported in PowerShell 3.0 or later; I'm testing on PowerShell 5.0.

How to cut an entire line in vim and paste it?

The quickest way I found is through editing mode:

  1. Press yy to copy the line.
  2. Then dd to delete the line.
  3. Then p to paste the line.

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

Well, I'm late.


In your image, the paper is white, while the background is colored. So, it's better to detect the paper is Saturation(???) channel in HSV color space. Take refer to wiki HSL_and_HSV first. Then I'll copy most idea from my answer in this Detect Colored Segment in an image.


Main steps:

  1. Read into BGR
  2. Convert the image from bgr to hsv space
  3. Threshold the S channel
  4. Then find the max external contour(or do Canny, or HoughLines as you like, I choose findContours), approx to get the corners.

This is my result:

enter image description here


The Python code(Python 3.5 + OpenCV 3.3):

#!/usr/bin/python3
# 2017.12.20 10:47:28 CST
# 2017.12.20 11:29:30 CST

import cv2
import numpy as np

##(1) read into  bgr-space
img = cv2.imread("test2.jpg")

##(2) convert to hsv-space, then split the channels
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h,s,v = cv2.split(hsv)

##(3) threshold the S channel using adaptive method(`THRESH_OTSU`) or fixed thresh
th, threshed = cv2.threshold(s, 50, 255, cv2.THRESH_BINARY_INV)

##(4) find all the external contours on the threshed S
#_, cnts, _ = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]

canvas  = img.copy()
#cv2.drawContours(canvas, cnts, -1, (0,255,0), 1)

## sort and choose the largest contour
cnts = sorted(cnts, key = cv2.contourArea)
cnt = cnts[-1]

## approx the contour, so the get the corner points
arclen = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.02* arclen, True)
cv2.drawContours(canvas, [cnt], -1, (255,0,0), 1, cv2.LINE_AA)
cv2.drawContours(canvas, [approx], -1, (0, 0, 255), 1, cv2.LINE_AA)

## Ok, you can see the result as tag(6)
cv2.imwrite("detected.png", canvas)

Related answers:

  1. How to detect colored patches in an image using OpenCV?
  2. Edge detection on colored background using OpenCV
  3. OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection
  4. How to use `cv2.findContours` in different OpenCV versions?

Can't subtract offset-naive and offset-aware datetimes

The correct solution is to add the timezone info e.g., to get the current time as an aware datetime object in Python 3:

from datetime import datetime, timezone

now = datetime.now(timezone.utc)

On older Python versions, you could define the utc tzinfo object yourself (example from datetime docs):

from datetime import tzinfo, timedelta, datetime

ZERO = timedelta(0)

class UTC(tzinfo):
  def utcoffset(self, dt):
    return ZERO
  def tzname(self, dt):
    return "UTC"
  def dst(self, dt):
    return ZERO

utc = UTC()

then:

now = datetime.now(utc)

Class 'App\Http\Controllers\DB' not found and I also cannot use a new Model

I like to do this witch i think is cleaner :

1 - Add the model to namespace:

use App\Employee;

2 - then you can do :

$employees = Employee::get();

or maybe somthing like this:

$employee = Employee::where('name', 'John')->first();

SQL Server: Query fast, but slow from procedure

I've got another idea. What if you create this table-based function:

CREATE FUNCTION tbfSelectFromView
(   
    -- Add the parameters for the function here
    @SessionGUID UNIQUEIDENTIFIER
)
RETURNS TABLE 
AS
RETURN 
(
    SELECT *
    FROM Report_Opener
    WHERE SessionGUID = @SessionGUID
    ORDER BY CurrencyTypeOrder, Rank
)
GO

And then selected from it using the following statement (even putting this in your SP):

SELECT *
FROM tbfSelectFromView(@SessionGUID)

It looks like what's happening (which everybody has already commented on) is that SQL Server just makes an assumption somewhere that's wrong, and maybe this will force it to correct the assumption. I hate to add the extra step, but I'm not sure what else might be causing it.

Set IDENTITY_INSERT ON is not working

In VB code, when trying to submit an INSERT query, you must submit a double query in the same 'executenonquery' like this:

sqlQuery = "SET IDENTITY_INSERT dbo.TheTable ON; INSERT INTO dbo.TheTable (Col1, COl2) VALUES (Val1, Val2); SET IDENTITY_INSERT dbo.TheTable OFF;"

I used a ; separator instead of a GO.

Works for me. Late but efficient!

How to retrieve the current version of a MySQL database management system (DBMS)?

For UBUNTU you can try the following command to check mysql version :

mysql --version

Can we instantiate an abstract class directly?

No, abstract class can never be instantiated.

Changing PowerShell's default output encoding to UTF-8

To be short, use:

write-output "your text" | out-file -append -encoding utf8 "filename"

Array and string offset access syntax with curly braces is deprecated

It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.

Let's say you have something like this in your code:

$str = "test";
echo($str{0});

since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:

$str = "test";
echo($str[0]);

Fixing the code in the question will look something like this:

public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
    $records = $this->listRecords($zoneID, $type, $name);
    if (isset($records->result[0]->id)) {
        return $records->result[0]->id;
    }
    return false;
}

Why does my Eclipse keep not responding?

If there is a project you earlier imported externally (outside of Workspace), that may cause this problem. If you can access Eclipse try to remove it. If you are getting the 'No responding at startup', then go delete the file at source.

This will solve the problem.

Border length smaller than div width?

You can use pseudoelements. E.g.

_x000D_
_x000D_
div {_x000D_
  width   : 200px;_x000D_
  height  : 50px;   _x000D_
  position: relative;_x000D_
  z-index : 1;_x000D_
  background: #eee;_x000D_
}_x000D_
_x000D_
div:before {_x000D_
  content : "";_x000D_
  position: absolute;_x000D_
  left    : 0;_x000D_
  bottom  : 0;_x000D_
  height  : 1px;_x000D_
  width   : 50%;  /* or 100px */_x000D_
  border-bottom:1px solid magenta;_x000D_
}
_x000D_
<div>Item 1</div>_x000D_
<div>Item 2</div>
_x000D_
_x000D_
_x000D_

No need to use extra markup for presentational purpose. :after is also supported from IE8.

edit:

if you need a right-aligned border, just change left: 0 with right: 0

if you need a center-aligned border just simply set left: 50px;

Moving all files from one directory to another using Python

import shutil 
import os 
import logging

source = '/var/spools/asterisk/monitor' 
dest1 = '/tmp/'


files = os.listdir(source)

for f in files:
        shutil.move(source+f, dest1)

logging.basicConfig(filename='app.log', filemode='w', format='%(name)s
- %(levelname)s - %(message)s')

logging.info('directories moved')

A little bit cooked code with log feature. You can also configure this to run at some period of time using crontab.

* */1 * * * python /home/yourprogram.py > /dev/null 2>&1

runs every hour! cheers

Java, How to add values to Array List used as value in HashMap

String courseID = "Comp-101";
List<String> scores = new ArrayList<String> ();
scores.add("100");
scores.add("90");
scores.add("80");
scores.add("97");

Map<String, ArrayList<String>> myMap = new HashMap<String, ArrayList<String>>();
myMap.put(courseID, scores);

Hope this helps!

Restful API service

I would highly recommend the REST client Retrofit.

I have found this well written blog post extremely helpful, it also contains simple example code. The author uses Retrofit to make the network calls and Otto to implement a data bus pattern:

http://www.mdswanson.com/blog/2014/04/07/durable-android-rest-clients.html

Oracle PL/SQL - How to create a simple array variable?

Another solution is to use an Oracle Collection as a Hashmap:

declare 
-- create a type for your "Array" - it can be of any kind, record might be useful
  type hash_map is table of varchar2(1000) index by varchar2(30);
  my_hmap hash_map ;
-- i will be your iterator: it must be of the index's type
  i varchar2(30);
begin
  my_hmap('a') := 'apple';
  my_hmap('b') := 'box';
  my_hmap('c') := 'crow';
-- then how you use it:

  dbms_output.put_line (my_hmap('c')) ;

-- or to loop on every element - it's a "collection"
  i := my_hmap.FIRST;

  while (i is not null)  loop     
    dbms_output.put_line(my_hmap(i));      
    i := my_hmap.NEXT(i);
  end loop;

end;

Upload DOC or PDF using PHP

You can use

$_FILES['filename']['error'];

If any type of error occurs then it returns 'error' else 1,2,3,4 or 1 if done

1 : if file size is over limit .... You can find other options by googling

bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date

I was using AngularJS and AngularStrap 2.3.7 and trying to catch the 'change' event by listening to a <form> element (not the input itself) and none of the answers here worked for me. I tried to do:

$(form).on('change change.dp dp.change changeDate' function () {...})

And nothing would fire. I ended up listening to the focus and blur events and setting a custom property before/after on the element itself:

// special hack to make bs-datepickers fire change events
// use timeout to make sure they all exist first
$timeout(function () {  
    $('input[bs-datepicker]').on('focus', function (e){
        e.currentTarget.focusValue = e.currentTarget.value;
    });        
    $('input[bs-datepicker]').on('blur', function (e){
        if (e.currentTarget.focusValue !== e.currentTarget.value) {
            var event = new Event('change', { bubbles: true });
            e.currentTarget.dispatchEvent(event);
        }
    });
})

This basically manually checks the value before and after the focus and blur and dispatches a new 'change' event. The { bubbles: true } bit is what got the form to detect the change. If you have any datepicker elements inside of an ng-if you'll need to wrap the listeners in a $timeout to make sure the digest happens first so all of your datepicker elements exist.

Hope this helps someone!

How to check if a value exists in an array in Ruby

if you don't want to use include? you can first wrap the element in an array and then check whether the wrapped element is equal to the intersection of the array and the wrapped element. This will return a boolean value based on equality.

def in_array?(array, item)
    item = [item] unless item.is_a?(Array)
    item == array & item
end

Check if all values of array are equal

arr.length && arr.reduce(function(a, b){return (a === b)?a:false;}) === arr[0];

Drop data frame columns by name

There is a potentially more powerful strategy based on the fact that grep() will return a numeric vector. If you have a long list of variables as I do in one of my dataset, some variables that end in ".A" and others that end in ".B" and you only want the ones that end in ".A" (along with all the variables that don't match either pattern, do this:

dfrm2 <- dfrm[ , -grep("\\.B$", names(dfrm)) ]

For the case at hand, using Joris Meys example, it might not be as compact, but it would be:

DF <- DF[, -grep( paste("^",drops,"$", sep="", collapse="|"), names(DF) )]

Remote origin already exists on 'git push' to a new repository

METHOD1->

Since origin already exist remove it.

git remote rm origin
git remote add origin https://github.com/USERNAME/REPOSITORY.git

METHOD2->

One can also change existing remote repository URL by ->git remote set-url

If you're updating to use HTTPS

git remote set-url origin https://github.com/USERNAME/REPOSITORY.git

If you're updating to use SSH

git remote set-url origin [email protected]:USERNAME/REPOSITORY.git

If trying to update a remote that doesn't exist you will receive a error. So be careful of that.

METHOD3->

Use the git remote rename command to rename an existing remote. An existing remote name, for example, origin.

git remote rename origin startpoint
# Change remote name from 'origin' to 'startpoint'

To verify remote's new name->

git remote -v

If new to Git try this tutorial->

TRY GIT TUTORIAL

Align DIV's to bottom or baseline

The answer posted by Y. Shoham (using absolute positioning) seems to be the simplest solution in most cases where the container is a fixed height, but if the parent DIV has to contain multiple DIVs and auto adjust it's height based on dynamic content, then there can be a problem. I needed to have two blocks of dynamic content; one aligned to the top of the container and one to the bottom and although I could get the container to adjust to the size of the top DIV, if the DIV aligned to the bottom was taller, it would not resize the container but would extend outside. The method outlined above by romiem using table style positioning, although a bit more complicated, is more robust in this respect and allowed alignment to the bottom and correct auto height of the container.

CSS

#container {
        display: table;
        height: auto;
}

#top {
    display: table-cell;
    width:50%;
    height: 100%;
}

#bottom {
    display: table-cell;
    width:50%;
    vertical-align: bottom;
    height: 100%;
}

HTML

<div id=“container”>
    <div id=“top”>Dynamic content aligned to top of #container</div>
    <div id=“bottom”>Dynamic content aligned to botttom of #container</div>
</div>

Example

I realise this is not a new answer but I wanted to comment on this approach as it lead me to find my solution but as a newbie I was not allowed to comment, only post.

Build a basic Python iterator

I see some of you doing return self in __iter__. I just wanted to note that __iter__ itself can be a generator (thus removing the need for __next__ and raising StopIteration exceptions)

class range:
  def __init__(self,a,b):
    self.a = a
    self.b = b
  def __iter__(self):
    i = self.a
    while i < self.b:
      yield i
      i+=1

Of course here one might as well directly make a generator, but for more complex classes it can be useful.

How to create war files

Simplistic Shell code for creating WAR files from a standard Eclipse dynamic Web Project. Uses RAM File system (/dev/shm) on a Linux platform.

#!/bin/sh

UTILITY=$(basename $0)

if [ -z "$1" ] ; then
    echo "usage: $UTILITY [-s] <web-app-directory>..."
    echo "       -s ..... With source"
    exit 1
fi

if [ "$1" == "-s" ] ; then
    WITH_SOURCE=1
    shift
fi

while [ ! -z "$1" ] ; do
    WEB_APP_DIR=$1

    shift

    if [ ! -d $WEB_APP_DIR ] ; then
        echo "\"$WEB_APP_DIR\" is not a directory"
        continue
    fi

    if [ ! -d $WEB_APP_DIR/WebContent ] ; then
        echo "\"$WEB_APP_DIR\" is not a Web Application directory"
        continue
    fi

    TMP_DIR=/dev/shm/${WEB_APP_DIR}.$$.tmp
    WAR_FILE=/dev/shm/${WEB_APP_DIR}.war

    mkdir $TMP_DIR

    pushd $WEB_APP_DIR > /dev/null
    cp -r WebContent/* $TMP_DIR
    cp -r build/* $TMP_DIR/WEB-INF
    [ ! -z "$WITH_SOURCE" ] && cp -r src/* $TMP_DIR/WEB-INF/classes
    cd $TMP_DIR > /dev/null
    [ -e $WAR_FILE ] && rm -f $WAR_FILE
    jar cf $WAR_FILE .
    ls -lsF $WAR_FILE
    popd > /dev/null

    rm -rf $TMP_DIR
done

How to parse a String containing XML in Java and retrieve the value of the root node?

You could also use tools provided by the base JRE:

String msg = "<message>HELLO!</message>";
DocumentBuilder newDocumentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document parse = newDocumentBuilder.parse(new ByteArrayInputStream(msg.getBytes()));
System.out.println(parse.getFirstChild().getTextContent());

How to check if an NSDictionary or NSMutableDictionary contains a key?

One very nasty gotcha which just wasted a bit of my time debugging - you may find yourself prompted by auto-complete to try using doesContain which seems to work.

Except, doesContain uses an id comparison instead of the hash comparison used by objectForKey so if you have a dictionary with string keys it will return NO to a doesContain.

NSMutableDictionary* keysByName = [[NSMutableDictionary alloc] init];
keysByName[@"fred"] = @1;
NSString* test = @"fred";

if ([keysByName objectForKey:test] != nil)
    NSLog(@"\nit works for key lookups");  // OK
else
    NSLog(@"\nsod it");

if (keysByName[test] != nil)
    NSLog(@"\nit works for key lookups using indexed syntax");  // OK
else
    NSLog(@"\nsod it");

if ([keysByName doesContain:@"fred"])
    NSLog(@"\n doesContain works literally");
else
    NSLog(@"\nsod it");  // this one fails because of id comparison used by doesContain

How do I uninstall nodejs installed from pkg (Mac OS X)?

Following previous posts, here is the full list I used

sudo npm uninstall npm -g
sudo rm -rf /usr/local/lib/node /usr/local/lib/node_modules /var/db/receipts/org.nodejs.*
sudo rm -rf /usr/local/include/node /Users/$USER/.npm
sudo rm /usr/local/bin/node
sudo rm /usr/local/share/man/man1/node.1
sudo rm /usr/local/lib/dtrace/node.d
brew install node

Java null check why use == instead of .equals()

Because equal is a function derived from Object class, this function compares items of the class. if you use it with null it will return false cause cause class content is not null. In addition == compares reference to an object.

Overlapping Views in Android

Visible gallery changes visibility which is how you get the gallery over other view overlap. the Home sample app has some good examples of this technique.

Difference between scaling horizontally and vertically for databases

Adding lots of load balancers creates extra overhead and latency and that is the drawback for scaling out horizontally in nosql databases. It is like the question why people say RPC is not recommended since it is not robust.

I think in a real system we should use both sql and nosql databases to utilize both multicore and cloud computing capabilities of today's systems.

On the other hand, complex transactional queries has high performance if sql databases such as oracle being used. NoSql could be used for bigdata and horizontal scalability by sharding.

Purge Kafka Topic

Following command can be used to delete all the existing messages in kafka topic:

kafka-delete-records --bootstrap-server <kafka_server:port> --offset-json-file delete.json

The structure of the delete.json file should be following:

{ "partitions": [ { "topic": "foo", "partition": 1, "offset": -1 } ], "version": 1 }

where offset :-1 will delete all the records (This command has been tested with kafka 2.0.1

jQuery onclick event for <li> tags

I'm not really sure what your question is, but to get the text of the li element you can use:

$(this).text();

And to get the id of an element you can use .attr('id');. Once you have a reference to the element you want (e.g. $(this)) you can perform any jQuery function on it.

How to fix Hibernate LazyInitializationException: failed to lazily initialize a collection of roles, could not initialize proxy - no Session

Adding following property to your persistence.xml may solve your problem temporarily

<property name="hibernate.enable_lazy_load_no_trans" value="true" />

As @vlad-mihalcea said it's an antipattern and does not solve lazy initialization issue completely, initialize your associations before closing transaction and use DTOs instead.

Animate visibility modes, GONE and VISIBLE

To animate layout changes, you can add the following attribute to your LinearLayout

android:animateLayoutChanges="true"

and it will animate changes automatically for you.


For information, if android:animateLayoutChanges="true" is used, then custom animation via anim xml will not work.

Is there a command to list all Unix group names?

If you want all groups known to the system, I would recommend using getent group instead of parsing /etc/group:

getent group

The reason is that on networked systems, groups may not only read from /etc/group file, but also obtained through LDAP or Yellow Pages (the list of known groups comes from the local group file plus groups received via LDAP or YP in these cases).

If you want just the group names you can use:

getent group | cut -d: -f1

Returning an array using C

Your method will return a local stack variable that will fail badly. To return an array, create one outside the function, pass it by address into the function, then modify it, or create an array on the heap and return that variable. Both will work, but the first doesn't require any dynamic memory allocation to get it working correctly.

void returnArray(int size, char *retArray)
{
  // work directly with retArray or memcpy into it from elsewhere like
  // memcpy(retArray, localArray, size); 
}

#define ARRAY_SIZE 20

int main(void)
{
  char foo[ARRAY_SIZE];
  returnArray(ARRAY_SIZE, foo);
}

Parsing HTML using Python

I recommend using justext library:

https://github.com/miso-belica/jusText

Usage: Python2:

import requests
import justext

response = requests.get("http://planet.python.org/")
paragraphs = justext.justext(response.content, justext.get_stoplist("English"))
for paragraph in paragraphs:
    print paragraph.text

Python3:

import requests
import justext

response = requests.get("http://bbc.com/")
paragraphs = justext.justext(response.content, justext.get_stoplist("English"))
for paragraph in paragraphs:
    print (paragraph.text)

CSS blur on background image but not on content

You could overlay one element above the blurred element like so

DEMO

div {
    position: absolute;
    left:0;
    top: 0;
}
p {
    position: absolute;
    left:0;
    top: 0;
}

Implement division with bit-wise operator

The standard way to do division is by implementing binary long-division. This involves subtraction, so as long as you don't discount this as not a bit-wise operation, then this is what you should do. (Note that you can of course implement subtraction, very tediously, using bitwise logical operations.)

In essence, if you're doing Q = N/D:

  1. Align the most-significant ones of N and D.
  2. Compute t = (N - D);.
  3. If (t >= 0), then set the least significant bit of Q to 1, and set N = t.
  4. Left-shift N by 1.
  5. Left-shift Q by 1.
  6. Go to step 2.

Loop for as many output bits (including fractional) as you require, then apply a final shift to undo what you did in Step 1.

jQuery - selecting elements from inside a element

....but $('span', $('#foo')); doesn't work?

This method is called as providing selector context.

In this you provide a second argument to the jQuery selector. It can be any css object string just like you would pass for direct selecting or a jQuery element.

eg.

$("span",".cont1").css("background", '#F00');

The above line will select all spans within the container having the class named cont1.

DEMO

How to make a website secured with https

What kind of business data? Trade secrets or just stuff that they don't want people to see but if it got out, it wouldn't be a big deal? If we are talking trade secrets, financial information, customer information and stuff that's generally confidential. Then don't even go down that route.

I'm wondering whether I need to use a secured connection (https) or just the forms authentication is enough.

Use a secure connection all the way.

Do I need to alter the code / Config

Yes. Well may be not. You may want to have an expert do this for you.

Is SSL and https one and the same...

Mostly yes. People usually refer to those things as the same thing.

Do I need to apply with someone to get some license or something.

You probably want to have your certificate signed by a certificate authority. It will cost you or your client a bit of money.

Do I need to make all my pages secured or only the login page...

Use https throughout. Performance is usually not an issue if the site is meant for internal users.

I was searching Internet for answer, but I was not able to get all these points... Any whitepaper or other references would also be helpful...

Start here for some pointers: http://www.owasp.org/index.php/Category:OWASP_Guide_Project

Note that SSL is a minuscule piece of making your web site secure once it is accessible from the internet. It does not prevent most sort of hacking.

'AND' vs '&&' as operator

Precedence differs between && and and (&& has higher precedence than and), something that causes confusion when combined with a ternary operator. For instance,

$predA && $predB ? "foo" : "bar"

will return a string whereas

$predA and $predB ? "foo" : "bar"

will return a boolean.

How can I get the current user directory?

you can use the following code:

if(Platform.Equals("WinCE"))
{
    m_CurrentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
}
else if(Platform.Equals("Win32NT"))
{
    m_CurrentPath = Directory.GetCurrentDirectory();
}

more information see: Get Current Directory Path in both WinXP and WinCE with C#

How do I get the MAX row with a GROUP BY in LINQ query?

The answers are OK if you only require those two fields, but for a more complex object, maybe this approach could be useful:

from x in db.Serials 
group x by x.Serial_Number into g 
orderby g.Key 
select g.OrderByDescending(z => z.uid)
.FirstOrDefault()

... this will avoid the "select new"

How to check if directory exists in %PATH%?

I took your implementation using the for loop and extended it into something that iterates through all elements of the path. Each iteration of the for loop removes the first element of the path (%p) from the entire path (held in %q and %r).

@echo off
SET MYPATHCOPY=%PATH%

:search
for /f "delims=; tokens=1,2*" %%p in ("%MYPATHCOPY%") do (
   @echo %%~p
   SET MYPATHCOPY=%%~q;%%~r
)

if "%MYPATHCOPY%"==";" goto done;
goto search;

:done

Sample output:

Z:\>path.bat
C:\Program Files\Microsoft DirectX SDK (November 2007)\Utilities\Bin\x86
c:\program files\imagemagick-6.3.4-q16
C:\WINDOWS\system32
C:\WINDOWS
C:\SFU\common\
c:\Program Files\Debugging Tools for Windows
C:\Program Files\Nmap

Preserve Line Breaks From TextArea When Writing To MySQL

Two solutions for this:

  1. PHP function nl2br():

    e.g.,

    echo nl2br("This\r\nis\n\ra\nstring\r");
    
    // will output
    This<br />
    is<br />
    a<br />
    string<br />
    
  2. Wrap the input in <pre></pre> tags.

    See: W3C Wiki - HTML/Elements/pre

What is the difference between a candidate key and a primary key?

Primary key -> Any column or set of columns that can uniquely identify a record in the table is a primary key. (There can be only one Primary key in the table)

Candidate key -> Any column or set of columns that are candidate to become primary key are Candidate key. (There can be one or more candidate key(s) in the table, if there is only one candidate key, it can be chosen as Primary key)

TestNG ERROR Cannot find class in classpath

If none of the above answers work, you can run the test in IDE, get the class path and use it in your command. Ex: If you are using Intellij IDEA, you can find it at the top of the console(screenshot below). Intellij Console

Clicking on the highlighted part expands and displays the complete class path.

you need to remove the references to jars inside the folder: JetBrains\IntelliJ IDEA Community Edition VERSION

java -cp "path_copied" org.testng.TestNG testng.xml

If the project is a Maven project, you can add maven surefire plugin and provide testng suite XML file path, navigate to the project directory and run the command: mvn clean install test

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.12</version>
                <configuration>
                    <suiteXmlFiles>
                        <suiteXmlFile>config/testrun_config.xml</suiteXmlFile>
                    </suiteXmlFiles>
                </configuration>
            </plugin>

How do I add an element to array in reducer of React native redux?

Two different options to add item to an array without mutation

case ADD_ITEM :
    return { 
        ...state,
        arr: [...state.arr, action.newItem]
    }

OR

case ADD_ITEM :
    return { 
        ...state,
        arr: state.arr.concat(action.newItem)
    }

How to include multiple js files using jQuery $.getScript() method

Load the following up needed script in the callback of the previous one like:

$.getScript('scripta.js', function()
{
   $.getScript('scriptb.js', function()
   {
       // run script that depends on scripta.js and scriptb.js
   });
});

How to refresh page on back button click?

I found two ways to handle this. Choose the best for your case. Solutions tested on Firefox 53 and Safari 10.1

1. Detect if user is using the back/foreward button, then reload whole page

if (!!window.performance && window.performance.navigation.type === 2) {
            // value 2 means "The page was accessed by navigating into the history"
            console.log('Reloading');
            window.location.reload(); // reload whole page

        }

2. reload whole page if page is cached

window.onpageshow = function (event) {
        if (event.persisted) {
            window.location.reload();
        }
    };

Good way to encapsulate Integer.parseInt()

If you're using Java 8 or up, you can use a library I just released: https://github.com/robtimus/try-parse. It has support for int, long and boolean that doesn't rely on catching exceptions. Unlike Guava's Ints.tryParse it returns OptionalInt / OptionalLong / Optional, much like in https://stackoverflow.com/a/38451745/1180351 but more efficient.

Unable to find a @SpringBootConfiguration when doing a JpaTest

I think that the best solution for this issue is to align your tests folders structure with the application folder structure.

I had the same issue which was caused by duplicating my project from a different folder structure project.

if your test project and your application project will have the same structure you will not be required to add any special annotations to your tests classes and everything will work as is.

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

I often use an extenstion method based on another version I found here (see Replacing characters in C# (ascii)) A quick explanation:

  • Normalizing to form D splits charactes like è to an e and a nonspacing `
  • From this, the nospacing characters are removed
  • The result is normalized back to form C (I'm not sure if this is neccesary)

Code:

using System.Linq;
using System.Text;
using System.Globalization;

// namespace here
public static class Utility
{
    public static string RemoveDiacritics(this string str)
    {
        if (null == str) return null;
        var chars =
            from c in str.Normalize(NormalizationForm.FormD).ToCharArray()
            let uc = CharUnicodeInfo.GetUnicodeCategory(c)
            where uc != UnicodeCategory.NonSpacingMark
            select c;

        var cleanStr = new string(chars.ToArray()).Normalize(NormalizationForm.FormC);

        return cleanStr;
    }

    // or, alternatively
    public static string RemoveDiacritics2(this string str)
    {
        if (null == str) return null;
        var chars = str
            .Normalize(NormalizationForm.FormD)
            .ToCharArray()
            .Where(c=> CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
            .ToArray();

        return new string(chars).Normalize(NormalizationForm.FormC);
    }
}

Validating parameters to a Bash script

one liner Bash argument validation, with and without directory validation

Here are some methods that have worked for me. You can use them in either the global script namespace (if in the global namespace, you can't reference the function builtin variables)

quick and dirty one liner

: ${1?' You forgot to supply a directory name'}

output:

./my_script: line 279: 1: You forgot to supply a directory name

Fancier - supply function name and usage

${1? ERROR Function: ${FUNCNAME[0]}() Usage: " ${FUNCNAME[0]} directory_name"}

output:

./my_script: line 288: 1:  ERROR Function: deleteFolders() Usage:  deleteFolders directory_name

Add complex validation logic without cluttering your current function

Add the following line within the function or script that receives the argument.

: ${1?'forgot to supply a directory name'} && validate $1 || die 'Please supply a valid directory'

You can then create a validation function that does something like

validate() {

    #validate input and  & return 1 if failed, 0 if succeed
    if [[ ! -d "$1" ]]; then
        return 1
    fi
}

and a die function that aborts the script on failure

die() { echo "$*" 1>&2 ; exit 1; }

For additional arguments, just add an additional line, replicating the format.

: ${1?' You forgot to supply the first argument'}
: ${2?' You forgot to supply the second argument'}

How to add a hook to the application context initialization event?

Create your annotation

  @Retention(RetentionPolicy.RUNTIME)
    public @interface AfterSpringLoadComplete {
    }

Create class

    public class PostProxyInvokerContextListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    ConfigurableListableBeanFactory factory;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext context = event.getApplicationContext();
        String[] names = context.getBeanDefinitionNames();
        for (String name : names) {
            try {
                BeanDefinition definition = factory.getBeanDefinition(name);
                String originalClassName = definition.getBeanClassName();
                Class<?> originalClass = Class.forName(originalClassName);
                Method[] methods = originalClass.getMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(AfterSpringLoadComplete.class)){
                        Object bean = context.getBean(name);
                        Method currentMethod = bean.getClass().getMethod(method.getName(), method.getParameterTypes());
                        currentMethod.invoke(bean);
                    }
                }
            } catch (Exception ignored) {
            }
        }
    }
}

Register this class by @Component annotation or in xml

<bean class="ua.adeptius.PostProxyInvokerContextListener"/>

and use annotation where you wan on any method that you want to run after context initialized, like:

   @AfterSpringLoadComplete
    public void init() {}

How do I select an element that has a certain class?

The element.class selector is for styling situations such as this:

<span class="large"> </span>
<p class="large"> </p>

.large {
    font-size:150%; font-weight:bold;
}

p.large {
    color:blue;
}

Both your span and p will be assigned the font-size and font-weight from .large, but the color blue will only be assigned to p.

As others have pointed out, what you're working with is descendant selectors.

Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp()

add async in main()

and await before

follow my code

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  var fsconnect = FirebaseFirestore.instance;

  myget() async {
    var d = await fsconnect.collection("students").get();
    // print(d.docs[0].data());

    for (var i in d.docs) {
      print(i.data());
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(
        title: Text('Firebase Firestore App'),
      ),
      body: Column(
        children: <Widget>[
          RaisedButton(
            child: Text('send data'),
            onPressed: () {
              fsconnect.collection("students").add({
                'name': 'sarah',
                'title': 'xyz',
                'email': '[email protected]',
              });
              print("send ..");
            },
          ),
          RaisedButton(
            child: Text('get data'),
            onPressed: () {
              myget();
              print("get data ...");
            },
          )
        ],
      ),
    ));
  }
}

Need to remove href values when printing in Chrome

For normal users. Open the inspect window of current page. And type in:

l = document.getElementsByTagName("a");
for (var i =0; i<l.length; i++) {
    l[i].href = "";
}

Then you shall not see the url links in print preview.

JQuery get data from JSON array

try this

$.getJSON(url, function(data){
    $.each(data.response.venue.tips.groups.items, function (index, value) {
        console.log(this.text);
    });
});

Retrieving the first digit of a number

    int number = 534;
    int firstDigit = Integer.parseInt(Integer.toString(number).substring(0, 1));

MVC ajax json post to controller action method

Below is how I got this working.

The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.

[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]

[HttpPost]  
  public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)  
  {            
     var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
     return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
  }

The JQuery script used to call this action method:

var requestData = {
         InvoiceNumber: $.trim(this.value),
         SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
      };


      $.ajax({
         url: '/en/myController/GetDataForInvoiceNumber',
         type: 'POST',
         data: JSON.stringify(requestData),
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',
         error: function (xhr) {
            alert('Error: ' + xhr.statusText);
         },
         success: function (result) {
            CheckIfInvoiceFound(result);
         },
         async: true,
         processData: false
      });

Xcode: failed to get the task for process

Having the developer code signing id is correct for sure, but also make sure you device is added to the Member Center via organizer, or through the developer portal.

A few days ago I reset my device list, and today I was suddenly getting this for an iPod I debug with all the time. About 15 mins later I realized the problem.

How do I set log4j level on the command line?

As part of your jvm arguments you can set -Dlog4j.configuration=file:"<FILE_PATH>". Where FILE_PATH is the path of your log4j.properties file.

Please note that as of log4j2, the new system variable to use is log4j.configurationFile and you put in the actual path to the file (i.e. without the file: prefix) and it will automatically load the factory based on the extension of the configuration file:

-Dlog4j.configurationFile=/path/to/log4jconfig.{ext}

multiple ways of calling parent method in php

There are three scenarios (that I can think of) where you would call a method in a subclass where the method exits in the parent class:

  1. Method is not overwritten by subclass, only exists in parent.

    This is the same as your example, and generally it's better to use $this -> get_species(); You are right that in this case the two are effectively the same, but the method has been inherited by the subclass, so there is no reason to differentiate. By using $this you stay consistent between inherited methods and locally declared methods.

  2. Method is overwritten by the subclass and has totally unique logic from the parent.

    In this case, you would obviously want to use $this -> get_species(); because you don't want the parent's version of the method executed. Again, by consistently using $this, you don't need to worry about the distinction between this case and the first.

  3. Method extends parent class, adding on to what the parent method achieves.

    In this case, you still want to use `$this -> get_species(); when calling the method from other methods of the subclass. The one place you will call the parent method would be from the method that is overwriting the parent method. Example:

    abstract class Animal {
    
        function get_species() {
    
            echo "I am an animal.";
    
        }
    
     }
    
     class Dog extends Animal {
    
         function __construct(){
    
             $this->get_species();
         }
    
         function get_species(){
    
             parent::get_species();
             echo "More specifically, I am a dog.";
         }
    }
    

The only scenario I can imagine where you would need to call the parent method directly outside of the overriding method would be if they did two different things and you knew you needed the parent's version of the method, not the local. This shouldn't be the case, but if it did present itself, the clean way to approach this would be to create a new method with a name like get_parentSpecies() where all it does is call the parent method:

function get_parentSpecies(){

     parent::get_species();
}

Again, this keeps everything nice and consistent, allowing for changes/modifications to the local method rather than relying on the parent method.

Getting request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

Basically, to make a cross domain AJAX requests, the requested server should allow the cross origin sharing of resources (CORS). You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/

In your scenario, you are setting the headers in the client which in fact needs to be set into http://localhost:8080/app server side code.

If you are using PHP Apache server, then you will need to add following in your .htaccess file:

Header set Access-Control-Allow-Origin "*"

Convert a video to MP4 (H.264/AAC) with ffmpeg

You can also try adding the Motumedia PPA to your apt sources and update your ffmpeg packages.

How to change Status Bar text color in iOS

Change in info PLIST In Swift 3 is very easy just with 2 steps. Go to your info.plist and change the key View controller-based status bar appearance to "NO". Then in the Appdelegate just add this line in didfinishlaunchingwithoptions method

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        UIApplication.shared.statusBarStyle = .lightContent
        return true
    }

this has been deprecated in iOS9 now you should do override this property in the rootviewcontroller

doing this has been deprecated in iOS 9 should do this on the rootviewcontroller

override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
 }

NULL vs nullptr (Why was it replaced?)

nullptr is always a pointer type. 0 (aka. C's NULL bridged over into C++) could cause ambiguity in overloaded function resolution, among other things:

f(int);
f(foo *);

Recursively list files in Java

I would go with something like:

public void list(File file) {
    System.out.println(file.getName());
    File[] children = file.listFiles();
    for (File child : children) {
        list(child);
    }
}

The System.out.println is just there to indicate to do something with the file. there is no need to differentiate between files and directories, since a normal file will simply have zero children.

How to make my font bold using css?

You could use a couple approaches. First would be to use the strong tag

Here is an <strong>example of that tag</strong>.

Another approach would be to use the font-weight property. You can achieve inline, or via a class or id. Let's say you're using a class.

.className {
  font-weight: bold;
}

Alternatively, you can also use a hard value for font-weight and most fonts support a value between 300 and 700, incremented by 100. For example, the following would be bold:

.className {
  font-weight: 700;
}

Create listview in fragment android

The inflate() method takes three parameters:

  1. The id of a layout XML file (inside R.layout),
  2. A parent ViewGroup into which the fragment's View is to be inserted,

  3. A third boolean telling whether the fragment's View as inflated from the layout XML file should be inserted into the parent ViewGroup.

In this case we pass false because the View will be attached to the parent ViewGroup elsewhere, by some of the Android code we call (in other words, behind our backs). When you pass false as last parameter to inflate(), the parent ViewGroup is still used for layout calculations of the inflated View, so you cannot pass null as parent ViewGroup .

 View rootView = inflater.inflate(R.layout.fragment_photos, container, false);

So, You need to call rootView in here

ListView lv = (ListView)rootView.findViewById(R.id.lv_contact);

How can I view an object with an alert()

Try this:

alert(JSON.parse(product) );

Return char[]/string from a function

you can use a static array in your method, to avoid lose of your array when your function ends :

char * createStr() 
{
    char char1= 'm';
    char char2= 'y';

    static char str[3];  
    str[0] = char1;
    str[1] = char2;
    str[2] = '\0';

    return str;
}

Edit : As Toby Speight mentioned this approach is not thread safe, and also recalling the function leads to data overwrite that is unwanted in some applications. So you have to save the data in a buffer as soon as you return back from the function. (However because it is not thread safe method, concurrent calls could still make problem in some cases, and to prevent this you have to use lock. capture it when entering the function and release it after copy is done, i prefer not to use this approach because its messy and error prone.)

Get a list of checked checkboxes in a div using jQuery

If you need to get quantity of selected checkboxes:

var selected = []; // initialize array
    $('div#checkboxes input[type=checkbox]').each(function() {
       if ($(this).is(":checked")) {
           selected.push($(this));
       }
    });
var selectedQuantity = selected.length;

How do you view ALL text from an ntext or nvarchar(max) in SSMS?

I have written an add-in for SSMS and this problem is fixed there. You can use one of 2 ways:

you can use "Copy current cell 1:1" to copy original cell data to clipboard:

http://www.ssmsboost.com/Features/ssms-add-in-copy-results-grid-cell-contents-line-with-breaksCopy original cell contents

Or, alternatively, you can open cell contents in external text editor (notepad++ or notepad) using "Cell visualizers" feature: http://www.ssmsboost.com/Features/ssms-add-in-results-grid-visualizers

(feature allows to open contents of field in any external application, so if you know that it is text - you use text editor to open it. If contents is binary data with picture - you select view as picture. Sample below shows opening a picture):SSMS Results grid visualizers

How can I use Timer (formerly NSTimer) in Swift?

SimpleTimer (Swift 3.1)

Why?

This is a simple timer class in swift that enables you to:

  • Local scoped timer
  • Chainable
  • One liners
  • Use regular callbacks

Usage:

SimpleTimer(interval: 3,repeats: true){print("tick")}.start()//Ticks every 3 secs

Code:

class SimpleTimer {/*<--was named Timer, but since swift 3, NSTimer is now Timer*/
    typealias Tick = ()->Void
    var timer:Timer?
    var interval:TimeInterval /*in seconds*/
    var repeats:Bool
    var tick:Tick

    init( interval:TimeInterval, repeats:Bool = false, onTick:@escaping Tick){
        self.interval = interval
        self.repeats = repeats
        self.tick = onTick
    }
    func start(){
        timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(update), userInfo: nil, repeats: true)//swift 3 upgrade
    }
    func stop(){
        if(timer != nil){timer!.invalidate()}
    }
    /**
     * This method must be in the public or scope
     */
    @objc func update() {
        tick()
    }
}

Send POST data on redirect with JavaScript/jQuery?

Here is a method, which does not use jQuery. I used it to create a bookmarklet, which checks the current page on w3-html-validator.

var f = document.createElement('form');
f.action='http://validator.w3.org/check';
f.method='POST';
f.target='_blank';

var i=document.createElement('input');
i.type='hidden';
i.name='fragment';
i.value='<!DOCTYPE html>'+document.documentElement.outerHTML;
f.appendChild(i);

document.body.appendChild(f);
f.submit();

fatal: Not a valid object name: 'master'

You need to commit at least one time on master before creating a new branch.

Find text string using jQuery?

Normally jQuery selectors do not search within the "text nodes" in the DOM. However if you use the .contents() function, text nodes will be included, then you can use the nodeType property to filter only the text nodes, and the nodeValue property to search the text string.

    $('*', 'body')
        .andSelf()
        .contents()
        .filter(function(){
            return this.nodeType === 3;
        })
        .filter(function(){
            // Only match when contains 'simple string' anywhere in the text
            return this.nodeValue.indexOf('simple string') != -1;
        })
        .each(function(){
            // Do something with this.nodeValue
        });

Maven Modules + Building a Single Specific Module

Say Parent pom.xml contains 6 modules and you want to run A, B and F.

<modules>
        <module>A</module>
        <module>B</module>
        <module>C</module>
        <module>D</module>
        <module>E</module>
        <module>F</module>
  </modules>

1- cd into parent project

 mvn --projects A,B,F --also-make clean install

OR

mvn -pl A,B,F -am clean install

OR

mvn -pl A,B,F -amd clean install

Note: When you specify a project with the -am option, Maven will build all of the projects that the specified project depends upon (either directly or indirectly). Maven will examine the list of projects and walk down the dependency tree, finding all of the projects that it needs to build.

While the -am command makes all of the projects required by a particular project in a multi-module build, the -amd or --also-make-dependents option configures Maven to build a project and any project that depends on that project. When using --also-make-dependents, Maven will examine all of the projects in our reactor to find projects that depend on a particular project. It will automatically build those projects and nothing else.

How to display svg icons(.svg files) in UI using React Component?

You can directly use .svg extension with img tag if the image is remotely hosted.

ReactDOM.render(
  <img src={"http://s.cdpn.io/3/kiwi.svg"}/>,
  document.getElementById('root')
);

Here is the fiddle: http://codepen.io/srinivasdamam-1471688843/pen/ZLNYdy?editors=0110

Note: If you are using any web app bundlers (like Webpack) you need to have related file loader.

Bootstrap Carousel Full Screen

You can do it without forcing html and body to me 100% height. Use view port height instead. And with mouse wheel control too.

_x000D_
_x000D_
function debounce(func, wait, immediate) {_x000D_
  var timeout;_x000D_
  return function() {_x000D_
    var context = this,_x000D_
      args = arguments;_x000D_
    var later = function() {_x000D_
      timeout = null;_x000D_
      if (!immediate) func.apply(context, args);_x000D_
    };_x000D_
    var callNow = immediate && !timeout;_x000D_
    clearTimeout(timeout);_x000D_
    timeout = setTimeout(later, wait);_x000D_
    if (callNow) func.apply(context, args);_x000D_
  };_x000D_
}_x000D_
_x000D_
var slider = document.getElementById("demo");_x000D_
var onScroll = debounce(function(direction) {_x000D_
  //console.log(direction);_x000D_
  if (direction == false) {_x000D_
   $('.carousel-control-next').click();_x000D_
  } else {_x000D_
   $('.carousel-control-prev').click();_x000D_
  }_x000D_
}, 100, true);_x000D_
_x000D_
slider.addEventListener("wheel", function(e) {_x000D_
  e.preventDefault();_x000D_
  var delta;_x000D_
  if (event.wheelDelta) {_x000D_
    delta = event.wheelDelta;_x000D_
  } else {_x000D_
    delta = -1 * event.deltaY;_x000D_
  }_x000D_
_x000D_
  onScroll(delta >= 0);_x000D_
});
_x000D_
.carousel-item {_x000D_
  height: 100vh;_x000D_
  background: #212121;_x000D_
}_x000D_
_x000D_
.carousel-control-next,_x000D_
.carousel-control-prev {_x000D_
  width: 8% !important;_x000D_
}_x000D_
_x000D_
.carousel-item.active,_x000D_
.carousel-item-left,_x000D_
.carousel-item-right {_x000D_
  display: flex !important;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
}_x000D_
_x000D_
.carousel-item h1 {_x000D_
    color: #fff;_x000D_
    font-size: 72px;_x000D_
    padding: 0 10%;_x000D_
 }
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<div id="demo" class="carousel slide" data-ride="carousel" data-interval="false">_x000D_
_x000D_
  <!-- The slideshow -->_x000D_
  <div class="carousel-inner">_x000D_
    <div class="carousel-item active">_x000D_
      <h1 class="display-1 text-center">Lorem ipsum dolor sit amet adipisicing</h1>_x000D_
    </div>_x000D_
    <div class="carousel-item">_x000D_
      <h1 class="display-1 text-center">Inventore omnis odio, dolore culpa atque?</h1>_x000D_
    </div>_x000D_
    <div class="carousel-item">_x000D_
     <h1 class="display-1 text-center">Lorem ipsum dolor sit</h1>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <!-- Left and right controls -->_x000D_
  <a class="carousel-control-prev" href="#demo" data-slide="prev">_x000D_
    <span class="carousel-control-prev-icon"></span>_x000D_
  </a>_x000D_
  <a class="carousel-control-next" href="#demo" data-slide="next">_x000D_
    <span class="carousel-control-next-icon"></span>_x000D_
  </a>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to add additional fields to form before submit?

May be useful for some:

(a function that allow you to add the data to the form using an object, with override for existing inputs, if there is) [pure js]

(form is a dom el, and not a jquery object [jqryobj.get(0) if you need])

function addDataToForm(form, data) {
    if(typeof form === 'string') {
        if(form[0] === '#') form = form.slice(1);
        form = document.getElementById(form);
    }

    var keys = Object.keys(data);
    var name;
    var value;
    var input;

    for (var i = 0; i < keys.length; i++) {
        name = keys[i];
        // removing the inputs with the name if already exists [overide]
        // console.log(form);
        Array.prototype.forEach.call(form.elements, function (inpt) {
             if(inpt.name === name) {
                 inpt.parentNode.removeChild(inpt);
             }
        });

        value = data[name];
        input = document.createElement('input');
        input.setAttribute('name', name);
        input.setAttribute('value', value);
        input.setAttribute('type', 'hidden');

        form.appendChild(input);
    }

    return form;
}

Use :

addDataToForm(form, {
    'uri': window.location.href,
     'kpi_val': 150,
     //...
});

you can use it like that too

var form = addDataToForm('myFormId', {
    'uri': window.location.href,
     'kpi_val': 150,
     //...
});

you can add # if you like too ("#myformid").

How to use fetch in typescript

If you take a look at @types/node-fetch you will see the body definition

export class Body {
    bodyUsed: boolean;
    body: NodeJS.ReadableStream;
    json(): Promise<any>;
    json<T>(): Promise<T>;
    text(): Promise<string>;
    buffer(): Promise<Buffer>;
}

That means that you could use generics in order to achieve what you want. I didn't test this code, but it would looks something like this:

import { Actor } from './models/actor';

fetch(`http://swapi.co/api/people/1/`)
      .then(res => res.json<Actor>())
      .then(res => {
          let b:Actor = res;
      });

MySQL my.cnf performance tuning recommendations

Try starting with the Percona wizard and comparing their recommendations against your current settings one by one. Don't worry there aren't as many applicable settings as you might think.

https://tools.percona.com/wizard

Update circa 2020: Sorry, this tool reached it's end of life: https://www.percona.com/blog/2019/04/22/end-of-life-query-analyzer-and-mysql-configuration-generator/

Everyone points to key_buffer_size first which you have addressed. With 96GB memory I'd be wary of any tiny default value (likely to be only 96M!).

Create a data.frame with m columns and 2 rows

For completeness:

Along the lines of Chase's answer, I usually use as.data.frame to coerce the matrix to a data.frame:

m <- as.data.frame(matrix(0, ncol = 30, nrow = 2))

EDIT: speed test data.frame vs. as.data.frame

system.time(replicate(10000, data.frame(matrix(0, ncol = 30, nrow = 2))))
   user  system elapsed 
  8.005   0.108   8.165 

system.time(replicate(10000, as.data.frame(matrix(0, ncol = 30, nrow = 2))))
   user  system elapsed 
  3.759   0.048   3.802 

Yes, it appears to be faster (by about 2 times).

How do I join two lists in Java?

Probably not simpler, but intriguing and ugly:

List<String> newList = new ArrayList<String>() { { addAll(listOne); addAll(listTwo); } };

Don't use it in production code... ;)

Format / Suppress Scientific Notation from Python Pandas Aggregation Results

Here is another way of doing it, similar to Dan Allan's answer but without the lambda function:

>>> pd.options.display.float_format = '{:.2f}'.format
>>> Series(np.random.randn(3))
0    0.41
1    0.99
2    0.10

or

>>> pd.set_option('display.float_format', '{:.2f}'.format)

Get int from String, also containing letters, in Java

Replace all non-digit with blank: the remaining string contains only digits.

Integer.parseInt(s.replaceAll("[\\D]", ""))

This will also remove non-digits inbetween digits, so "x1x1x" becomes 11.

If you need to confirm that the string consists of a sequence of digits (at least one) possibly followed a letter, then use this:

s.matches("[\\d]+[A-Za-z]?")

Altering column size in SQL Server

ALTER TABLE [Employee]
ALTER COLUMN [Salary] NUMERIC(22,5) NOT NULL

How to set URL query params in Vue with Vue-Router

Here is the example in docs:

// with query, resulting in /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})

Ref: https://router.vuejs.org/en/essentials/navigation.html

As mentioned in those docs, router.replace works like router.push

So, you seem to have it right in your sample code in question. But I think you may need to include either name or path parameter also, so that the router has some route to navigate to. Without a name or path, it does not look very meaningful.

This is my current understanding now:

  • query is optional for router - some additional info for the component to construct the view
  • name or path is mandatory - it decides what component to show in your <router-view>.

That might be the missing thing in your sample code.

EDIT: Additional details after comments

Have you tried using named routes in this case? You have dynamic routes, and it is easier to provide params and query separately:

routes: [
    { name: 'user-view', path: '/user/:id', component: UserView },
    // other routes
]

and then in your methods:

this.$router.replace({ name: "user-view", params: {id:"123"}, query: {q1: "q1"} })

Technically there is no difference between the above and this.$router.replace({path: "/user/123", query:{q1: "q1"}}), but it is easier to supply dynamic params on named routes than composing the route string. But in either cases, query params should be taken into account. In either case, I couldn't find anything wrong with the way query params are handled.

After you are inside the route, you can fetch your dynamic params as this.$route.params.id and your query params as this.$route.query.q1.

jQuery UI themes and HTML tables

Why noy just use the theme styles in the table? i.e.

<table>
  <thead class="ui-widget-header">
    <tr>
      <th>Id</th>
      <th>Description</th>
    </td>
  </thead>
  <tbody class="ui-widget-content">
    <tr>
      <td>...</td>
      <td>...</td>
    </tr>
      .
      .
      .
  </tbody>
</table>

And you don't need to use any code...

How to pass integer from one Activity to another?

In Sender Activity Side:

Intent passIntent = new Intent(getApplicationContext(), "ActivityName".class);
passIntent.putExtra("value", integerValue);
startActivity(passIntent);

In Receiver Activity Side:

int receiveValue = getIntent().getIntExtra("value", 0);

Accessing a property in a parent Component

You could:

  • Define a userStatus parameter for the child component and provide the value when using this component from the parent:

    @Component({
      (...)
    })
    export class Profile implements OnInit {
      @Input()
      userStatus:UserStatus;
    
      (...)
    }
    

    and in the parent:

    <profile [userStatus]="userStatus"></profile>
    
  • Inject the parent into the child component:

    @Component({
      (...)
    })
    export class Profile implements OnInit {
      constructor(app:App) {
        this.userStatus = app.userStatus;
      }
    
      (...)
    }
    

    Be careful about cyclic dependencies between them.

how to clear localstorage,sessionStorage and cookies in javascript? and then retrieve?

how to completely clear localstorage

localStorage.clear();

how to completely clear sessionstorage

sessionStorage.clear();

[...] Cookies ?

var cookies = document.cookie;

for (var i = 0; i < cookies.split(";").length; ++i)
{
    var myCookie = cookies[i];
    var pos = myCookie.indexOf("=");
    var name = pos > -1 ? myCookie.substr(0, pos) : myCookie;
    document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}

is there any way to get the value back after clear these ?

No, there isn't. But you shouldn't rely on this if this is related to a security question.

"Gradle Version 2.10 is required." Error

Easiest way for me to fix this issue:

  1. close IDE.
  2. delete "gradle" folder
  3. re-open project.

Currency formatting in Python

Oh, that's an interesting beast.

I've spent considerable time of getting that right, there are three main issues that differs from locale to locale: - currency symbol and direction - thousand separator - decimal point

I've written my own rather extensive implementation of this which is part of the kiwi python framework, check out the LGPL:ed source here:

http://svn.async.com.br/cgi-bin/viewvc.cgi/kiwi/trunk/kiwi/currency.py?view=markup

The code is slightly Linux/Glibc specific, but shouldn't be too difficult to adopt to windows or other unixes.

Once you have that installed you can do the following:

>>> from kiwi.datatypes import currency
>>> v = currency('10.5').format()

Which will then give you:

'$10.50'

or

'10,50 kr'

Depending on the currently selected locale.

The main point this post has over the other is that it will work with older versions of python. locale.currency was introduced in python 2.5.

How to pass boolean parameter value in pipeline to downstream jobs?

build job: 'downstream_job_name', parameters: [
    booleanParam(name: 'parameter_name', value: false)
]

(cf. https://www.jenkins.io/doc/pipeline/steps/pipeline-build-step/#-build-%20build%20a%20job)

How to force JS to do math instead of putting two strings together

Number()

dots = document.getElementById("txt").value;
dots = Number(dots) + 5;

// from MDN
Number('123')     // 123
Number('123') === 123 /// true
Number('12.3')    // 12.3
Number('12.00')   // 12
Number('123e-1')  // 12.3
Number('')        // 0
Number(null)      // 0
Number('0x11')    // 17
Number('0b11')    // 3
Number('0o11')    // 9
Number('foo')     // NaN
Number('100a')    // NaN
Number('-Infinity') //-Infinity

What is the difference between HAVING and WHERE in SQL?

WHERE is applied as a limitation on the set returned by SQL; it uses SQL's built-in set oeprations and indexes and therefore is the fastest way to filter result sets. Always use WHERE whenever possible.

HAVING is necessary for some aggregate filters. It filters the query AFTER sql has retrieved, assembled, and sorted the results. Therefore, it is much slower than WHERE and should be avoided except in those situations that require it.

SQL Server will let you get away with using HAVING even when WHERE would be much faster. Don't do it.

Git: How to pull a single file from a server repository in Git?

Try using:

git checkout branchName -- fileName

Ex:

git checkout master -- index.php

Determining the last row in a single column

Never too late to post an alternative answer I hope. Here's a snippet of my Find last Cell. I'm primarily interested in speed. On a DB I'm using with around 150,000 rows this function took (average) 0.087 seconds to find solution compared to @Mogsdad elegant JS solution above which takes (average) 0.53 sec on same data. Both arrays were pre-loaded before the function call. It makes use of recursion to do a binary search. For 100,000+ rows you should find it takes no more than 15 to 20 hops to return it's result.

I've left the Log calls in so you can test it in the console first and see its workings.

/* @OnlyCurrentDoc */

function myLastRow() {

var ss=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var colArray = ss.getRange('A1:A').getDisplayValues();  // Change to relevant column label and put in Cache
var TestRow=ss.getLastRow();
var MaxRow=ss.getMaxRows(); 

Logger.log ('TestRow = %s',TestRow);
Logger.log ('MaxRow = %s',MaxRow);

var FoundRow=FindLastRow(TestRow,MaxRow);

Logger.log ('FoundRow = %s',FoundRow);    

function FindLastRow(v_TestRow,v_MaxRow) {

/* Some housekeeping/error trapping first
* 1) Check that LastRow doesn't = Max Rows. If so then suggest to add a few lines as this
* indicates the LastRow was the end of the sheet.
* 2) Check it's not a new sheet with no data ie, LastRow = 0 and/or cell A1 is empty.
* 3) A return result of 0 = an error otherwise any positive value is a valid result.
*/

 return   !(colArray[0][0]) ? 1                   // if first row is empty then presume it's a new empty sheet
        :!!(colArray[v_TestRow][0]) ? v_TestRow   // if the last row is not empty then column A was the longest
        : v_MaxRow==v_TestRow ? v_TestRow         // if Last=Max then consider adding a line here to extend row count, else
        : searchPair(0,v_TestRow);                // get on an find the last row
}

function searchPair(LowRow,HighRow){

var BinRow = ((LowRow+HighRow)/2)|0;   // force an INT to avoid row ambiguity

Logger.log ('LowRow/HighRow/BinRow = %s/%s/%s',LowRow, HighRow, BinRow);

/*   Check your log. You shoud find that the last row is always found in under 20 hops.
 *   This will be true whether your data rows are 100 or 100,000 long.
 *   The longest element of this script is loading the Cache (ColArray)
 */

 return   (!(colArray[BinRow-1][0]))^(!(colArray[BinRow][0])) ? BinRow
        : (!(colArray[BinRow-1][0]))&(!(colArray[BinRow][0])) ? searchPair(LowRow,BinRow-1)
        : (!!(colArray[BinRow-1][0]))|(!!(colArray[BinRow][0])) ? searchPair(BinRow+1,HighRow)
        : false;   // Error
 }
}

/* The premise for the above logic is that the binary search is looking for a specific pairing, <Text/No text>
 * on adjacent rows.  You said there are no gaps so the pairing <No Text/Text> is not tested as it's irrelevant.
 * If the logic finds <No Text/No Text> then it looks back up the sheet, if it finds <Text/Text> it looks further
 * down the sheet.  I think you'll find this is quite fast, especially on datasets > 100,000 rows.
 */

Using margin:auto to vertically-align a div

variable height ,margin top and bottom auto

_x000D_
_x000D_
.black {background:rgba(0,0,0,.5);_x000D_
width: 300px;_x000D_
height: 100px;_x000D_
display: -webkit-flex; /* Safari */_x000D_
display: flex;}_x000D_
.message{_x000D_
background:tomato;_x000D_
margin:auto;_x000D_
padding:5%;_x000D_
width:auto;_x000D_
}
_x000D_
<div class="black">_x000D_
<div class="message">_x000D_
    This is a popup message._x000D_
</div>
_x000D_
_x000D_
_x000D_

variable height ,margin top and bottom auto

Set position / size of UI element as percentage of screen size

The above problem can also be solved using ConstraintLayout through Guidelines.

Below is the snippet.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.constraint.Guideline
    android:id="@+id/upperGuideLine"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.68" />

<Gallery
    android:id="@+id/gallery"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@+id/lowerGuideLine"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="@+id/upperGuideLine" />

<android.support.constraint.Guideline
    android:id="@+id/lowerGuideLine"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.84" />

</android.support.constraint.ConstraintLayout>

How to downgrade python from 3.7 to 3.6

I was having trouble installing tensorflow with python 3.7 and followed these instructions to have a virtual environment setup with python3.6 and got it working

Download the Python3.6 tgz file from the official website (eg. Python-3.6.6.tgz)
Unpack it with tar -xvzf Python-3.6.6.tgz
cd Python-3.6.6
run ./configure
run make altinstall to install it (install vs altinstall explanation here 

setting up python3.6 virtual environment for tensorflow

If you are using jupyter notebook or jupyter lab this can be helpful to choose the right virtual environment

python -m venv projectname
source projectname/bin/activate
pip install ipykernel
ipython kernel install --user --name=projectname

At this point, you can start jupyter, create a new notebook and select the kernel that lives inside your environment.

virtual environment and jupyter notebooks

Hope this helps

RegEx to exclude a specific string constant

You have to use a negative lookahead assertion.

(?!^ABC$)

You could for example use the following.

(?!^ABC$)(^.*$)

If this does not work in your editor, try this. It is tested to work in ruby and javascript:

^((?!ABC).)*$

How to store arrays in MySQL?

Use database field type BLOB to store arrays.

Ref: http://us.php.net/manual/en/function.serialize.php

Return Values

Returns a string containing a byte-stream representation of value that can be stored anywhere.

Note that this is a binary string which may include null bytes, and needs to be stored and handled as such. For example, serialize() output should generally be stored in a BLOB field in a database, rather than a CHAR or TEXT field.

Git: How to remove file from index without deleting files from any repository

To remove the file from the index, use:

git reset myfile

This should not affect your local copy or anyone else's.

Is there a way to style a TextView to uppercase all of its letters?

By using AppCompat textAllCaps in Android Apps supporting older API's (less than 14)

There is one UI widgets that ships with AppCompat named CompatTextView is a Custom TextView extension that adds support for textAllCaps

For newer android API > 14 you can use :

android:textAllCaps="true"

A simple example:

<android.support.v7.internal.widget.CompatTextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:textAllCaps="true"/>

Source:developer.android

Update:

As it so happens CompatTextView was replaced by AppCompatTextView in latest appcompat-v7 library ~ Eugen Pechanec

align an image and some text on the same line without using div width?

Floating will result in wrapping if space is not available.

You can use display:inline and white-space:nowrap to achieve this. Fiddle

<div id="container" style="white-space:nowrap">

    <div id="image" style="display:inline;">
        <img src="tree.png"/>
    </div>

    <div id="texts" style="display:inline; white-space:nowrap;"> 
        A very long text(about 300 words) 
    </div>

</div>?

Sass - Converting Hex to RGBa for background opacity

If you need to mix colour from variable and alpha transparency, and with solutions that include rgba() function you get an error like

      background-color: rgba(#{$color}, 0.3);
                       ^
      $color: #002366 is not a color.
   ?
   ¦       background-color: rgba(#{$color}, 0.3);
   ¦                         ^^^^^^^^^^^^^^^^^^^^

Something like this might be useful.

$meeting-room-colors: (
  Neumann: '#002366',
  Turing: '#FF0000',
  Lovelace: '#00BFFF',
  Shared: '#00FF00',
  Chilling: '#FF1493',
);
$color-alpha: EE;

@each $name, $color in $meeting-room-colors {

  .#{$name} {

     background-color: #{$color}#{$color-alpha};

  }

}

What's the difference between console.dir and console.log?

Another useful difference in Chrome exists when sending DOM elements to the console.

Notice:

  • console.log prints the element in an HTML-like tree
  • console.dir prints the element in a JSON-like tree

Specifically, console.log gives special treatment to DOM elements, whereas console.dir does not. This is often useful when trying to see the full representation of the DOM JS object.

There's more information in the Chrome Console API reference about this and other functions.

How do I restart a program based on user input?

You can do this simply with a function. For example:

def script():
    # program code here...
    restart = raw_input("Would you like to restart this program?")
    if restart == "yes" or restart == "y":
        script()
    if restart == "n" or restart == "no":
        print "Script terminating. Goodbye."
script()

Of course you can change a lot of things here. What is said, what the script will accept as a valid input, the variable and function names. You can simply nest the entire program in a user-defined function (Of course you must give everything inside an extra indent) and have it restart at anytime using this line of code: myfunctionname(). More on this here.

SQL Server function to return minimum date (January 1, 1753)

You could write a User Defined Function that returns the min date value like this:

select cast(-53690 as datetime)

Then use that function in your scripts, and if you ever need to change it, there is only one place to do that.

Alternately, you could use this query if you prefer it for better readability:

select cast('1753-1-1' as datetime)

Example Function

create function dbo.DateTimeMinValue()
returns datetime as
begin
    return (select cast(-53690 as datetime))
end

Usage

select dbo.DateTimeMinValue() as DateTimeMinValue

DateTimeMinValue
-----------------------
1753-01-01 00:00:00.000

Add text to textarea - Jquery

Just append() the text nodes:

$('#replyBox').append(quote); 

http://jsfiddle.net/nQErc/

How to perform mouseover function in Selenium WebDriver using Java?

Check this example how we could implement this.

enter image description here

public class HoverableDropdownTest {

    private WebDriver driver;
    private Actions action;

    //Edit: there may have been a typo in the '- >' expression (I don't really want to add this comment but SO insist on ">6 chars edit"...
    Consumer < By > hover = (By by) -> {
        action.moveToElement(driver.findElement(by))
              .perform();
    };

    @Test
    public void hoverTest() {
        driver.get("https://www.bootply.com/render/6FC76YQ4Nh");

        hover.accept(By.linkText("Dropdown"));
        hover.accept(By.linkText("Dropdown Link 5"));
        hover.accept(By.linkText("Dropdown Submenu Link 5.4"));
        hover.accept(By.linkText("Dropdown Submenu Link 5.4.1"));
    }

    @BeforeTest
    public void setupDriver() {
        driver = new FirefoxDriver();
        action = new Actions(driver);
    }

    @AfterTest
    public void teardownDriver() {
        driver.quit();
    }

}

For detailed answer, check here - http://www.testautomationguru.com/selenium-webdriver-automating-hoverable-multilevel-dropdowns/

How to get to Model or Viewbag Variables in a Script Tag

You can do this way, providing Json or Any other variable:

1) For exemple, in the controller, you can use Json.NET to provide Json to the ViewBag:

ViewBag.Number = 10;
ViewBag.FooObj = JsonConvert.SerializeObject(new Foo { Text = "Im a foo." });

2) In the View, put the script like this at the bottom of the page.

<script type="text/javascript">
    var number = parseInt(@ViewBag.Number); //Accessing the number from the ViewBag
    alert("Number is: " + number);
    var model = @Html.Raw(@ViewBag.FooObj); //Accessing the Json Object from ViewBag
    alert("Text is: " + model.Text);
</script> 

Get a DataTable Columns DataType

dt.Columns[0].DataType.Name.ToString()

Does 'position: absolute' conflict with Flexbox?

You have to give width:100% to parent to center the text.

_x000D_
_x000D_
 .parent {_x000D_
   display: flex;_x000D_
   justify-content: center;_x000D_
   position: absolute;_x000D_
   width:100%_x000D_
 }
_x000D_
<div class="parent">_x000D_
  <div class="child">text</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

If you also need to centre align vertically, give height:100% and align-itens: center

.parent {
   display: flex;
   justify-content: center;
   align-items: center;
   position: absolute;
   width:100%;
   height: 100%;
 }

Why is my locally-created script not allowed to run under the RemoteSigned execution policy?

When you run a .ps1 PowerShell script you might get the message saying “.ps1 is not digitally signed. The script will not execute on the system.” To fix it you have to run the command below to run Set-ExecutionPolicy and change the Execution Policy setting.

Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass

Get: TypeError: 'dict_values' object does not support indexing when using python 3.2.3

In Python 3, dict.values() (along with dict.keys() and dict.items()) returns a view, rather than a list. See the documentation here. You therefore need to wrap your call to dict.values() in a call to list like so:

v = list(d.values())
{names[i]:v[i] for i in range(len(names))}

How to check whether a given string is valid JSON in Java

A wild idea, try parsing it and catch the exception:

import org.json.*;

public boolean isJSONValid(String test) {
    try {
        new JSONObject(test);
    } catch (JSONException ex) {
        // edited, to include @Arthur's comment
        // e.g. in case JSONArray is valid as well...
        try {
            new JSONArray(test);
        } catch (JSONException ex1) {
            return false;
        }
    }
    return true;
}

This code uses org.json JSON API implementation that is available on github, in maven and partially on Android.

Static variable inside of a function in C

6 7

compiler arranges that static variable initialization does not happen each time the function is entered

How to get the list of all installed color schemes in Vim?

Just for convenient reference as I see that there are a lot of people searching for this topic and are too laz... sorry, busy, to check themselves (including me). Here a list of the default set of colour schemes for Vim 7.4:

blue.vim
darkblue.vim,
delek.vim
desert.vim
elflord.vim
evening.vim
industry.vim                                                                                                                                                 
koehler.vim                                                                                                                                                  
morning.vim                                                                                                                                                  
murphy.vim                                                                                                                                                   
pablo.vim                                                                                                                                                    
peachpuff.vim                                                                                                                                                
ron.vim                                                                                                                                                      
shine.vim                                                                                                                                                    
slate.vim                                                                                                                                                    
torte.vim                                                                                                                                                    
zellner.vim 

What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

I had this problem when upgrading to Visual Studio 2015 and none of the solutions posted here made any difference, although the config is right the location for the change is not. I fixed this issue by adding this configuration:

<startup useLegacyV2RuntimeActivationPolicy="true">
</startup>

To: C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow\TE.ProcessHost.Managed.exe.config

Then restarted Visual Studio.

How can I use an array of function pointers?

This simple example for multidimensional array with function pointers":

void one( int a, int b){    printf(" \n[ ONE ]  a =  %d   b = %d",a,b);}
void two( int a, int b){    printf(" \n[ TWO ]  a =  %d   b = %d",a,b);}
void three( int a, int b){    printf("\n [ THREE ]  a =  %d   b = %d",a,b);}
void four( int a, int b){    printf(" \n[ FOUR ]  a =  %d   b = %d",a,b);}
void five( int a, int b){    printf(" \n [ FIVE ]  a =  %d   b = %d",a,b);}
void(*p[2][2])(int,int)   ;
int main()
{
    int i,j;
    printf("multidimensional array with function pointers\n");

    p[0][0] = one;    p[0][1] = two;    p[1][0] = three;    p[1][1] = four;
    for (  i  = 1 ; i >=0; i--)
        for (  j  = 0 ; j <2; j++)
            (*p[i][j])( (i, i*j);
    return 0;
}

How do I set GIT_SSL_NO_VERIFY for specific repos only?

for windows, if you want global config, then run

git config --global http.sslVerify false

How to remove a directory from git repository?

You can use Attlasian Source Tree (Windows) (https://www.atlassian.com/software/sourcetree/overview). Just select files from tree and push button "Remove" at the top. Files will be deleted from local repository and local git database. Then Commit, then push.

How do I access named capturing groups in a .NET Regex?

The following code sample, will match the pattern even in case of space characters in between. i.e. :

<td><a href='/path/to/file'>Name of File</a></td>

as well as:

<td> <a      href='/path/to/file' >Name of File</a>  </td>

Method returns true or false, depending on whether the input htmlTd string matches the pattern or no. If it matches, the out params contain the link and name respectively.

/// <summary>
/// Assigns proper values to link and name, if the htmlId matches the pattern
/// </summary>
/// <returns>true if success, false otherwise</returns>
public static bool TryGetHrefDetails(string htmlTd, out string link, out string name)
{
    link = null;
    name = null;

    string pattern = "<td>\\s*<a\\s*href\\s*=\\s*(?:\"(?<link>[^\"]*)\"|(?<link>\\S+))\\s*>(?<name>.*)\\s*</a>\\s*</td>";

    if (Regex.IsMatch(htmlTd, pattern))
    {
        Regex r = new Regex(pattern,  RegexOptions.IgnoreCase | RegexOptions.Compiled);
        link = r.Match(htmlTd).Result("${link}");
        name = r.Match(htmlTd).Result("${name}");
        return true;
    }
    else
        return false;
}

I have tested this and it works correctly.

Does WhatsApp offer an open API?

1) It looks possible. This info on Github describes how to create a java program to send a message using the whatsapp encryption protocol from WhisperSystems.

2) No. See the whatsapp security white paper.

3) See #1.

node and Error: EMFILE, too many open files

I did all the stuff above mentioned for same problem but nothing worked. I tried below it worked 100%. Simple config changes.

Option 1 set limit (It won't work most of the time)

user@ubuntu:~$ ulimit -n 65535

check available limit

user@ubuntu:~$ ulimit -n
1024

Option 2 To increase the available limit to say 65535

user@ubuntu:~$ sudo nano /etc/sysctl.conf

add the following line to it

fs.file-max = 65535

run this to refresh with new config

user@ubuntu:~$ sudo sysctl -p

edit the following file

user@ubuntu:~$ sudo vim /etc/security/limits.conf

add following lines to it

root soft     nproc          65535    
root hard     nproc          65535   
root soft     nofile         65535   
root hard     nofile         65535

edit the following file

user@ubuntu:~$ sudo vim /etc/pam.d/common-session

add this line to it

session required pam_limits.so

logout and login and try the following command

user@ubuntu:~$ ulimit -n
65535

Option 3 Just add below line in

DefaultLimitNOFILE=65535

to /etc/systemd/system.conf and /etc/systemd/user.conf

Node.js get file extension

It's a lot more efficient to use the substr() method instead of split() & pop()

Have a look at the performance differences here: http://jsperf.com/remove-first-character-from-string

// returns: 'html'
var path = require('path');
path.extname('index.html').substr(1);

enter image description here

Update August 2019 As pointed out by @xentek in the comments; substr() is now considered a legacy function (MDN documentation). You can use substring() instead. The difference between substr() and substring() is that the second argument of substr() is the maximum length to return while the second argument of substring() is the index to stop at (without including that character). Also, substr() accepts negative start positions to be used as an offset from the end of the string while substring() does not.

How to use HTTP GET in PowerShell?

In PowerShell v3, have a look at the Invoke-WebRequest and Invoke-RestMethod e.g.:

$msg = Read-Host -Prompt "Enter message"
$encmsg = [System.Web.HttpUtility]::UrlEncode($msg)
Invoke-WebRequest -Uri "http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$encmsg&encoding=windows-1255"

Remove multiple objects with rm()

Make the list a character vector (not a vector of names)

rm(list = c('temp1','temp2'))

or

rm(temp1, temp2)

how to install tensorflow on anaconda python 3.6

I will simply leave this here because none of the other approaches worked for me. Also, I can look it up myself when I need it for new devices.

THIS IS THE WAY IT WORKS:

  1. Install Anaconda
  2. Open Anaconda Prompt
  3. conda create --name tensorflow
  4. conda activate tensorflow
  5. Search with conda search tensorflow for all available TensorFlow versions
  6. Choose the one you need (usually the newest one)
  7. Explicitly name the version now (otherwise it happened to me that version 1.14 was installed): conda install -c conda-forge tensorflow=YOUR_VERSION
  8. Open Anaconda, choose the new environment and install Spyder
  9. Install Microsoft Visual C++ Redistributable for Visual Studio 2015, 2017 and 2019
  10. Download msvcp140.dll and add the .dll-File to the Windows\System32 folder

Now it should work like a charm!

TROUBLESHOOTING:

If it still doesn't work, try this, it worked for me:

Open Anaconda-Prompt:

  1. Create an environment with Python 3.6 like this: conda create --name tensorflow_env python=3.6
  2. conda activate tensorflow
  3. Steps 6. and 6. from the list above
  4. conda install tensorflow=YOUR_VERSION(not forge, just like this!)
  5. Now do steps 8, 9, 10 from above

TENSORFLOW GPU:

If you want to use your GPU, do it the same way as described above, with the only difference to install tensorflow-gpu instead if tensorflow.

And, you must install the newest NVIDIA driver for your GPU, you can find and choose the right one here.

(Yes, in TF 2 there's both, a CPU and GPU support, in the "normal" library. However, if you install tensorflow-gpu via conda, it installs the CUDA and cudNN etc. you need automatically for you - also the right versions. This way easier and faster.)

Count number of iterations in a foreach loop

foreach ($Contents as $index=>$item) {
  $item[$index];// if there are 15 $item[number] in this foreach, I want get the value : 15
}

How do the post increment (i++) and pre increment (++i) operators work in Java?

++a increments and then uses the variable.
a++ uses and then increments the variable.

If you have

a = 1;

and you do

System.out.println(a++); //You will see 1

//Now a is 2

System.out.println(++a); //You will see 3

codaddict explains your particular snippet.

CSS: Creating textured backgrounds

If you search for an image base-64 converter, you can embed some small image texture files as code into your @import url('') section of code. It will look like a lot of code; but at least all your data is now stored locally - rather than having to call a separate resource to load the image.

Example link: http://www.base64-image.de/

When I take a file from my own inventory of a simple icon in PNG format, and convert it to base-64, it looks like this in my CSS:

url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAm0SURBVHjaRFdLrF1lFf72++xzzj33nMPt7QuhxNJCY4smGomKCQlWxMSJgQ4dyEATE3FCSDRxjnHiwMTUAdHowIGJOqBEg0RDCCESKIgCWtqCfd33eeyz39vvW/vcctvz2nv/61/rW9/61vqd7CIewMT5VlnChf059t40QBwB7io+vjx3kczb++D9Tof3x1xWNu39hP9nHhxH62t0u7zWb9rFtl73G1veXamrs98rf+5Pbjnnnv5p+IPNiQvXreF7AZ914bgOv/PBOIDH767HH/DgO4F9d7hLHPkYrIRw+d1x2/sufBRViboCgkCvBmmWcw2v5zWStABv4+iBOe49enXqb2x4a79+wYfidx2XRgP4vm8QBLTgBx4CLva4QRjyO+9FUUjndD1ATJjkgNaEoW/R6ZmyqgxFvU3nCTzaqLhzURSoGWJ82cN9d3r3+Z5TV6srni30fAdNXSP0a3ToiCHvVuh1mQsua+gl98Zqz0PNEIOAv4OidZToNU1OG8TAbUC7qGirdV6bV0SGa3gvISKrPUcoFj5xt/S4xDtktFVZMRrXItDiKAxRFiVh9HH2y+s05OHVizvod+mJ4yEnebSOROCzAfJ5ZgRxGHmXzwQ+U+aKFJ5oQ8fllGfp0XM+f0OsaaoaHnPq8U4YtFAqz0rL+riDR7+4guPrGaK4i8+dWMdotYdBf8CIPaatgzCKEHdi7hPRTg9uvIoLL76DC39+DcN+F4s8ZaAOCkYfEOmCQenPl3ftho4xmxcYfcmcCZGAMALjUYBvf2WM3//pDcwZoVKSzyNUowHGa2Pc0R9iOFjFcMSHhwxtQHNjDye+8Bht1Hj+wpsCy3i0N19gY3sPZ+5ty8uXVyFh8jyXm7EW+RkwZ47jmjNFJXKEGJ06g8ebDi5vptjYnWJvj68iR87vO2R3b0bHtmck4jYOjVYQuR8gHr2L73z3NN68eBm3NqbGo7gTMoAu6qatbV8wi70iiCL2/ZaQIfPZYf59eiBYcfdXMbj7NJ55+Cf4x1sfYkUiYSZ3jbie267LyKFPfXKI809/BjsfXMPpPMPjZ4/g2fNvg5mywEaDFa5JSNpGDihSMZU64Dlkr2uElCqVJFhJV4UEsMLXacTdIY4cSCwNYrdSKEOeZ1Q2Qv7n6iZ+99IlPHCwwot/3cDxU/dynWdk3v9ToJVs101lP1zWrgzJjGwpFULBzWs0t6WwINNd3HnwgPHGZbUIpZIIqFpqcqcbx2R4jJcv3sLdD6Z4+587JG6Fg+MAl6+1xAZajShLiR/Z4Wszwh9zw7gTWemYoFgZtvxgUsyJcOl5oOtcW0uwpHKMTrbmSYLVfoyk6OLUqZM4uNbF1asf4cBKTkHKuGll61MqYl0JXXrU68ao5RjRUNk5vpQtMkmuyQ1Yrb7H15qRJwj2hUvpkxPUfTpeSX+ZljTNMZmXOHLsJJ48t4KbWzso329w4ZUNOuuaGrpMiVBw95uPR0csWhrsdTv2aSXK+vYIPfK/86m/8VpDKe7cblAtOjClExpCQtfSJMVOcBL+I9/A0bMP4cFP32NaoHQrCD2vunddzwTbUqA8Rp2gLUEJDKOS5ktmceMScP1dNpQCi6Tk3gGBabBIMxmhdtS2eV21FRGFEa5f36Ht+4HRw7jnzEOMlmsXKbI8NxQkAf5w6FD3QyNU20Rqay5Mj5GwMS9ZDTf/S+MhTnyiD9w1RK/XwTvv7xqRxKG8rFoSEzUJmch2a3PXCtVY3+tzuwZ50d7LGYhs+8qnOlrJHRtGpM3F8IqkUDRMLzepceNGQjHZxFPfHGJ1MKMTx/DMDz1c/rCy3NdNc1u+hYQSu8gFc2R9Qn8qaVF5v71rhV+r+ZA46myN8iiPJcl+YAQTS8TByZ6Dm9cb7O7usgNu4+T2BJvbazQxREG9EHo5YVUqFWmWMx3FhPc3IG3O0tIqQMaLggZj64aQ5toEo1w7hDLJarBCrBv2SUb1gpSOTCYNtjYqE5QgcrC7UxtitfX/wHIqIs+ThTnuqP8vrvPu83wdxtbNErMkp050DLGcPNCw4jtUuR7FQ4YWWYlzjw5wZJSwZoXEzEpuPkvRFBk0FtQFiZext6eOkdV1GBFTFAStFoiA83RBljfoRZzR/vdvDhA7eOftGerSMfbnRMcjlWwCExOlhjVFZJIU+PqXYqyevAJc2cJ8K8KlzRDFSoXd6RCDO2GbiS83FyusdTJewxP7ha7LeJoVbU/gJr6zg/zyFYRHZnj9YorabTki5CRGxgFYvgoSMVBxYpYGWB0dZ+ncg9d/VeKRJ1/FGtuxmF4pHyp7Qd9McezoHTh8IG51QE6oFMtWB+KY82J3gX+9N8MJ9xZeeSNDh2gusgwpn8mLZXUIxsDGk8aYmU83We8sn/EYvf4Yp08cZvPpGbzyuVr2CxMvEyENpLCB0+Y93q8KDbcVIke8qXGpW+Kt9xc2U+oZIZCXRTsRzea+abgm2YybTKc587YH8LNOGoyHKrvISrGNHuaIUNPoXTF9FYlbL0tRk9WMLD60RpImFCmOYn95rcH2XoW1VXc5Z/LVOK0QZWllRhSWCDWdpsg/ShAOK+xMBtie5lailSlcKzgWad1+qnekWWojuSon10heB3jqCYpYlmD98AjPPbdLojsMsK0UNSH9k5KqB1tX23dCjeTGjRzhdoED4QTff2Idh8YhK8CxuVgGoDLT6KZzAk8navN1vocimZCYKdaHCe5f2+AGfTz7h5zzAW2NQrKfaRJqFZYtXkLEN83tIcdwTbJXthwMj64jM/hdPPZZ1rWXstY9SjbTxTyio5ZI/uocEPF3OCIAh0kEcifZQbO7wT4Q4Jd/3MbPfnuNLbnHlFXYP1KpAjTsiEu+8uiYmHh2FPvx+Q8NSqFScEaUUtoMQQLoWXmuKbu2SmjssKH7MqrkNstzXcnjWsXX0YN944/WFrJlnbO2IWY5lMIOEMkiMxk9cdchu6nGUi6xUr4ko4I9YxmpWozNS/0vjBeVafx+dNZofHdZ722FqOKKsp2GHBNspaCq/e0pdSByLRKeifhZW3cET0U6SIg03ZglqgEV7TGMMxQluzQnijLntdCMS2Z1DlyQS1nRmGhlWeu8KsRxWjscF3itcfz+ILv5tc9vYGui+a6FUP0ey8OymF812qD1WPOATkeSUxMgpklqaNMQS6soVSGu1Xpp3ZTNLsBSQ9oUSIPuO9aQsKj8H/2i+M14cIVV5UZZThrWikhQtOdEhxOqH1ZQI6PysyQdO93q/KdeHbC/hp2P+aG3PG1aiCVahDWIm49p77RHf/LHfeFlvPR/AQYAyMIq/fJRUogAAAAASUVORK5CYII=')

With your texture images, you'll want to employ a similar process.

react hooks useEffect() cleanup for only componentWillUnmount?

useEffect are isolated within its own scope and gets rendered accordingly. Image from https://reactjs.org/docs/hooks-custom.html

enter image description here

javascript regex for special characters

How about this:-

var regularExpression = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,}$/;

It will allow a minimum of 6 characters including numbers, alphabets, and special characters

Remote Connections Mysql Ubuntu

You are using ubuntu 12 (quite old one)

First, Open the /etc/mysql/mysql.conf.d/mysqld.cnf file (/etc/mysql/my.cnf in Ubuntu 14.04 and earlier versions

Under the [mysqld] Locate the Line, bind-address = 127.0.0.1 And change it to, bind-address = 0.0.0.0 or comment it

Then, Restart the Ubuntu MysQL Server systemctl restart mysql.service

Now Ubuntu Server will allow remote access to the MySQL Server, But still you need to configure MySQL users to allow access from any host.

User must be 'username'@'%' with all the required grants

To make sure that, MySQL server listens on all interfaces, run the netstat command as follows.

netstat -tulnp | grep mysql

Hope this works !

What exactly is OAuth (Open Authorization)?

OAuth is all about delegating Authorization (choosing someone who can do Authorization for you). Note that Authentication and Authorization are different things. OAuth is Authorization (Access control), and if you want to implement Authentication (ID verification) also, OpenID protocol can be used on top of OAuth.

All big companies like Facebook, Google, Github,... use this kind of authentication/authorization nowadays. For example, I just signed in on this website using my Google account, this means Stackoverflow doesn't know my password, it receives the allowance from Google where my password (hashed obviously) is saved. This gives a lot of benefits, one of them is; In the near future you won't have to make several accounts on every website. One website (which you trust most) can be used to login to all other websites. So you'll only have to remember one password.

$watch an object

Call $watch with true as the third argument:

$scope.$watch('form', function(newVal, oldVal){
    console.log('changed');
}, true);

By default when comparing two complex objects in JavaScript, they will be checked for "reference" equality, which asks if the two objects refer to the same thing, rather than "value" equality, which checks if the values of all the properties of those objects are equal.

Per the Angular documentation, the third parameter is for objectEquality:

When objectEquality == true, inequality of the watchExpression is determined according to the angular.equals function. To save the value of the object for later comparison, the angular.copy function is used. This therefore means that watching complex objects will have adverse memory and performance implications.

Do subclasses inherit private fields?

Most of the confusion in the question/answers here surrounds the definition of Inheritance.

Obviously, as @DigitalRoss explains an OBJECT of a subclass must contain its superclass's private fields. As he states, having no access to a private member doesn't mean its not there.

However. This is different than the notion of inheritance for a class. As is the case in the java world, where there is a question of semantics the arbiter is the Java Language Specification (currently 3rd edition).

As the JLS states (https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.2):

Members of a class that are declared private are not inherited by subclasses of that class. Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared.

This addresses the exact question posed by the interviewer: "do subCLASSES inherit private fields". (emphasis added by me)

The answer is No. They do not. OBJECTS of subclasses contain private fields of their superclasses. The subclass itself has NO NOTION of private fields of its superclass.

Is it semantics of a pedantic nature? Yes. Is it a useful interview question? Probably not. But the JLS establishes the definition for the Java world, and it does so (in this case) unambiguously.

EDITED (removed a parallel quote from Bjarne Stroustrup which due to the differences between java and c++ probably only add to the confusion. I'll let my answer rest on the JLS :)

Getting Java version at runtime

Just a note that in Java 9 and above, the naming convention is different. System.getProperty("java.version") returns "9" rather than "1.9".

How to atomically delete keys matching a pattern using Redis

Disclaimer: the following solution doesn't provide atomicity.

Starting with v2.8 you really want to use the SCAN command instead of KEYS[1]. The following Bash script demonstrates deletion of keys by pattern:

#!/bin/bash

if [ $# -ne 3 ] 
then
  echo "Delete keys from Redis matching a pattern using SCAN & DEL"
  echo "Usage: $0 <host> <port> <pattern>"
  exit 1
fi

cursor=-1
keys=""

while [ $cursor -ne 0 ]; do
  if [ $cursor -eq -1 ]
  then
    cursor=0
  fi

  reply=`redis-cli -h $1 -p $2 SCAN $cursor MATCH $3`
  cursor=`expr "$reply" : '\([0-9]*[0-9 ]\)'`
  keys=${reply##[0-9]*[0-9 ]}
  redis-cli -h $1 -p $2 DEL $keys
done

[1] KEYS is a dangerous command that can potentially result in a DoS. The following is a quote from its documentation page:

Warning: consider KEYS as a command that should only be used in production environments with extreme care. It may ruin performance when it is executed against large databases. This command is intended for debugging and special operations, such as changing your keyspace layout. Don't use KEYS in your regular application code. If you're looking for a way to find keys in a subset of your keyspace, consider using sets.

UPDATE: a one liner for the same basic effect -

$ redis-cli --scan --pattern "*:foo:bar:*" | xargs -L 100 redis-cli DEL

Convert byte slice to io.Reader

r := strings(byteData)

This also works to turn []byte into io.Reader

Open Facebook page from Android app?

A more reusable approach.

This is a functionality we generally use in most of our apps. Hence here is a reusable piece of code to achieve this.

(Similar to other answers in terms for facts. Posting it here just to simplify and make the implementation reusable)

"fb://page/ does not work with newer versions of the FB app. You should use fb://facewebmodal/f?href= for newer versions. (Like mentioned in another answer here)

This is a full fledged working code currently live in one of my apps:

public static String FACEBOOK_URL = "https://www.facebook.com/YourPageName";
public static String FACEBOOK_PAGE_ID = "YourPageName";

//method to get the right URL to use in the intent
public String getFacebookPageURL(Context context) {
        PackageManager packageManager = context.getPackageManager();
        try {
            int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;
            if (versionCode >= 3002850) { //newer versions of fb app
                return "fb://facewebmodal/f?href=" + FACEBOOK_URL;
            } else { //older versions of fb app
                return "fb://page/" + FACEBOOK_PAGE_ID;
            }
        } catch (PackageManager.NameNotFoundException e) {
            return FACEBOOK_URL; //normal web url
        }
    }

This method will return the correct url for app if installed or web url if app is not installed.

Then start an intent as follows:

Intent facebookIntent = new Intent(Intent.ACTION_VIEW);
String facebookUrl = getFacebookPageURL(this);
facebookIntent.setData(Uri.parse(facebookUrl));
startActivity(facebookIntent);

That's all you need.

How to count rows with SELECT COUNT(*) with SQLAlchemy?

Query for just a single known column:

session.query(MyTable.col1).count()

check if a std::vector contains a certain object?

See question: How to find an item in a std::vector?

You'll also need to ensure you've implemented a suitable operator==() for your object, if the default one isn't sufficient for a "deep" equality test.

does linux shell support list data structure?

It supports lists, but not as a separate data structure (ignoring arrays for the moment).

The for loop iterates over a list (in the generic sense) of white-space separated values, regardless of how that list is created, whether literally:

for i in 1 2 3; do
    echo "$i"
done

or via parameter expansion:

listVar="1 2 3"
for i in $listVar; do
    echo "$i"
done

or command substitution:

for i in $(echo 1; echo 2; echo 3); do
    echo "$i"
done

An array is just a special parameter which can contain a more structured list of value, where each element can itself contain whitespace. Compare the difference:

array=("item 1" "item 2" "item 3")
for i in "${array[@]}"; do   # The quotes are necessary here
    echo "$i"
done

list='"item 1" "item 2" "item 3"'
for i in $list; do
    echo $i
done
for i in "$list"; do
    echo $i
done
for i in ${array[@]}; do
    echo $i
done

Return number of rows affected by UPDATE statements

CREATE PROCEDURE UpdateTables
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    DECLARE @RowCount1 INTEGER
    DECLARE @RowCount2 INTEGER
    DECLARE @RowCount3 INTEGER
    DECLARE @RowCount4 INTEGER

    UPDATE Table1 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount1 = @@ROWCOUNT
    UPDATE Table2 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount2 = @@ROWCOUNT
    UPDATE Table3 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount3 = @@ROWCOUNT
    UPDATE Table4 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount4 = @@ROWCOUNT

    SELECT @RowCount1 AS Table1, @RowCount2 AS Table2, @RowCount3 AS Table3, @RowCount4 AS Table4
END

How to convert JSON object to JavaScript array?

This will solve the problem:

const json_data = {"2013-01-21":1,"2013-01-22":7};

const arr = Object.keys(json_data).map((key) => [key, json_data[key]]);

console.log(arr);

Or using Object.entries() method:

console.log(Object.entries(json_data));

In both the cases, output will be:

/* output: 
[['2013-01-21', 1], ['2013-01-22', 7]]
*/

How to set DataGrid's row Background, based on a property value using data bindings

Use a DataTrigger:

<DataGrid ItemsSource="{Binding YourItemsSource}">
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow"> 
            <Style.Triggers>
                <DataTrigger Binding="{Binding State}" Value="State1">
                    <Setter Property="Background" Value="Red"></Setter>
                </DataTrigger>
                <DataTrigger Binding="{Binding State}" Value="State2">
                    <Setter Property="Background" Value="Green"></Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>
</DataGrid>

How do I test a single file using Jest?

If you use Yarn, you can add the .spec.js or .test.js file directly after:

yarn test src/lib/myfile.test.js

This is the part from my package.json file with Jest installed as a local package (removed the relevant parts):

{
...
  "scripts": {
    "test": "jest",
    "testw": "jest --watch",
    "testc": "jest --coverage",
...
  },
  "devDependencies": {
    "jest": "^18.1.0",
    ...
  },

}

What's the best way to check if a String represents an integer in Java?

This works for me. Simply to identify whether a String is a primitive or a number.

private boolean isPrimitive(String value){
        boolean status=true;
        if(value.length()<1)
            return false;
        for(int i = 0;i<value.length();i++){
            char c=value.charAt(i);
            if(Character.isDigit(c) || c=='.'){

            }else{
                status=false;
                break;
            }
        }
        return status;
    }

How to apply box-shadow on all four sides?

The most simple solution and easiest way is to add shadow for all four side. CSS

box-shadow: 0 0 2px 2px #ccc; /* with blur shadow*/
box-shadow: 0 0 0 2px #ccc; /* without blur shadow*/

Live search through table rows

Old question but i find out how to do it faster. For my example: i have about 10k data in my table so i need some fast search machine.

Here is what i did:

$('input[name="search"]').on('keyup', function() {

        var input, filter, tr, td, i;

        input  = $(this);
        filter = input.val().toUpperCase();
        tr     = $("table tr");

        for (i = 0; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td")[0]; // <-- change number if you want other column to search
            if (td) {
                if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
                    tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }
    })

Hope it helps somebody.

How to get an IFrame to be responsive in iOS Safari?

The solution for this problem is actually quite simple and there are two ways to go about it. If you have control over the Content.html then simply change the div#ScrolledArea width CSS to:

        width: 1px;
        min-width: 100%;
        *width: 100%;

Basically the idea here is simple, you set the width to something that is smaller than the viewport (iframe width in this case) and then overwrite it with min-width: 100% to allow for actual width: 100% which iOS Safari by default overwrites. The *width: 100%; is there so the code would remain IE6 compatible, but if you do not care for IE6 you can omit it. Demo

enter image description here enter image description here

As you can see now, the div#ScrolledArea width is actually 100% and the overflow: scroll; can do it's thing and hide the overflowing content. If you have access to the iframe content, then this is preferable.

However if you do not have access to the iframe content (for what ever reason) then you can actually use the same technique on the iframe itself. Simply use the same CSS on the iframe:

    iframe {
        width: 1px;
        min-width: 100%;
        *width: 100%;
    }

However, there is one limitation with this, you need to turn off the scrollbars with scrolling="no" on the iframe for this to work:

<iframe height="950" width="100%" scrolling="no" src="Content.html"></iframe>

If the scrollbars are allowed, then this wont work on the iframe anymore. That said, if you modify the Content.html instead then you can retain the scrolling in the iframe. Demo

How to reload a div without reloading the entire page?

Use this.

$('#mydiv').load(document.URL +  ' #mydiv');

Note, include a space before the hastag.

Mongoose limit/offset and count query

There is a library that will do all of this for you, check out mongoose-paginate-v2

how to filter out a null value from spark dataframe

Or like df.filter($"friend_id".isNotNull)

How to get domain URL and application name?

I would strongly suggest you to read through the docs, for similar methods. If you are interested in context path, have a look here, ServletContext.getContextPath().

jquery drop down menu closing by clicking outside

You would need to attach your click event to some element. If there are lots of other elements on the page you would not want to attach a click event to all of them.

One potential way would be to create a transparent div below your dropdown menu but above all other elements on the page. You would show it when the drop down was shown. Have the element have a click hander that hides the drop down and the transparent div.

_x000D_
_x000D_
$('#clickCatcher').click(function () { _x000D_
  $('#dropContainer').hide();_x000D_
  $(this).hide();_x000D_
});
_x000D_
#dropContainer { z-index: 101; ... }_x000D_
#clickCatcher { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 100; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="dropDown"></div>_x000D_
<div id="clickCatcher"></div>
_x000D_
_x000D_
_x000D_

Asynchronously load images with jQuery

$(function () {

    if ($('#hdnFromGLMS')[0].value == 'MB9262') {
        $('.clr').append('<img src="~/Images/CDAB_london.jpg">');
    }
    else
    {
        $('.clr').css("display", "none");
        $('#imgIreland').css("display", "block");
        $('.clrIrland').append('<img src="~/Images/Ireland-v1.jpg">');
    }
});

Replace characters from a column of a data frame R

If your variable data1$c is a factor, it's more efficient to change the labels of the factor levels than to create a new vector of characters:

levels(data1$c) <- sub("_", "-", levels(data1$c))


            a b   c
1  0.73945260 a A-B
2  0.75998815 b A-B
3  0.19576725 c A-B
4  0.85932140 d A-B
5  0.80717115 e A-C
6  0.09101492 f A-C
7  0.10183586 g A-C
8  0.97742424 h A-C
9  0.21364521 i A-C
10 0.02389782 j A-C

How to establish a connection pool in JDBC?

HikariCP

It's modern, it's fast, it's simple. I use it for every new project. I prefer it a lot over C3P0, don't know the other pools too well.

How do I auto-resize an image to fit a 'div' container?

A simple solution is to use flexbox. Define the container's CSS to:

.container{
    display: flex;
    justify-content: center;
    align-items: center;
    align-content: center;
    overflow: hidden;
    /* Any custom height */
}

Adjust the contained image width to 100% and you should get a nice centered image in the container with the dimensions preserved.

Inheritance with base class constructor with parameters

The problem is that the base class foo has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:

public bar(int a, int b) : base(a, b)
{
    c = a * b;
}

How to convert list of key-value tuples into dictionary?

This gives me the same error as trying to split the list up and zip it. ValueError: dictionary update sequence element #0 has length 1916; 2 is required

THAT is your actual question.

The answer is that the elements of your list are not what you think they are. If you type myList[0] you will find that the first element of your list is not a two-tuple, e.g. ('A', 1), but rather a 1916-length iterable.

Once you actually have a list in the form you stated in your original question (myList = [('A',1),('B',2),...]), all you need to do is dict(myList).

Object cannot be cast from DBNull to other types

I suspect that the line

DataTO.Id = Convert.ToInt64(dataAccCom.GetParameterValue(IDbCmd, "op_Id"));

is causing the problem. Is it possible that the op_Id value is being set to null by the stored procedure?

To Guard against it use the Convert.IsDBNull method. For example:

if (!Convert.IsDBNull(dataAccCom.GetParameterValue(IDbCmd, "op_Id"))
{
 DataTO.Id = Convert.ToInt64(dataAccCom.GetParameterValue(IDbCmd, "op_Id"));
}
else 
{
 DataTO.Id = ...some default value or perform some error case management
}

Getting Django admin url for an object

For pre 1.1 django it is simple (for default admin site instance):

reverse('admin_%s_%s_change' % (app_label, model_name), args=(object_id,))