Programs & Examples On #Lineargradientbrush

How to pass form input value to php function

you must have read about function call . here i give you example of it.

<?php
 funtion pr($n)
{
echo $n;
 }
?>
<form action="<?php $f=$_POST['input'];pr($f);?>" method="POST">
<input name=input type=text></input>
</form>

Pandas: ValueError: cannot convert float NaN to integer

Also, even at the lastest versions of pandas if the column is object type you would have to convert into float first, something like:

df['column_name'].astype(np.float).astype("Int32")

NB: You have to go through numpy float first and then to nullable Int32, for some reason.

The size of the int if it's 32 or 64 depends on your variable, be aware you may loose some precision if your numbers are to big for the format.

Check if a column contains text using SQL

Leaving database modeling issues aside. I think you can try

SELECT * FROM STUDENTS WHERE ISNUMERIC(STUDENTID) = 0

But ISNUMERIC returns 1 for any value that seems numeric including things like -1.0e5

If you want to exclude digit-only studentids, try something like

SELECT * FROM STUDENTS WHERE STUDENTID LIKE '%[^0-9]%'

Git diff -w ignore whitespace only at start & end of lines

For end of line use:

git diff --ignore-space-at-eol

Instead of what are you using currently:

git diff -w (--ignore-all-space)

For start of line... you are out of luck if you want a built in solution.

However, if you don't mind getting your hands dirty there's a rather old patch floating out there somewhere that adds support for "--ignore-space-at-sol".

JSON Java 8 LocalDateTime format in Spring Boot

I finally found here how to do it. To fix it, I needed another dependency:

compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.4.0")

By including this dependency, Spring will automatically register a converter for it, as described here. After that, you need to add the following to application.properties:

spring.jackson.serialization.write_dates_as_timestamps=false

This will ensure that a correct converter is used, and dates will be printed in the format of 2016-03-16T13:56:39.492

Annotations are only needed in case you want to change the date format.

How to use org.apache.commons package?

Download commons-net binary from here. Extract the files and reference the commons-net-x.x.jar file.

Passing parameters to JavaScript files

You can pass parameters with arbitrary attributes. This works in all recent browsers.

<script type="text/javascript" data-my_var_1="some_val_1" data-my_var_2="some_val_2" src="/js/somefile.js"></script>

Inside somefile.js you can get passed variables values this way:

........

var this_js_script = $('script[src*=somefile]'); // or better regexp to get the file name..

var my_var_1 = this_js_script.attr('data-my_var_1');   
if (typeof my_var_1 === "undefined" ) {
   var my_var_1 = 'some_default_value';
}
alert(my_var_1); // to view the variable value

var my_var_2 = this_js_script.attr('data-my_var_2');   
if (typeof my_var_2 === "undefined" ) {
   var my_var_2 = 'some_default_value';
}
alert(my_var_2); // to view the variable value

...etc...

Visual Studio displaying errors even if projects build

for VS-2017, deleting .vs folder worked for me.

jQuery when element becomes visible

A catch-all jQuery custom event based on an extension of it's core methods like it was proposed by different people in this thread:

(function() {
    var ev = new $.Event('event.css.jquery'),
        css = $.fn.css,
        show = $.fn.show,
        hide = $.fn.hide;

    // extends css()
    $.fn.css = function() {
        css.apply(this, arguments);
        $(this).trigger(ev);
    };

    // extends show()
    $.fn.show = function() {
        show.apply(this, arguments);
        $(this).trigger(ev);
    };

    // extends hide()
    $.fn.hide = function() {
        hide.apply(this, arguments);
        $(this).trigger(ev);
    };
})();

An external library then, uses sth like $('selector').css('property', value).

As we don't want to alter the library's code but we DO want to extend it's behavior we do sth like:

$('#element').on('event.css.jquery', function(e) {
    // ...more code here...
});

Example: user clicks on a panel that is built by a library. The library shows/hides elements based on user interaction. We want to add a sensor that shows that sth has been hidden/shown because of that interaction and should be called after the library's function.

Another example: jsfiddle.

JavaFX and OpenJDK

Try obuildfactory.

There is need to modify these scripts (contains error and don't exactly do the "thing" required), i will upload mine scripts forked from obuildfactory in next few days. and so i will also update my answer accordingly.

Until then enjoy, sir :)

SelectedValue vs SelectedItem.Value of DropDownList

SelectedValue returns the same value as SelectedItem.Value.

SelectedItem.Value and SelectedItem.Text might have different values and the performance is not a factor here, only the meanings of these properties matters.

<asp:DropDownList runat="server" ID="ddlUserTypes">
    <asp:ListItem Text="Admins" Value="1" Selected="true" />
    <asp:ListItem Text="Users" Value="2"/>
</asp:DropDownList>

Here, ddlUserTypes.SelectedItem.Value == ddlUserTypes.SelectedValue and both would return the value "1".

ddlUserTypes.SelectedItem.Text would return "Admins", which is different from ddlUserTypes.SelectedValue

edit

under the hood, SelectedValue looks like this

public virtual string SelectedValue
{
    get
    {
        int selectedIndex = this.SelectedIndex;
        if (selectedIndex >= 0)
        {
            return this.Items[selectedIndex].Value;
        }
        return string.Empty;
    }
}

and SelectedItem looks like this:

public virtual ListItem SelectedItem
{
    get
    {
        int selectedIndex = this.SelectedIndex;
        if (selectedIndex >= 0)
        {
            return this.Items[selectedIndex];
        }
        return null;
    }
}

One major difference between these two properties is that the SelectedValue has a setter also, since SelectedItem doesn't. The getter of SelectedValue is faster when writing code, and the problem of execution performance has no real reason to be discussed. Also a big advantage of SelectedValue is when using Binding expressions.

edit data binding scenario (you can't use SelectedItem.Value)

<asp:Repeater runat="server">
 <ItemTemplate>
     <asp:DropDownList ID="ddlCategories" runat="server" 
                       SelectedValue='<%# Eval("CategoryId")%>'>
     </asp:DropDownList>
 </ItemTemplate>
</asp:Repeater>

CodeIgniter - How to return Json response from controller

return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500)
            ->set_output(json_encode(array(
                    'text' => 'Error 500',
                    'type' => 'danger'
            )));

Binding a generic list to a repeater - ASP.NET

Code Behind:

public class Friends
{
    public string   ID      { get; set; }
    public string   Name    { get; set; }
    public string   Image   { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
        List <Friends> friendsList = new List<Friends>();

        foreach (var friend  in friendz)
        {
            friendsList.Add(
                new Friends { ID = friend.id, Name = friend.name }    
            );

        }

        this.rptFriends.DataSource = friendsList;
        this.rptFriends.DataBind();
}

.aspx Page

<asp:Repeater ID="rptFriends" runat="server">
            <HeaderTemplate>
                <table border="0" cellpadding="0" cellspacing="0">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                        </tr>
                    </thead>
                    <tbody>
            </HeaderTemplate>
            <ItemTemplate>
                    <tr>
                        <td><%# Eval("ID") %></td>
                        <td><%# Eval("Name") %></td>
                    </tr>
            </ItemTemplate>
            <FooterTemplate>
                    </tbody>
                </table>
            </FooterTemplate>
        </asp:Repeater>

'numpy.ndarray' object is not callable error

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:

In [16]: import numpy as np

In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()

TypeError: 'numpy.ndarray' object is not callable

If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean or pd.rolling_std to a numpy array earlier in your code.

What I mean is something like this:

In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan,  nan,  nan])

In [4]: pd.rolling_mean = np.array([1,2,3])

In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...

TypeError: 'numpy.ndarray' object is not callable

So, basically you need to search the rest of your codebase for pd.rolling_mean = ... and/or pd.rolling_std = ... to see where you may have overwritten them.


Also, if you'd like, you can put in reload(pd) just before your snippet, which should make it run by restoring the value of pd to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.

Tokenizing Error: java.util.regex.PatternSyntaxException, dangling metacharacter '*'

It is because * is used as a metacharacter to signify one or more occurences of previous character. So if i write M* then it will look for files MMMMMM..... ! Here you are using * as the only character so the compiler is looking for the character to find multiple occurences of,so it throws the exception.:)

angular 2 ngIf and CSS transition/animation

CSS only solution for modern browsers

@keyframes slidein {
    0%   {margin-left:1500px;}
    100% {margin-left:0px;}
}
.note {
    animation-name: slidein;
    animation-duration: .9s;
    display: block;
}

How to create a blank/empty column with SELECT query in oracle?

I think you should use null

SELECT CustomerName AS Customer, null AS Contact 
FROM Customers;

And Remember that Oracle

treats a character value with a length of zero as null.

How can I convert this one line of ActionScript to C#?

There is collection of Func<...> classes - Func that is probably what you are looking for:

 void MyMethod(Func<int> param1 = null) 

This defines method that have parameter param1 with default value null (similar to AS), and a function that returns int. Unlike AS in C# you need to specify type of the function's arguments.

So if you AS usage was

MyMethod(function(intArg, stringArg) { return true; }) 

Than in C# it would require param1 to be of type Func<int, siring, bool> and usage like

MyMethod( (intArg, stringArg) => { return true;} ); 

C++ Cout & Cin & System "Ambiguous"

This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.

Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.

In this case I'd ask why you're including both cstdlib and stdlib.h; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib puts them in the namespace std in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!

Anyway, your use of using namespace std (which I would recommend against, in future) means that std::system from cstdlib now conflicts with system from stdlib.h. I can't explain what's going on with std::cout and std::cin.

Try removing #include <stdlib.h> and see what happens.

If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.

DBCC SHRINKFILE on log file not reducing size even after BACKUP LOG TO DISK

Okay, here is a solution to reduce the physical size of the transaction file, but without changing the recovery mode to simple.

Within your database, locate the file_id of the log file using the following query.

SELECT * FROM sys.database_files;

In my instance, the log file is file_id 2. Now we want to locate the virtual logs in use, and do this with the following command.

DBCC LOGINFO;

Here you can see if any virtual logs are in use by seeing if the status is 2 (in use), or 0 (free). When shrinking files, empty virtual logs are physically removed starting at the end of the file until it hits the first used status. This is why shrinking a transaction log file sometimes shrinks it part way but does not remove all free virtual logs.

If you notice a status 2's that occur after 0's, this is blocking the shrink from fully shrinking the file. To get around this do another transaction log backup, and immediately run these commands, supplying the file_id found above, and the size you would like your log file to be reduced to.

-- DBCC SHRINKFILE (file_id, LogSize_MB)
DBCC SHRINKFILE (2, 100);
DBCC LOGINFO;

This will then show the virtual log file allocation, and hopefully you'll notice that it's been reduced somewhat. Because virtual log files are not always allocated in order, you may have to backup the transaction log a couple of times and run this last query again; but I can normally shrink it down within a backup or two.

VC++ fatal error LNK1168: cannot open filename.exe for writing

Restarting Visual Studio solved the problem for me.

How get an apostrophe in a string in javascript

You can use double quotes instead of single quotes:

theAnchorText = "I'm home";

Alternatively, escape the apostrophe:

theAnchorText = 'I\'m home';

The backslash tells JavaScript (this has nothing to do with jQuery, by the way) that the next character should be interpreted as "special". In this case, an apostrophe after a backslash means to use a literal apostrophe but not to end the string.

There are also other characters you can put after a backslash to indicate other special characters. For example, you can use \n for a new line, or \t for a tab.

How to make div fixed after you scroll to that div?

<script>
if($(window).width() >= 1200){
    (function($) {
        var element = $('.to_move_content'),
            originalY = element.offset().top;

        // Space between element and top of screen (when scrolling)
        var topMargin = 10;

        // Should probably be set in CSS; but here just for emphasis
        element.css('position', 'relative');

        $(window).on('scroll', function(event) {
            var scrollTop = $(window).scrollTop();

            element.stop(false, false).animate({
                top: scrollTop < originalY
                    ? 0
                    : scrollTop - originalY + topMargin
            }, 0);
        });
    })(jQuery);
}

Try this ! just add class .to_move_content to you div

Is there a way to disable initial sorting for jquery DataTables?

As per latest api docs:

$(document).ready(function() {
    $('#example').dataTable({
        "order": []
    });
});

More Info

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

I was facing the same issue, here is line from error

File "/usr/lib/python3/dist-packages/numpy/lib/npyio.py", line 260, in __getitem__

So i solve the issue by updating "npyio.py" file. In npyio.py line 196 assigning value to allow_pickle so i update this line as

self.allow_pickle = True

Flutter : Vertically center column

CrossAlignment.center is using the Width of the 'Child Widget' to center itself and hence gets rendered at the start of the page.

When the Column is centered within the page body's 'Center Container' , the CrossAlignment.center uses page body's 'Center' as reference and renders the widget at the center of the page

enter image description here

Code

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
    title:"DynamicWidgetApp",
    home:DynamicWidgetApp(),

));

class DynamicWidgetApp extends StatefulWidget{
  @override
  DynamicWidgetAppState createState() => DynamicWidgetAppState();
  }

class  DynamicWidgetAppState extends State<DynamicWidgetApp>{
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: Center(
     //Removing body:Center will change the reference
    // and render the widget at the start of the page 
        child: Column(
            mainAxisAlignment : MainAxisAlignment.center,
            crossAxisAlignment : CrossAxisAlignment.center,
            children: [
              Text("My Centered Widget"),
            ]
          ),
      ),
      floatingActionButton: FloatingActionButton(
        // onPressed: ,
        child : Icon(Icons.add),
      ),
      );
    }
  }

How do you share code between projects/solutions in Visual Studio?

You could include the same project in more than one solution, but you're guaranteed to run into problems sometime down the road (relative paths can become invalid when you move directories around for example)

After years of struggling with this, I finally came up with a workable solution, but it requires you to use Subversion for source control (which is not a bad thing)

At the directory level of your solution, add a svn:externals property pointing to the projects you want to include in your solution. Subversion will pull the project from the repository and store it in a subfolder of your solution file. Your solution file can simply use relative paths to refer to your project.

If I find some more time, I'll explain this in detail.

How to Inspect Element using Safari Browser

Press CMD + , than click in show develop menu in menu bar. After that click Option + CMD + i to open and close the inspector

enter image description here

How can I send an xml body using requests library?

Just send xml bytes directly:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import requests

xml = """<?xml version='1.0' encoding='utf-8'?>
<a>?</a>"""
headers = {'Content-Type': 'application/xml'} # set what your server accepts
print requests.post('http://httpbin.org/post', data=xml, headers=headers).text

Output

{
  "origin": "x.x.x.x",
  "files": {},
  "form": {},
  "url": "http://httpbin.org/post",
  "args": {},
  "headers": {
    "Content-Length": "48",
    "Accept-Encoding": "identity, deflate, compress, gzip",
    "Connection": "keep-alive",
    "Accept": "*/*",
    "User-Agent": "python-requests/0.13.9 CPython/2.7.3 Linux/3.2.0-30-generic",
    "Host": "httpbin.org",
    "Content-Type": "application/xml"
  },
  "json": null,
  "data": "<?xml version='1.0' encoding='utf-8'?>\n<a>\u0431</a>"
}

Android Overriding onBackPressed()

Just call the onBackPressed() method in the activity you want to show the dialog and inside it show your dialog.

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

var userPasswordString = new Buffer(baseAuth, 'base64').toString('ascii');

Change this line from your code to this -

var userPasswordString = Buffer.from(baseAuth, 'base64').toString('ascii');

or in my case, I gave the encoding in reverse order

var userPasswordString = Buffer.from(baseAuth, 'utf-8').toString('base64');

convert month from name to number

It may be easiest to create a fake date so you can use the date function.

Excellent reference here: http://php.net/manual/en/function.date.php

Example:

<?
$month = 7;

$tempDate = mktime(0, 0, 0, $month, 1, 1900); 

echo date("m",$tempDate);


?>

Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

Just create the database using createdb CLI tool:

PGHOST="my.database.domain.com"
PGUSER="postgres"
PGDB="mydb"
createdb -h $PGHOST -p $PGPORT -U $PGUSER $PGDB

If the database exists, it will return an error:

createdb: database creation failed: ERROR:  database "mydb" already exists

How can I create a dropdown menu from a List in Tkinter?

To create a "drop down menu" you can use OptionMenu in tkinter

Example of a basic OptionMenu:

from Tkinter import *

master = Tk()

variable = StringVar(master)
variable.set("one") # default value

w = OptionMenu(master, variable, "one", "two", "three")
w.pack()

mainloop()

More information (including the script above) can be found here.


Creating an OptionMenu of the months from a list would be as simple as:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

mainloop()

In order to retrieve the value the user has selected you can simply use a .get() on the variable that we assigned to the widget, in the below case this is variable:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

def ok():
    print ("value is:" + variable.get())

button = Button(master, text="OK", command=ok)
button.pack()

mainloop()

I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.

C# - How to convert string to char?

Use:

string str = "Hello";
char[] characters = str.ToCharArray();

If you have a single character string, You can also try

string str = "A";
char character = char.Parse(str);    

//OR 
string str = "A";
char character = str.ToCharArray()[0];

If (Array.Length == 0)

You can use

if (array == null || array.Length == 0)

OR

if (!(array != null && array.Length != 0))

NOTE!!!!! To insure that c# will implement the short circuit correctly; you have to compare that the object with NULL before you go to the children compare of the object.

C# 7.0 and above

if(!(array?.Length != 0))

What is IllegalStateException?

public class UserNotFoundException extends Exception {
    public UserNotFoundException(String message) {
        super(message)

Drawable image on a canvas

also you can use this way. it will change your big drawble fit to your canvas:

Resources res = getResources();
Bitmap bitmap = BitmapFactory.decodeResource(res, yourDrawable);
yourCanvas.drawBitmap(bitmap, 0, 0, yourPaint);

Phone: numeric keyboard for text input

 <input type="text" inputmode="decimal">

it will give u text input using numeric key-pad

How do I rename a MySQL schema?

If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE

Edit: On the model overview it's under Physical Schemata

Screenshot:

enter image description here

Converting any object to a byte array in java

As i've mentioned in other, similar questions, you may want to consider compressing the data as the default java serialization is a bit verbose. you do this by putting a GZIPInput/OutputStream between the Object streams and the Byte streams.

Iteration over std::vector: unsigned vs signed index variable

Obscure but important detail: if you say "for(auto it)" as follows, you get a copy of the object, not the actual element:

struct Xs{int i} x;
x.i = 0;
vector <Xs> v;
v.push_back(x);
for(auto it : v)
    it.i = 1;         // doesn't change the element v[0]

To modify the elements of the vector, you need to define the iterator as a reference:

for(auto &it : v)

What is the best IDE to develop Android apps in?

An IDE which supports Android development is Processing for Android: http://wiki.processing.org/w/Android. Processing is its own language but it's easy to learn. Processing for Android requires the JDK and Android SDK to be installed but runs on its own. It runs on Linux, Mac OSX and Windows (on a side note: one can develop a desktop app in Processing and then compile it to target any of these operating systems). Its development is ongoing but it works. It's especially good for quickly sketching up an idea and running it on your Android phone (even if you plan to develop it further in another IDE).

There is an active support forum here: http://forum.processing.org/android-processing.

How to transform numpy.matrix or array to scipy sparse matrix

In Python, the Scipy library can be used to convert the 2-D NumPy matrix into a Sparse matrix. SciPy 2-D sparse matrix package for numeric data is scipy.sparse

The scipy.sparse package provides different Classes to create the following types of Sparse matrices from the 2-dimensional matrix:

  1. Block Sparse Row matrix
  2. A sparse matrix in COOrdinate format.
  3. Compressed Sparse Column matrix
  4. Compressed Sparse Row matrix
  5. Sparse matrix with DIAgonal storage
  6. Dictionary Of Keys based sparse matrix.
  7. Row-based list of lists sparse matrix
  8. This class provides a base class for all sparse matrices.

CSR (Compressed Sparse Row) or CSC (Compressed Sparse Column) formats support efficient access and matrix operations.

Example code to Convert Numpy matrix into Compressed Sparse Column(CSC) matrix & Compressed Sparse Row (CSR) matrix using Scipy classes:

import sys                 # Return the size of an object in bytes
import numpy as np         # To create 2 dimentional matrix
from scipy.sparse import csr_matrix, csc_matrix 
# csr_matrix: used to create compressed sparse row matrix from Matrix
# csc_matrix: used to create compressed sparse column matrix from Matrix

create a 2-D Numpy matrix

A = np.array([[1, 0, 0, 0, 0, 0],\
              [0, 0, 2, 0, 0, 1],\
              [0, 0, 0, 2, 0, 0]])
print("Dense matrix representation: \n", A)
print("Memory utilised (bytes): ", sys.getsizeof(A))
print("Type of the object", type(A))

Print the matrix & other details:

Dense matrix representation: 
 [[1 0 0 0 0 0]
 [0 0 2 0 0 1]
 [0 0 0 2 0 0]]
Memory utilised (bytes):  184
Type of the object <class 'numpy.ndarray'>

Converting Matrix A to the Compressed sparse row matrix representation using csr_matrix Class:

S = csr_matrix(A)
print("Sparse 'row' matrix: \n",S)
print("Memory utilised (bytes): ", sys.getsizeof(S))
print("Type of the object", type(S))

The output of print statements:

Sparse 'row' matrix:
(0, 0) 1
(1, 2) 2
(1, 5) 1
(2, 3) 2
Memory utilised (bytes): 56
Type of the object: <class 'scipy.sparse.csr.csc_matrix'>

Converting Matrix A to Compressed Sparse Column matrix representation using csc_matrix Class:

S = csc_matrix(A)
print("Sparse 'column' matrix: \n",S)
print("Memory utilised (bytes): ", sys.getsizeof(S))
print("Type of the object", type(S))

The output of print statements:

Sparse 'column' matrix:
(0, 0) 1
(1, 2) 2
(2, 3) 2
(1, 5) 1
Memory utilised (bytes): 56
Type of the object: <class 'scipy.sparse.csc.csc_matrix'>

As it can be seen the size of the compressed matrices is 56 bytes and the original matrix size is 184 bytes.

For a more detailed explanation and code examples please refer to this article: https://limitlessdatascience.wordpress.com/2020/11/26/sparse-matrix-in-machine-learning/

Visual Studio can't 'see' my included header files

I encountered this issue, but the solutions provided didn't directly help me, so I'm sharing how I got myself into a similar situation and temporarily resolved it.

I created a new project within an existing solution and copy & pasted the Header and CPP file from another project within that solution that I needed to include in my new project through the IDE. Intellisense displayed an error suggesting it could not resolve the reference to the header file and compiling the code failed with the same error too.

After reading the posts here, I checked the project folder with Windows File Explorer and only the main.cpp file was found. For some reason, my copy and paste of the header file and CPP file were just a reference? (I assume) and did not physically copy the file into the new project file.

I deleted the files from the Project view within Visual Studio and I used File Explorer to copy the files that I needed to the project folder/directory. I then referenced the other solutions posted here to "include files in project" by showing all files and this resolved the problem.

It boiled down to the files not being physically in the Project folder/directory even though they were shown correctly within the IDE.

Please Note I understand duplicating code is not best practice and my situation is purely a learning/hobby project. It's probably in my best interest and anyone else who ended up in a similar situation to use the IDE/project/Solution setup correctly when reusing code from other projects - I'm still learning and I'll figure this out one day!

AngularJS multiple filter with custom filter function

In view file (HTML or EJS)

<div ng-repeat="item in vm.itemList  | filter: myFilter > </div>

and In Controller

$scope.myFilter = function(item) {
return (item.propertyA === 'value' || item.propertyA === 'value');
}

How do you pass a function as a parameter in C?

This question already has the answer for defining function pointers, however they can get very messy, especially if you are going to be passing them around your application. To avoid this unpleasantness I would recommend that you typedef the function pointer into something more readable. For example.

typedef void (*functiontype)();

Declares a function that returns void and takes no arguments. To create a function pointer to this type you can now do:

void dosomething() { }

functiontype func = &dosomething;
func();

For a function that returns an int and takes a char you would do

typedef int (*functiontype2)(char);

and to use it

int dosomethingwithchar(char a) { return 1; }

functiontype2 func2 = &dosomethingwithchar
int result = func2('a');

There are libraries that can help with turning function pointers into nice readable types. The boost function library is great and is well worth the effort!

boost::function<int (char a)> functiontype2;

is so much nicer than the above.

Shell script to send email

sendmail works for me on the mac (10.6.8)

echo "Hello" | sendmail -f [email protected] [email protected]

How to get Python requests to trust a self signed SSL certificate?

Case where multiple certificates are needed was solved as follows: Concatenate the multiple root pem files, myCert-A-Root.pem and myCert-B-Root.pem, to a file. Then set the requests REQUESTS_CA_BUNDLE var to that file in my ./.bash_profile.

$ cp myCert-A-Root.pem ca_roots.pem
$ cat myCert-B-Root.pem >> ca_roots.pem
$ echo "export REQUESTS_CA_BUNDLE=~/PATH_TO/CA_CHAIN/ca_roots.pem" >> ~/.bash_profile ; source ~/.bash_profile

want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format

Here's a simple snippet working in Java 8 and using the "new" date and time API LocalDateTime:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss.SS");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now)); 

How to get the selected date of a MonthCalendar control in C#

Using SelectionRange you will get the Start and End date.

private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
    var startDate = monthCalendar1.SelectionRange.Start.ToString("dd MMM yyyy");
    var endDate = monthCalendar1.SelectionRange.End.ToString("dd MMM yyyy");
}

If you want to update the maximum number of days that can be selected, then set MaxSelectionCount property. The default is 7.

// Only allow 21 days to be selected at the same time.
monthCalendar1.MaxSelectionCount = 21;

HTML / CSS Popup div on text click

You can simply use jQuery UI Dialog

Example:

_x000D_
_x000D_
$(function() {_x000D_
  $("#dialog").dialog();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8" />_x000D_
  <title>jQuery UI Dialog - Default functionality</title>_x000D_
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />_x000D_
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>_x000D_
  <link rel="stylesheet" href="/resources/demos/style.css" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="dialog" title="Basic dialog">_x000D_
    <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>_x000D_
  </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to add Class in <li> using wp_nav_menu() in Wordpress?

Without walker menu it's not possible to directly add it. You can, however, add it by javascript.

$('#menu > li').addClass('class_name');

Static method in a generic class?

You can't use a class's generic type parameters in static methods or static fields. The class's type parameters are only in scope for instance methods and instance fields. For static fields and static methods, they are shared among all instances of the class, even instances of different type parameters, so obviously they cannot depend on a particular type parameter.

It doesn't seem like your problem should require using the class's type parameter. If you describe what you are trying to do in more detail, maybe we can help you find a better way to do it.

Sort a list of tuples by 2nd item (integer value)

As a python neophyte, I just wanted to mention that if the data did actually look like this:

data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]

then sorted() would automatically sort by the second element in the tuple, as the first elements are all identical.

Unknown URL content://downloads/my_downloads

The exception is caused by disabled Download Manager. And there is no way to activate/deactivate Download Manager directly, since it's system application and we don't have access to it.

Only alternative way is redirect user to settings of Download Manager Application.

try {
     //Open the specific App Info page:
     Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
     intent.setData(Uri.parse("package:" + "com.android.providers.downloads"));
     startActivity(intent);

} catch ( ActivityNotFoundException e ) {
     e.printStackTrace();

     //Open the generic Apps page:
     Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
     startActivity(intent);
}

How to ping ubuntu guest on VirtualBox

Using NAT (the default) this is not possible. Bridged Networking should allow it. If bridged does not work for you (this may be the case when your network adminstration does not allow multiple IP addresses on one physical interface), you could try 'Host-only networking' instead.

For configuration of Host-only here is a quote from the vbox manual(which is pretty good). http://www.virtualbox.org/manual/ch06.html:

For host-only networking, like with internal networking, you may find the DHCP server useful that is built into VirtualBox. This can be enabled to then manage the IP addresses in the host-only network since otherwise you would need to configure all IP addresses statically.

In the VirtualBox graphical user interface, you can configure all these items in the global settings via "File" -> "Settings" -> "Network", which lists all host-only networks which are presently in use. Click on the network name and then on the "Edit" button to the right, and you can modify the adapter and DHCP settings.

PHP __get and __set magic methods

To expand on Berry's answer, that setting the access level to protected allows __get and __set to be used with explicitly declared properties (when accessed outside the class, at least) and the speed being considerably slower, I'll quote a comment from another question on this topic and make a case for using it anyway:

I agree that __get is more slow to a custom get function (doing the same things), this is 0.0124455 the time for __get() and this 0.0024445 is for custom get() after 10000 loops. – Melsi Nov 23 '12 at 22:32 Best practice: PHP Magic Methods __set and __get

According to Melsi's tests, considerably slower is about 5 times slower. That is definitely considerably slower, but also note that the tests show that you can still access a property with this method 10,000 times, counting time for loop iteration, in roughly 1/100 of a second. It is considerably slower in comparison with actual get and set methods defined, and that is an understatement, but in the grand scheme of things, even 5 times slower is never actually slow.

The computing time of the operation is still negligible and not worth considering in 99% of real world applications. The only time it should really be avoided is when you're actually going to be accessing the properties over 10,000 times in a single request. High traffic sites are doing something really wrong if they can't afford throwing a few more servers up to keep their applications running. A single line text ad on the footer of a high traffic site where the access rate becomes an issue could probably pay for a farm of 1,000 servers with that line of text. The end user is never going to be tapping their fingers wondering what is taking the page so long to load because your application's property access takes a millionth of a second.

I say this speaking as a developer coming from a background in .NET, but invisible get and set methods to the consumer is not .NET's invention. They simply aren't properties without them, and these magic methods are PHP's developer's saving grace for even calling their version of properties "properties" at all. Also, the Visual Studio extension for PHP does support intellisense with protected properties, with that trick in mind, I'd think. I would think with enough developers using the magic __get and __set methods in this way, the PHP developers would tune up the execution time to cater to the developer community.

Edit: In theory, protected properties seemed like it'd work in most situation. In practice, it turns out that there's a lot of times you're going to want to use your getters and setters when accessing properties within the class definition and extended classes. A better solution is a base class and interface for when extending other classes, so you can just copy the few lines of code from the base class into the implementing class. I'm doing a bit more with my project's base class, so I don't have an interface to provide right now, but here is the untested stripped down class definition with magic property getting and setting using reflection to remove and move the properties to a protected array:

/** Base class with magic property __get() and __set() support for defined properties. */
class Component {
    /** Gets the properties of the class stored after removing the original
     * definitions to trigger magic __get() and __set() methods when accessed. */
    protected $properties = array();

    /** Provides property get support. Add a case for the property name to
     * expand (no break;) or replace (break;) the default get method. When
     * overriding, call parent::__get($name) first and return if not null,
     * then be sure to check that the property is in the overriding class
     * before doing anything, and to implement the default get routine. */
    public function __get($name) {
        $caller = array_shift(debug_backtrace());
        $max_access = ReflectionProperty::IS_PUBLIC;
        if (is_subclass_of($caller['class'], get_class($this)))
            $max_access = ReflectionProperty::IS_PROTECTED;
        if ($caller['class'] == get_class($this))
            $max_access = ReflectionProperty::IS_PRIVATE;
        if (!empty($this->properties[$name])
            && $this->properties[$name]->class == get_class()
            && $this->properties[$name]->access <= $max_access)
            switch ($name) {
                default:
                    return $this->properties[$name]->value;
            }
    }

    /** Provides property set support. Add a case for the property name to
     * expand (no break;) or replace (break;) the default set method. When
     * overriding, call parent::__set($name, $value) first, then be sure to
     * check that the property is in the overriding class before doing anything,
     * and to implement the default set routine. */
    public function __set($name, $value) {
        $caller = array_shift(debug_backtrace());
        $max_access = ReflectionProperty::IS_PUBLIC;
        if (is_subclass_of($caller['class'], get_class($this)))
            $max_access = ReflectionProperty::IS_PROTECTED;
        if ($caller['class'] == get_class($this))
            $max_access = ReflectionProperty::IS_PRIVATE;
        if (!empty($this->properties[$name])
            && $this->properties[$name]->class == get_class()
            && $this->properties[$name]->access <= $max_access)
            switch ($name) {
                default:
                    $this->properties[$name]->value = $value;
            }
    }

    /** Constructor for the Component. Call first when overriding. */
    function __construct() {
        // Removing and moving properties to $properties property for magic
        // __get() and __set() support.
        $reflected_class = new ReflectionClass($this);
        $properties = array();
        foreach ($reflected_class->getProperties() as $property) {
            if ($property->isStatic()) { continue; }
            $properties[$property->name] = (object)array(
                'name' => $property->name, 'value' => $property->value
                , 'access' => $property->getModifier(), 'class' => get_class($this));
            unset($this->{$property->name}); }
        $this->properties = $properties;
    }
}

My apologies if there are any bugs in the code.

How to repair a serialized string which has been corrupted by an incorrect byte count length?

You can fix broken serialize string using following function, with multibyte character handling.

function repairSerializeString($value)
{

    $regex = '/s:([0-9]+):"(.*?)"/';

    return preg_replace_callback(
        $regex, function($match) {
            return "s:".mb_strlen($match[2]).":\"".$match[2]."\""; 
        },
        $value
    );
}

How do I enter a multi-line comment in Perl?

I found it. Perl has multi-line comments:

#!/usr/bin/perl

use strict;

use warnings;

=for comment

Example of multiline comment.

Example of multiline comment.

=cut

print "Multi Line Comment Example \n";

Convert HttpPostedFileBase to byte[]

As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:

MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();

It's easy enough to write the equivalent of CopyTo in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream.

For efficient purposes you could check whether the stream returned is already a MemoryStream:

byte[] data;
using (Stream inputStream = model.File.InputStream)
{
    MemoryStream memoryStream = inputStream as MemoryStream;
    if (memoryStream == null)
    {
        memoryStream = new MemoryStream();
        inputStream.CopyTo(memoryStream);
    }
    data = memoryStream.ToArray();
}

Git push error pre-receive hook declined

I've faced the same issue, this is because I am pushing my code directly in the master branch, and I don't have rights for this. So I push my code in a new branch and after that, I created a pull request to merge with master.

Nginx 403 error: directory index of [folder] is forbidden

For me the problem was that any routes other than the base route were working, adding this line fixed my problem:

index           index.php;

Full thing:

server {

    server_name example.dev;
    root /var/www/example/public;
    index           index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include /etc/nginx/fastcgi_params;
        fastcgi_pass  127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

Kill a Process by Looking up the Port being used by it from a .BAT

Open command prompt and run the following commands

 C:\Users\username>netstat -o -n -a | findstr 0.0:3000
   TCP    0.0.0.0:3000      0.0.0.0:0              LISTENING       3116

C:\Users\username>taskkill /F /PID 3116

, here 3116 is the process ID

Why does the 260 character path length limit exist in Windows?

Quoting this article https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#maximum-path-length-limitation

Maximum Path Length Limitation

In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters. A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character. For example, the maximum path on drive D is "D:\some 256-character path string<NUL>" where "<NUL>" represents the invisible terminating null character for the current system codepage. (The characters < > are used here for visual clarity and cannot be part of a valid path string.)

Now we see that it is 1+2+256+1 or [drive][:\][path][null] = 260. One could assume that 256 is a reasonable fixed string length from the DOS days. And going back to the DOS APIs we realize that the system tracked the current path per drive, and we have 26 (32 with symbols) maximum drives (and current directories).

The INT 0x21 AH=0x47 says “This function returns the path description without the drive letter and the initial backslash.” So we see that the system stores the CWD as a pair (drive, path) and you ask for the path by specifying the drive (1=A, 2=B, …), if you specify a 0 then it assumes the path for the drive returned by INT 0x21 AH=0x15 AL=0x19. So now we know why it is 260 and not 256, because those 4 bytes are not stored in the path string.

Why a 256 byte path string, because 640K is enough RAM.

How can I get phone serial number (IMEI)

try this

 final TelephonyManager tm =(TelephonyManager)getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);

  String deviceid = tm.getDeviceId();

Error executing command 'ant' on Mac OS X 10.9 Mavericks when building for Android with PhoneGap/Cordova

The error message proved to be true as Apache Ant isn't in the path of Mac OS X Mavericks anymore.

Bulletproof solution:

  1. Download and install Homebrew by executing following command in terminal:

    ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

  2. Install Apache Ant via Homebrew by executing

    brew install ant

Run the PhoneGap build again and it should successfully compile and install your Android app.

What are the best practices for using a GUID as a primary key, specifically regarding performance?

Most of the times it should not be used as the primary key for a table because it really hit the performance of the database. useful links regarding GUID impact on performance and as a primary key.

  1. https://www.sqlskills.com/blogs/kimberly/disk-space-is-cheap/
  2. https://www.sqlskills.com/blogs/kimberly/guids-as-primary-keys-andor-the-clustering-key/

Show a child form in the centre of Parent form in C#

You need this:

Replace Me with this.parent, but you need to set parent before you show that form.

  Private Sub ÜberToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ÜberToolStripMenuItem.Click

        'About.StartPosition = FormStartPosition.Manual ' !!!!!
        About.Location = New Point(Me.Location.X + Me.Width / 2 - About.Width / 2, Me.Location.Y + Me.Height / 2 - About.Height / 2)
        About.Show()
    End Sub

jquery beforeunload when closing (not leaving) the page?

Try this, loading data via ajax and displaying through return statement.

<script type="text/javascript">
function closeWindow(){

    var Data = $.ajax({
        type : "POST",
        url : "file.txt",  //loading a simple text file for sample.
        cache : false,
        global : false,
        async : false,
        success : function(data) {
            return data;
        }

    }).responseText;


    return "Are you sure you want to leave the page? You still have "+Data+" items in your shopping cart";
}

window.onbeforeunload = closeWindow;
</script>

What is the easiest way to push an element to the beginning of the array?

array = ["foo"]
array.unshift "bar"
array
=> ["bar", "foo"]

be warned, it's destructive!

How can I add NSAppTransportSecurity to my info.plist file?

Xcode 8.2, iOS 10

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

How can I trigger another job from a jenkins pipeline (jenkinsfile) with GitHub Org Plugin?

Use build job plugin for that task in order to trigger other jobs from jenkins file. You can add variety of logic to your execution such as parallel ,node and agents options and steps for triggering external jobs. I gave some easy-to-read cookbook example for that.

1.example for triggering external job from jenkins file with conditional example:

if (env.BRANCH_NAME == 'master') {
  build job:'exactJobName' , parameters:[
    string(name: 'keyNameOfParam1',value: 'valueOfParam1')
    booleanParam(name: 'keyNameOfParam2',value:'valueOfParam2')
 ]
}

2.example triggering multiple jobs from jenkins file with conditionals example:

 def jobs =[
    'job1Title'{
    if (env.BRANCH_NAME == 'master') {
      build job:'exactJobName' , parameters:[
        string(name: 'keyNameOfParam1',value: 'valueNameOfParam1')
        booleanParam(name: 'keyNameOfParam2',value:'valueNameOfParam2')
     ]
    }
},
    'job2Title'{
    if (env.GIT_COMMIT == 'someCommitHashToPerformAdditionalTest') {
      build job:'exactJobName' , parameters:[
        string(name: 'keyNameOfParam3',value: 'valueOfParam3')
        booleanParam(name: 'keyNameOfParam4',value:'valueNameOfParam4')
        booleanParam(name: 'keyNameOfParam5',value:'valueNameOfParam5')
     ]
    }
}

Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1

I have been experiencing this issue when debugging using NetBeans, even executing the actual jar file. Antivirus would block sending email. You should temporarily disable your antivirus during debugging or exclude NetBeans and the actual jar file from being scanned. In my case, I'm using Avast.

See this link on how to Exclude : How to Add File/Website Exception into avast! Antivirus 2014

It works for me.

How can I get the intersection, union, and subset of arrays in Ruby?

I assume X and Y are arrays? If so, there's a very simple way to do this:

x = [1, 1, 2, 4]
y = [1, 2, 2, 2]

# intersection
x & y            # => [1, 2]

# union
x | y            # => [1, 2, 4]

# difference
x - y            # => [4]

Source

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel

You might changed the IIS features settings.The easy steps to resolve by open command prompt with run as administrator(For Windows Server 2008) and run the command C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -iru this will set up ASP.Net 4.0 ,Then Reset the IIS by the command iisreset

References: https://support.plesk.com/hc/en-us/articles/213392249-ASP-website-shows-error-Could-not-load-type-System-ServiceModel-Activation-HttpModule-from-assembly

Artisan, creating tables in database

Migration files must match the pattern *_*.php, or else they won't be found. Since users.php does not match this pattern (it has no underscore), this file will not be found by the migrator.

Ideally, you should be creating your migration files using artisan:

php artisan make:migration create_users_table

This will create the file with the appropriate name, which you can then edit to flesh out your migration. The name will also include the timestamp, to help the migrator determine the order of migrations.

You can also use the --create or --table switches to add a little bit more boilerplate to help get you started:

php artisan make:migration create_users_table --create=users

The documentation on migrations can be found here.

SQL DELETE with INNER JOIN

Add .* to s in your first line.

Try:

DELETE s.* FROM spawnlist s
INNER JOIN npc n ON s.npc_templateid = n.idTemplate
WHERE (n.type = "monster");

CSS Change List Item Background Color with Class

This is an issue of selector specificity. (The selector .selected is less specific than ul.nav li.)

To fix, use as much specificity in the overriding rule as in the original:

ul.nav li {
 background-color:blue;
}
ul.nav li.selected {
 background-color:red;
}

You might also consider nixing the ul, unless there will be other .navs. So:

.nav li {
 background-color:blue;
}
.nav li.selected {
 background-color:red;
}

That's a bit cleaner, less typing, and fewer bits.

How to get database structure in MySQL via query

That's the SHOW CREATE TABLE query. You can query the SCHEMA TABLES, too.

SHOW CREATE TABLE YourTableName;

Android Studio build fails with "Task '' not found in root project 'MyProject'."

Apparently this issue caused by Android Studio on the various situation but the reason is build error When importing an existing project into android studio.

In my case, I've imported my exist project where I was supposed to install few build tools then finally build configuration was done with error. In this case, just do the following things

  1. Close the current project
  2. File>New>Import Project (Don't use the open recent project)

    Note: I'm sure this kind of error is not on source code when this happened on Import project.

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

The problem in my case was that the database name was incorrect.
I solved the problem by referring the correct database name in the field as below

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/myDatabase</property>

Transition color fade on hover?

What do you want to fade? The background or color attribute?

Currently you're changing the background color, but telling it to transition the color property. You can use all to transition all properties.

.clicker { 
    -moz-transition: all .2s ease-in;
    -o-transition: all .2s ease-in;
    -webkit-transition: all .2s ease-in;
    transition: all .2s ease-in;
    background: #f5f5f5; 
    padding: 20px;
}

.clicker:hover { 
    background: #eee;
}

Otherwise just use transition: background .2s ease-in.

When should I use curly braces for ES6 import?

The curly braces are used only for import when export is named. If the export is default then curly braces are not used for import.

How to view an HTML file in the browser with Visual Studio Code

Open custom Chrome with URL from prompt

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "Open Chrome",
      "type": "process",
      "windows": {
        "command": "${config:chrome.executable}"
      },
      "args": ["--user-data-dir=${config:chrome.profileDir}", "${input:url}"],
      "problemMatcher": []
    }
  ],
  "inputs": [
    {
      "id": "url",
      "description": "Which URL?",
      "default": "http://localhost:8080",
      "type": "promptString"
    }
  ]
}

Open custom Chrome with active file

{
  "label": "Open active file in Chrome",
  "type": "process",
  "command": "chrome.exe",
  "windows": {
    "command": "${config:chrome.executable}"
  },
  "args": ["--user-data-dir=${config:chrome.profileDir}", "${file}"],
  "problemMatcher": []
},

Notes

  • if necessary, replace windows property by other OS
  • replace ${config:chrome.executable} with your custom chrome location, e.g. "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"
  • replace ${config:chrome.profileDir} with your custome chrome profile directory, e.g. "C:/My/Data/chrome/profile" or leave it out
  • You can keep the variables like above if you want. To do so, add following entries in settings.json - user or workspace - , adjust paths to your needs:
"chrome.executable": "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe",
"chrome.profileDir": "C:/My/Data/chrome/profile"
  • You could re-use these variables e.g. in launch.json for debugging purposes: "runtimeExecutable": "${config:chrome.executable}"

I want to truncate a text or line with ellipsis using JavaScript

This will put the ellipsis in the center of the line:

function truncate( str, max, sep ) {

    // Default to 10 characters
    max = max || 10;

    var len = str.length;
    if(len > max){

        // Default to elipsis
        sep = sep || "...";

        var seplen = sep.length;

        // If seperator is larger than character limit,
        // well then we don't want to just show the seperator,
        // so just show right hand side of the string.
        if(seplen > max) {
            return str.substr(len - max);
        }

        // Half the difference between max and string length.
        // Multiply negative because small minus big.
        // Must account for length of separator too.
        var n = -0.5 * (max - len - seplen);

        // This gives us the centerline.
        var center = len/2;

        var front = str.substr(0, center - n);
        var back = str.substr(len - center + n); // without second arg, will automatically go to end of line.

        return front + sep + back;

    }

    return str;
}

console.log( truncate("123456789abcde") ); // 123...bcde (using built-in defaults) 
console.log( truncate("123456789abcde", 8) ); // 12...cde (max of 8 characters) 
console.log( truncate("123456789abcde", 12, "_") ); // 12345_9abcde (customize the separator) 

For example:

1234567890 --> 1234...8910

And:

A really long string --> A real...string

Not perfect, but functional. Forgive the over-commenting... for the noobs.

Java 8 forEach with index

Since you are iterating over an indexable collection (lists, etc.), I presume that you can then just iterate with the indices of the elements:

IntStream.range(0, params.size())
  .forEach(idx ->
    query.bind(
      idx,
      params.get(idx)
    )
  )
;

The resulting code is similar to iterating a list with the classic i++-style for loop, except with easier parallelizability (assuming, of course, that concurrent read-only access to params is safe).

How to select only the first rows for each unique value of a column?

This will give you one row of each duplicate row. It will also give you the bit-type columns, and it works at least in MS Sql Server.

(select cname, address 
from (
  select cname,address, rn=row_number() over (partition by cname order by cname) 
  from customeraddresses  
) x 
where rn = 1) order by cname

If you want to find all the duplicates instead, just change the rn= 1 to rn > 1. Hope this helps

How can I generate a list or array of sequential integers in Java?

You could use Guava Ranges

You can get a SortedSet by using

ImmutableSortedSet<Integer> set = Ranges.open(1, 5).asSet(DiscreteDomains.integers());
// set contains [2, 3, 4]

Asp.net Validation of viewstate MAC failed

I had this same issue and it was due to a Gridview (generated from a vb code) on the page which had sorting enabled. Disabling Sort fixed my issue. I do not have this problem with the gridviews created using a SQLdatasource.

Converting any string into camel case

In Scott’s specific case I’d go with something like:

String.prototype.toCamelCase = function() {
    return this.replace(/^([A-Z])|\s(\w)/g, function(match, p1, p2, offset) {
        if (p2) return p2.toUpperCase();
        return p1.toLowerCase();        
    });
};

'EquipmentClass name'.toCamelCase()  // -> equipmentClassName
'Equipment className'.toCamelCase()  // -> equipmentClassName
'equipment class name'.toCamelCase() // -> equipmentClassName
'Equipment Class Name'.toCamelCase() // -> equipmentClassName

The regex will match the first character if it starts with a capital letter, and any alphabetic character following a space, i.e. 2 or 3 times in the specified strings.

By spicing up the regex to /^([A-Z])|[\s-_](\w)/g it will also camelize hyphen and underscore type names.

'hyphen-name-format'.toCamelCase()     // -> hyphenNameFormat
'underscore_name_format'.toCamelCase() // -> underscoreNameFormat

printf() prints whole array

But still, the memory address for each letter in this address is different.

Memory address is different but as its array of characters they are sequential. When you pass address of first element and use %s, printf will print all characters starting from given address until it finds '\0'.

Problems with jQuery getJSON using local files in Chrome

You can place your json to js file and save it to global variable. It is not asynchronous, but it can help.

mysql query order by multiple items

Sort by picture and then by activity:

SELECT some_cols
FROM `prefix_users`
WHERE (some conditions)
ORDER BY pic_set, last_activity DESC;

Importing CSV data using PHP/MySQL

I answered a virtually identical question just the other day: Save CSV files into mysql database

MySQL has a feature LOAD DATA INFILE, which allows it to import a CSV file directly in a single SQL query, without needing it to be processed in a loop via your PHP program at all.

Simple example:

<?php
$query = <<<eof
    LOAD DATA INFILE '$fileName'
     INTO TABLE tableName
     FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '"'
     LINES TERMINATED BY '\n'
    (field1,field2,field3,etc)
eof;

$db->query($query);
?>

It's as simple as that.

No loops, no fuss. And much much quicker than parsing it in PHP.

MySQL manual page here: http://dev.mysql.com/doc/refman/5.1/en/load-data.html

Hope that helps

How to add column to numpy array

I add a new column with ones to a matrix array in this way:

Z = append([[1 for _ in range(0,len(Z))]], Z.T,0).T

Maybe it is not that efficient?

How do I execute a MS SQL Server stored procedure in java/jsp, returning table data?

FWIW, sp_test will not be returning anything but an integer (all SQL Server stored procs just return an integer) and no result sets on the wire (since no SELECT statements). To get the output of the PRINT statements, you normally use the InfoMessage event on the connection (not the command) in ADO.NET.

Java method: Finding object in array list given a known attribute value

I solved this using java 8 lambdas

int dogId = 2;

return dogList.stream().filter(dog-> dogId == dog.getId()).collect(Collectors.toList()).get(0);

An efficient way to Base64 encode a byte array?

You could use the String Convert.ToBase64String(byte[]) to encode the byte array into a base64 string, then Byte[] Convert.FromBase64String(string) to convert the resulting string back into a byte array.

Correct way to write loops for promise.

Bergi's suggested function is really nice:

var promiseWhile = Promise.method(function(condition, action) {
      if (!condition()) return;
    return action().then(promiseWhile.bind(null, condition, action));
});

Still I want to make a tiny addition, which makes sense, when using promises:

var promiseWhile = Promise.method(function(condition, action, lastValue) {
  if (!condition()) return lastValue;
  return action().then(promiseWhile.bind(null, condition, action));
});

This way the while loop can be embedded into a promise chain and resolves with lastValue (also if the action() is never run). See example:

var count = 10;
util.promiseWhile(
  function condition() {
    return count > 0;
  },
  function action() {
    return new Promise(function(resolve, reject) {
      count = count - 1;
      resolve(count)
    })
  },
  count)

Sorting dictionary keys in python

>>> mydict = {'a':1,'b':3,'c':2}
>>> sorted(mydict, key=lambda key: mydict[key])
['a', 'c', 'b']

Cannot install node modules that require compilation on Windows 7 x64/VS2012

I had also a lot of problem to compile nodejs zmq.

For the problem with with vcbuild.exe, just add it to the PATH

For other problems I could compile just using Windows 7.1 SDK Command Prompt

(Menu Programs -> Microsoft Windows SDK v7.1 -> Windows 7.1 SDK Command Prompt)

And from the prompt:

npm install zmq

That's works :)

crop text too long inside div

Below code will hide your text with fixed width you decide. but not quite right for responsive designs.

.CropLongTexts {
  width: 170px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

Update

I have noticed in (mobile) device(s) that the text (mixed) with each other due to (fixed width)... so i have edited the code above to become hidden responsively as follow:

.CropLongTexts {
  max-width: 170px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

The (max-width) ensure the text will be hidden responsively whatever the (screen size) and will not mixed with each other.

Take a list of numbers and return the average

Simple math..

def average(n):
    result = 0
    for i in n:
      result += i
      ave_num = result / len(n)
    return ave_num

input -> [1,2,3,4,5]
output -> 3.0

How do you convert epoch time in C#?

currently you can simply use

DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()

it will be returned as a 64-bits long

How to convert HTML file to word?

When doing this I found it easiest to:

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

PostgreSQL IF statement

DO
$do$
BEGIN
   IF EXISTS (SELECT FROM orders) THEN
      DELETE FROM orders;
   ELSE
      INSERT INTO orders VALUES (1,2,3);
   END IF;
END
$do$

There are no procedural elements in standard SQL. The IF statement is part of the default procedural language PL/pgSQL. You need to create a function or execute an ad-hoc statement with the DO command.

You need a semicolon (;) at the end of each statement in plpgsql (except for the final END).

You need END IF; at the end of the IF statement.

A sub-select must be surrounded by parentheses:

    IF (SELECT count(*) FROM orders) > 0 ...

Or:

    IF (SELECT count(*) > 0 FROM orders) ...

This is equivalent and much faster, though:

    IF EXISTS (SELECT FROM orders) ...

Alternative

The additional SELECT is not needed. This does the same, faster:

DO
$do$
BEGIN
   DELETE FROM orders;
   IF NOT FOUND THEN
      INSERT INTO orders VALUES (1,2,3);
   END IF;
END
$do$

Though unlikely, concurrent transactions writing to the same table may interfere. To be absolutely sure, write-lock the table in the same transaction before proceeding as demonstrated.

How to get mouse position in jQuery without mouse-events?

You can't read mouse position in jQuery without using an event. Note firstly that the event.pageX and event.pageY properties exists on any event, so you could do:

$('#myEl').click(function(e) {
    console.log(e.pageX);
});

Your other option is to use a closure to give your whole code access to a variable that is updated by a mousemove handler:

var mouseX, mouseY;
$(document).mousemove(function(e) {
    mouseX = e.pageX;
    mouseY = e.pageY;
}).mouseover(); // call the handler immediately

// do something with mouseX and mouseY

Error : getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443

use: https://registry.npmjs.org/ Make sure you are trying to connect to:

registry.npmjs.org

if there is no error,try to clear cache

npm cache clean --force

then try

npm install

even you have any error

npm config set registry https://registry.npmjs.org/

then try

npm install -g @angular/cli

Cheap way to search a large text file for a string

5000 lines isn't big (well, depends on how long the lines are...)

Anyway: assuming the string will be a word and will be seperated by whitespace...

lines=open(file_path,'r').readlines()
str_wanted="whatever_youre_looking_for"


    for i in range(len(lines)):
        l1=lines.split()
        for p in range(len(l1)):
            if l1[p]==str_wanted:
                #found
                # i is the file line, lines[i] is the full line, etc.

Delete rows from multiple tables using a single query (SQL Express 2005) with a WHERE condition

Use this in procedure

declare cu cursor for SELECT [name] FROM sys.Tables where [name] like 'tbl_%'
declare @table varchar(100)
declare @sql nvarchar(1000)

OPEN cu  
FETCH NEXT FROM cu INTO @table 

WHILE @@FETCH_STATUS = 0  
BEGIN  
    set @sql = N'delete from ' + @table
    EXEC sp_executesql @sql
    FETCH NEXT FROM cu INTO @table 
END   
CLOSE cu;  
DEALLOCATE cu;

Why em instead of px?

Avoid em or px use rem instead becuase its easier to find the computed value. But between em and px, px is better because em is hard to debug.

How to get a random number in Ruby

Well, I figured it out. Apparently there is a builtin (?) function called rand:

rand(n + 1)

If someone answers with a more detailed answer, I'll mark that as the correct answer.

Git: how to reverse-merge a commit?

To revert a merge commit, you need to use: git revert -m <parent number>. So for example, to revert the recent most merge commit using the parent with number 1 you would use:

git revert -m 1 HEAD

To revert a merge commit before the last commit, you would do:

git revert -m 1 HEAD^

Use git show <merge commit SHA1> to see the parents, the numbering is the order they appear e.g. Merge: e4c54b3 4725ad2

git merge documentation: http://schacon.github.com/git/git-merge.html

git merge discussion (confusing but very detailed): http://schacon.github.com/git/howto/revert-a-faulty-merge.txt

Adding hours to JavaScript Date object?

The version suggested by kennebec will fail when changing to or from DST, since it is the hour number that is set.

this.setUTCHours(this.getUTCHours()+h);

will add h hours to this independent of time system peculiarities. Jason Harwig's method works as well.

How to sort a list of objects based on an attribute of the objects?

It looks much like a list of Django ORM model instances.

Why not sort them on query like this:

ut = Tag.objects.order_by('-count')

How do you check "if not null" with Eloquent?

We can use

Model::whereNotNull('sent_at');

Or

Model::whereRaw('sent_at is not null');

Getting Chrome to accept self-signed localhost certificate

I went down the process of using what bjnord suggested which was: Google Chrome, Mac OS X and Self-Signed SSL Certificates

What is shown in the blog did not work.

However, one of the comments to the blog was gold:

sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain site.crt

You'll need to follow the blog on how to get the cert file, after that you can use the command above and should be good to go.

Inserting a text where cursor is using Javascript/jquery

This jQuery plugin gives you a pre-made way of selection/caret manipulation.

How to group pandas DataFrame entries by date in a non-unique column

this will also work

data.groupby(data['date'].dt.year)

Error parsing yaml file: mapping values are not allowed here

My issue was a missing set of quotes;

Foo: bar 'baz'

should be

Foo: "bar 'baz'"

How to execute command stored in a variable?

Unix shells operate a series of transformations on each line of input before executing them. For most shells it looks something like this (taken from the bash manpage):

  • initial word splitting
  • brace expansion
  • tilde expansion
  • parameter, variable and arithmetic expansion
  • command substitution
  • secondary word splitting
  • path expansion (aka globbing)
  • quote removal

Using $cmd directly gets it replaced by your command during the parameter expansion phase, and it then undergoes all following transformations.

Using eval "$cmd" does nothing until the quote removal phase, where $cmd is returned as is, and passed as a parameter to eval, whose function is to run the whole chain again before executing.

So basically, they're the same in most cases, and differ when your command makes use of the transformation steps up to parameter expansion. For example, using brace expansion:

$ cmd="echo foo{bar,baz}"
$ $cmd
foo{bar,baz}
$ eval "$cmd"
foobar foobaz

How to get parameter on Angular2 route in Angular way?

As of Angular 6+, this is handled slightly differently than in previous versions. As @BeetleJuice mentions in the answer above, paramMap is new interface for getting route params, but the execution is a bit different in more recent versions of Angular. Assuming this is in a component:

private _entityId: number;

constructor(private _route: ActivatedRoute) {
    // ...
}

ngOnInit() {
    // For a static snapshot of the route...
    this._entityId = this._route.snapshot.paramMap.get('id');

    // For subscribing to the observable paramMap...
    this._route.paramMap.pipe(
        switchMap((params: ParamMap) => this._entityId = params.get('id'))
    );

    // Or as an alternative, with slightly different execution...
    this._route.paramMap.subscribe((params: ParamMap) =>  {
        this._entityId = params.get('id');
    });
}

I prefer to use both because then on direct page load I can get the ID param, and also if navigating between related entities the subscription will update properly.

Source in Angular Docs

How Do I Replace/Change The Heading Text Inside <h3></h3>, Using jquery?

jQuery(document).ready(function(){
   jQuery(".head h3").html('Public Offers');
});

#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation

In my case there was no DEFINER or root@localhost mentioned in my SQL file. Actually I was trying to import and run SQL file into SQLYog from Database->Import->Execute SQL Script menu. That was giving error.

Then I copied all the script from SQL file and ran in SQLYog query editor. That worked perfectly fine.

How to get a list of sub-folders and their files, ordered by folder-names

Hej man, why are you using this ?

dir /s/b/o:gn > f.txt (wrong one)

Don't you know what is that 'g' in '/o' ??

Check this out: http://www.computerhope.com/dirhlp.htm or dir /? for dir help

You should be using this instead:

dir /s/b/o:n > f.txt (right one)

How to upload a file in Django?

Generally speaking when you are trying to 'just get a working example' it is best to 'just start writing code'. There is no code here to help you with, so it makes answering the question a lot more work for us.

If you want to grab a file, you need something like this in an html file somewhere:

<form method="post" enctype="multipart/form-data">
    <input type="file" name="myfile" />
    <input type="submit" name="submit" value="Upload" />
</form>

That will give you the browse button, an upload button to start the action (submit the form) and note the enctype so Django knows to give you request.FILES

In a view somewhere you can access the file with

def myview(request):
    request.FILES['myfile'] # this is my file

There is a huge amount of information in the file upload docs

I recommend you read the page thoroughly and just start writing code - then come back with examples and stack traces when it doesn't work.

Send XML data to webservice using php curl

If you are using shared hosting, then there are chances that outbound port might be disabled by your hosting provider. So please contact your hosting provider and they will open the outbound port for you

How to select label for="XYZ" in CSS?

The selector would be label[for=email], so in CSS:

label[for=email]
{
    /* ...definitions here... */
}

...or in JavaScript using the DOM:

var element = document.querySelector("label[for=email]");

...or in JavaScript using jQuery:

var element = $("label[for=email]");

It's an attribute selector. Note that some browsers (versions of IE < 8, for instance) may not support attribute selectors, but more recent ones do. To support older browsers like IE6 and IE7, you'd have to use a class (well, or some other structural way), sadly.

(I'm assuming that the template {t _your_email} will fill in a field with id="email". If not, use a class instead.)

Note that if the value of the attribute you're selecting doesn't fit the rules for a CSS identifier (for instance, if it has spaces or brackets in it, or starts with a digit, etc.), you need quotes around the value:

label[for="field[]"]
{
    /* ...definitions here... */
}

They can be single or double quotes.

What is so bad about singletons?

Monopoly is the devil and singletons with non-readonly/mutable state are the 'real' problem...

After reading Singletons are Pathological Liars as suggested in jason's answer I came across this little tidbit that provides the best presented example of how singletons are often misused.

Global is bad because:

  • a. It causes namespace conflict
  • b. It exposes the state in a unwarranted fashion

When it comes to Singletons

  • a. The explicit OO way of calling them, prevents the conflicts, so point a. is not an issue
  • b. Singletons without state are (like factories) are not a problem. Singletons with state can again fall in two categories, those which are immutable or write once and read many (config/property files). These are not bad. Mutable Singletons, which are kind of reference holders are the ones which you are speaking of.

In the last statement he's referring to the blog's concept of 'singletons are liars'.

How does this apply to Monopoly?

To start a game of monopoly, first:

  • we establish the rules first so everybody is on the same page
  • everybody is given an equal start at the beginning of the game
  • only one set of rules is presented to avoid confusion
  • the rules aren't allowed to change throughout the game

Now, for anybody who hasn't really played monopoly, these standards are ideal at best. A defeat in monopoly is hard to swallow because, monopoly is about money, if you lose you have to painstakingly watch the rest of the players finish the game, and losses are usually swift and crushing. So, the rules usually get twisted at some point to serve the self-interest of some of the players at the expense of the others.

So you're playing monopoly with friends Bob, Joe, and Ed. You're swiftly building your empire and consuming market share at an exponential rate. Your opponents are weakening and you start to smell blood (figuratively). Your buddy Bob put all of his money into gridlocking as many low-value properties as possible but his isn't receiving a high return on investment the way he expected. Bob, as a stroke of bad luck, lands on your Boardwalk and is excised from the game.

Now the game goes from friendly dice-rolling to serious business. Bob has been made the example of failure and Joe and Ed don't want to end up like 'that guy'. So, being the leading player you, all of a sudden, become the enemy. Joe and Ed start practicing under-the-table trades, behind-the-back money injections, undervalued house-swapping and generally anything to weaken you as a player until one of them rises to the top.

Then, instead of one of them winning, the process starts all over. All of a sudden, a finite set of rules becomes a moving target and the game degenerates into the type of social interactions that would make up the foundation of every high-rated reality TV show since Survivor. Why, because the rules are changing and there's no consensus on how/why/what they're supposed to represent, and more importantly, there's no one person making the decisions. Every player in the game, at that point, is making his/her own rules and chaos ensues until two of the players are too tired to keep up the charade and slowly give up.

So, if a rulebook for a game accurately represented a singleton, the monopoly rulebook would be an example of abuse.

How does this apply to programming?

Aside from all of the obvious thread-safety and synchronization issues that mutable singletons present... If you have one set of data, that is capable of being read/manipulated by multiple different sources concurrently and exists during the lifetime of the application execution, it's probably a good time to step back and ask "am I using the right type of data structure here".

Personally, I have seen a programmer abuse a singleton by using it as some sort of twisted cross-thread database store within an application. Having worked on the code directly, I can attest that it was a slow (because of all the thread locks needed to make it thread-safe) and a nightmare to work on (because of the unpredictable/intermittent nature of synchronization bugs), and nearly impossible to test under 'production' conditions. Sure, a system could have been developed using polling/signaling to overcome some of the performance issues but that wouldn't solve the issues with testing and, why bother when a 'real' database can already accomplish the same functionality in a much more robust/scalable manner.

A Singleton is only an option if you need what a singleton provides. A write-one read-only instance of an object. That same rule should cascade to the object's properties/members as well.

Rotating a point about another point (2D)

I struggled while working MS OCR Read API which returns back angle of rotation in range (-180, 180]. So I have to do an extra step of converting negative angles to positive. I hope someone struggling with point rotation with negative or positive angles can use the following.

def rotate(origin, point, angle):
    """
    Rotate a point counter-clockwise by a given angle around a given origin.
    """
    # Convert negative angles to positive
    angle = normalise_angle(angle)

    # Convert to radians
    angle = math.radians(angle)

    # Convert to radians
    ox, oy = origin
    px, py = point
    
    # Move point 'p' to origin (0,0)
    _px = px - ox
    _py = py - oy
    
    # Rotate the point 'p' 
    qx = (math.cos(angle) * _px) - (math.sin(angle) * _py)
    qy = (math.sin(angle) * _px) + (math.cos(angle) * _py)
    
    # Move point 'p' back to origin (ox, oy)
    qx = ox + qx
    qy = oy + qy
    
    return [qx, qy]


def normalise_angle(angle):
    """ If angle is negative then convert it to positive. """
    if (angle != 0) & (abs(angle) == (angle * -1)):
        angle = 360 + angle
    return angle

Creating an Arraylist of Objects

ArrayList<Matrices> list = new ArrayList<Matrices>();
list.add( new Matrices(1,1,10) );
list.add( new Matrices(1,2,20) );

SQLite: How do I save the result of a query as a CSV file?

From here and d5e5's comment:

You'll have to switch the output to csv-mode and switch to file output.

sqlite> .mode csv
sqlite> .output test.csv
sqlite> select * from tbl1;
sqlite> .output stdout

Adding files to java classpath at runtime

yes, you can. it will need to be in its package structure in a separate directory from the rest of your compiled code if you want to isolate it. you will then just put its base dir in the front of the classpath on the command line.

Python - How to concatenate to a string in a for loop?

While "".join is more pythonic, and the correct answer for this problem, it is indeed possible to use a for loop.

If this is a homework assignment (please add a tag if this is so!), and you are required to use a for loop then what will work (although is not pythonic, and shouldn't really be done this way if you are a professional programmer writing python) is this:

endstring = ""
mylist = ['first', 'second', 'other']
for word in mylist:
  print "This is the word I am adding: " + word
  endstring = endstring + word
print "This is the answer I get: " + endstring

You don't need the 'prints', I just threw them in there so you can see what is happening.

How to set value to form control in Reactive Forms in Angular

Try this.

editqueForm =  this.fb.group({
   user: [this.question.user],
   questioning: [this.question.questioning, Validators.required],
   questionType: [this.question.questionType, Validators.required],
   options: new FormArray([])
})

setValue() and patchValue()

if you want to set the value of one control, this will not work, therefor you have to set the value of both controls:

formgroup.setValue({name: ‘abc’, age: ‘25’});

It is necessary to mention all the controls inside the method. If this is not done, it will throw an error.

On the other hand patchvalue() is a lot easier on that part, let’s say you only want to assign the name as a new value:

formgroup.patchValue({name:’abc’});

Node/Express file upload

Personally multer didn't work for me after weeks trying to get this file upload thing right. Then I switch to formidable and after a few days I got it working perfectly without any error, multiple files, express and react.js even though react is optional. Here's the guide: https://www.youtube.com/watch?v=jtCfvuMRsxE&t=122s

Failed to load resource: the server responded with a status of 404 (Not Found) css

you have defined the public dir in app root/public

app.use(express.static(__dirname + '/public')); 

so you have to use:

./css/main.css

What does %>% function mean in R?

%>% is similar to pipe in Unix. For example, in

a <- combined_data_set %>% group_by(Outlet_Identifier) %>% tally()

the output of combined_data_set will go into group_by and its output will go into tally, then the final output is assigned to a.

This gives you handy and easy way to use functions in series without creating variables and storing intermediate values.

getOutputStream() has already been called for this response

JSP is s presentation framework, and is generally not supposed to contain any program logic in it. As skaffman suggested, use pure servlets, or any MVC web framework in order to achieve what you want.

Failed to read artifact descriptor for org.apache.maven.plugins:maven-source-plugin:jar:2.4

Update the apache-maven-3.5.0-bin\apache-maven-3.5.0\conf\settings.xml file.

Check your internet explorer proxy --> Setting --> Internet explorer -->Connection --> LAN Setting

<proxy>
  <id>optional</id>
  <active>true</active>
  <protocol>http</protocol>
  <username>user</username>
  <password>****</password>
  <host>proxy</host>
  <port>8080</port>
</proxy>

Role/Purpose of ContextLoaderListener in Spring?

Your understanding is correct. I wonder why you don't see any advantages in ContextLoaderListener. For example, you need to build a session factory (to manage database). This operation can take some time, so it's better to do it on startup. Of course you can do it with init servlets or something else, but the advantage of Spring's approach is that you make configuration without writing code.

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

You can call a ant task called merge on maven, to put all coverage files (*.exec) together in the same file.

If you are run unit tests use the phase prepare-package, if you run integration test so use post-integration-test.

This site has an example to how call jacoco ant task in maven project

You can use this merged file on sonar.

How to update record using Entity Framework Core?

public async Task<bool> Update(MyObject item)
{
    Context.Entry(await Context.MyDbSet.FirstOrDefaultAsync(x => x.Id == item.Id)).CurrentValues.SetValues(item);
    return (await Context.SaveChangesAsync()) > 0;
}

Simple PHP calculator

You also need to put the [== 'add'] math operation into quotes

if($_POST['group1'] == 'add') {
echo $first + $second;
}

complete code schould look like that :

<?php
$first = $_POST['first'];
$second= $_POST['second'];
if($_POST['group1'] == 'add') {
echo $first + $second;
}
else if($_POST['group1'] == 'subtract') {
echo $first - $second;
}
else if($_POST['group1'] == 'times') {
echo $first * $second;
} 
else if($_POST['group1'] == 'divide') {
echo $first / $second;
}
?>

Select Tag Helper in ASP.NET Core MVC

My answer below doesn't solve the question but it relates to.

If someone is using enum instead of a class model, like this example:

public enum Counter
{
    [Display(Name = "Number 1")]
    No1 = 1,
    [Display(Name = "Number 2")]
    No2 = 2,
    [Display(Name = "Number 3")]
    No3 = 3
}

And a property to get the value when submiting:

public int No { get; set; }

In the razor page, you can use Html.GetEnumSelectList<Counter>() to get the enum properties.

<select asp-for="No" asp-items="@Html.GetEnumSelectList<Counter>()"></select>

It generates the following HTML:

<select id="No" name="No">
    <option value="1">Number 1</option>
    <option value="2">Number 2</option>
    <option value="3">Number 3</option>
</select>

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

I needed to use this as a cell function (like SUM or VLOOKUP) and found that it was easy to:

  1. Make sure you are in a Macro Enabled Excel File (save as xlsm).
  2. Open developer tools Alt + F11
  3. Add Microsoft VBScript Regular Expressions 5.5 as in other answers
  4. Create the following function either in workbook or in its own module:

    Function REGPLACE(myRange As Range, matchPattern As String, outputPattern As String) As Variant
        Dim regex As New VBScript_RegExp_55.RegExp
        Dim strInput As String
    
        strInput = myRange.Value
    
        With regex
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = matchPattern
        End With
    
        REGPLACE = regex.Replace(strInput, outputPattern)
    
    End Function
    
  5. Then you can use in cell with =REGPLACE(B1, "(\w) (\d+)", "$1$2") (ex: "A 243" to "A243")

Popup Message boxes

first you have to import: import javax.swing.JOptionPane; then you can call it using this:

JOptionPane.showMessageDialog(null, 
                              "ALERT MESSAGE", 
                              "TITLE", 
                              JOptionPane.WARNING_MESSAGE);

the null puts it in the middle of the screen. put whatever in quotes under alert message. Title is obviously title and the last part will format it like an error message. if you want a regular message just replace it with PLAIN_MESSAGE. it works pretty well in a lot of ways mostly for errors.

Entity Framework Timeouts

If you are using DbContext and EF v6+, alternatively you can use:

this.context.Database.CommandTimeout = 180;

Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style)

just to answer your question...btw sry that i'm 9 months late:D...there's a "workaround" 4 this kind of problems. i.e.

new AlertDialog.Builder(some_class.this).setTitle("bla").setMessage("bla bla").show();
wait();

simply add wait();

and them in the OnClickListener start the class again with notify() something like this

@Override
    public void onClick(DialogInterface dialog, int item) {
        Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_LONG).show();
        **notify**();
        dialog.cancel();
    }

the same workaround goes 4 toasts and other async calls in android

ASP.NET MVC Dropdown List From SelectList

Try this, just an example:

u.UserTypeOptions = new SelectList(new[]
    {
        new { ID="1", Name="name1" },
        new { ID="2", Name="name2" },
        new { ID="3", Name="name3" },
    }, "ID", "Name", 1);

Or

u.UserTypeOptions = new SelectList(new List<SelectListItem>
    {
        new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
        new SelectListItem { Selected = false, Text = "Homeowner", Value = "2"},
        new SelectListItem { Selected = false, Text = "Contractor", Value = "3"},
    },"Value","Text");

What does \u003C mean?

That is a unicode character code that, when parsed by JavaScript as a string, is converted into its corresponding character (JavaScript automatically converts any occurrences of \uXXXX into the corresponding Unicode character). For example, your example would be:

Browse Interests{{/i}}</a>\n        </li>\n  {{#logged_in}}\n

As you can see, \u003C changes into < (less-than sign) and \u003E changes into > (greater-than sign).

In addition to the link posted by Raynos, this page from the Unicode website lists a lot of characters (so many that they decided to annoyingly group them) and this page has a (kind of) nice index.

Defining array with multiple types in TypeScript

My TS lint was complaining about other solutions, so the solution that was working for me was:

item: Array<Type1 | Type2>

if there's only one type, it's fine to use:

item: Type1[]

Difference between shared objects (.so), static libraries (.a), and DLL's (.so)?

A static library(.a) is a library that can be linked directly into the final executable produced by the linker,it is contained in it and there is no need to have the library into the system where the executable will be deployed.

A shared library(.so) is a library that is linked but not embedded in the final executable, so will be loaded when the executable is launched and need to be present in the system where the executable is deployed.

A dynamic link library on windows(.dll) is like a shared library(.so) on linux but there are some differences between the two implementations that are related to the OS (Windows vs Linux) :

A DLL can define two kinds of functions: exported and internal. The exported functions are intended to be called by other modules, as well as from within the DLL where they are defined. Internal functions are typically intended to be called only from within the DLL where they are defined.

An SO library on Linux doesn't need special export statement to indicate exportable symbols, since all symbols are available to an interrogating process.

Flexbox: 4 items per row

Here is another apporach.

You can accomplish it in this way too:

.parent{
  display: flex;
  flex-wrap: wrap;
}

.child{
  width: 25%;
  box-sizing: border-box;
}

Sample: https://codepen.io/capynet/pen/WOPBBm

And a more complete sample: https://codepen.io/capynet/pen/JyYaba

How to print full stack trace in exception?

Recommend to use LINQPad related nuget package, then you can use exceptionInstance.Dump().

enter image description here

For .NET core:

  • Install LINQPad.Runtime

For .NET framework 4 etc.

  • Install LINQPad

Sample code:

using System;
using LINQPad;

namespace csharp_Dump_test
{
    public class Program
    {
        public static void Main()
        {
            try
            {
                dosome();
            }
            catch (Exception ex)
            {
                ex.Dump();
            }
        }

        private static void dosome()
        {
            throw new Exception("Unable.");
        }
    }
}

Running result: enter image description here

LinqPad nuget package is the most awesome tool for printing exception stack information. May it be helpful for you.

Access parent DataContext from DataTemplate

the issue is that a DataTemplate isn't part of an element its applied to it.

this means if you bind to the template you're binding to something that has no context.

however if you put a element inside the template then when that element is applied to the parent it gains a context and the binding then works

so this will not work

<DataTemplate >
    <DataTemplate.Resources>
        <CollectionViewSource x:Key="projects" Source="{Binding Projects}" >

but this works perfectly

<DataTemplate >
    <GroupBox Header="Projects">
        <GroupBox.Resources>
            <CollectionViewSource x:Key="projects" Source="{Binding Projects}" >

because after the datatemplate is applied the groupbox is placed in the parent and will have access to its Context

so all you have to do is remove the style from the template and move it into an element in the template

note that the context for a itemscontrol is the item not the control ie ComboBoxItem for ComboBox not the ComboBox itself in which case you should use the controls ItemContainerStyle instead

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

Angular and Django Rest Framework.

I encountered similar error while making post request to my DRF api. It happened that all I was missing was trailing slash for endpoint.

Best way to center a <div> on a page vertically and horizontally?

The best and most flexible way

My demo on dabblet.com

The main trick in this demo is that in the normal flow of elements going from top to bottom, so the margin-top: auto is set to zero. However, an absolutely positioned element acts the same for distribution of free space, and similarly can be centered vertically at the specified top and bottom (does not work in IE7).

This trick will work with any sizes of div.

_x000D_
_x000D_
div {_x000D_
 width: 100px;_x000D_
 height: 100px;_x000D_
 background-color: red;_x000D_
 _x000D_
 position: absolute;_x000D_
 top:0;_x000D_
 bottom: 0;_x000D_
 left: 0;_x000D_
 right: 0;_x000D_
   _x000D_
 margin: auto;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

What is attr_accessor in Ruby?

Simply put it will define a setter and getter for the class.

Note that

attr_reader :v is equivalant to 
def v
  @v
end

attr_writer :v is equivalant to
def v=(value)
  @v=value
end

So

attr_accessor :v which means 
attr_reader :v; attr_writer :v 

are equivalant to define a setter and getter for the class.

How to change the Push and Pop animations in a navigation based app

Here is how I have done the same in Swift:

For Push:

    UIView.animateWithDuration(0.75, animations: { () -> Void in
        UIView.setAnimationCurve(UIViewAnimationCurve.EaseInOut)
        self.navigationController!.pushViewController(nextView, animated: false)
        UIView.setAnimationTransition(UIViewAnimationTransition.FlipFromRight, forView: self.navigationController!.view!, cache: false)
    })

For Pop:

I actually did this a little differently to some of the responses above - but as I am new to Swift development, it might not be right. I have overridden viewWillDisappear:animated: and added the pop code in there:

    UIView.animateWithDuration(0.75, animations: { () -> Void in
        UIView.setAnimationCurve(UIViewAnimationCurve.EaseInOut)
        UIView.setAnimationTransition(UIViewAnimationTransition.FlipFromLeft, forView: self.navigationController!.view, cache: false)
    })

    super.viewWillDisappear(animated)

Read user input inside a loop

Try to change the loop like this:

for line in $(cat filename); do
    read input
    echo $input;
done

Unit test:

for line in $(cat /etc/passwd); do
    read input
    echo $input;
    echo "[$line]"
done

How to take MySQL database backup using MySQL Workbench?

In Window in new version you can export like this

enter image description here enter image description here

enter image description here

Is there a kind of Firebug or JavaScript console debug for Android?

You can try YConsole a js embedded console. It is lightweight and simple to use.

  • Catch logs and errors.
  • Object editor.

How to use :

<script type="text/javascript" src="js/YConsole-compiled.js"></script>
<script type="text/javascript" >YConsole.show();</script>

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

If you want to bind an event like 'click' for all the elements having same class in the rendered DOM element then you can set up an event listener by using following parts of the code in components.ts file.

import { Component, OnInit, Renderer, ElementRef} from '@angular/core';

constructor( elementRef: ElementRef, renderer: Renderer) {
    dragulaService.drop.subscribe((value) => {
      this.onDrop(value.slice(1));
    });
}

public onDrop(args) {

  let [e, el] = args;

  this.toggleClassComTitle(e,'checked');

}


public toggleClassComTitle(el: any, name: string) {

    el.querySelectorAll('.com-item-title-anchor').forEach( function ( item ) {

      item.addEventListener('click', function(event) {
              console.log("item-clicked");

       });
    });

}

PHP - Check if two arrays are equal

If you want to check non associative arrays, here is the solution:

$a = ['blog', 'company'];
$b = ['company', 'blog'];

(count(array_unique(array_merge($a, $b))) === count($a)) ? 'Equals' : 'Not Equals';
// Equals

What is JSON and why would I use it?

What is JSON?

JavaScript Object Notation (JSON) is a lightweight data-interchange format inspired by the object literals of JavaScript.

JSON values can consist of:

objects (collections of name-value pairs) arrays (ordered lists of values) strings (in double quotes) numbers true, false, or null

JSON is language independent.

JSON with PHP?

After PHP Version 5.2.0, JSON extension is decodes and encodes functionalities as default.

Json_encode - returns the JSON representation of values Json_decode - Decodes the JSON String Json_last_error - Returns the last error occured.

JSON Syntax and Rules?

JSON syntax is derived from JavaScript object notation syntax:

Data is in name/value pairs Data is separated by commas Curly braces hold objects Square brackets hold arrays

What is the difference between concurrency and parallelism?

The simplest and most elegant way of understanding the two in my opinion is this. Concurrency allows interleaving of execution and so can give the illusion of parallelism. This means that a concurrent system can run your Youtube video alongside you writing up a document in Word, for example. The underlying OS, being a concurrent system, enables those tasks to interleave their execution. Because computers execute instructions so quickly, this gives the appearance of doing two things at once.

Parallelism is when such things really are in parallel. In the example above, you might find the video processing code is being executed on a single core, and the Word application is running on another. Note that this means that a concurrent program can also be in parallel! Structuring your application with threads and processes enables your program to exploit the underlying hardware and potentially be done in parallel.

Why not have everything be parallel then? One reason is because concurrency is a way of structuring programs and is a design decision to facilitate separation of concerns, whereas parallelism is often used in the name of performance. Another is that some things fundamentally cannot fully be done in parallel. An example of this would be adding two things to the back of a queue - you cannot insert both at the same time. Something must go first and the other behind it, or else you mess up the queue. Although we can interleave such execution (and so we get a concurrent queue), you cannot have it parallel.

Hope this helps!

How to debug Google Apps Script (aka where does Logger.log log to?)

If you have the script editor open you will see the logs under View->Logs. If your script has an onedit trigger, make a change to the spreadsheet which should trigger the function with the script editor opened in a second tab. Then go to the script editor tab and open the log. You will see whatever your function passes to the logger.

Basically as long as the script editor is open, the event will write to the log and show it for you. It will not show if someone else is in the file elsewhere.

How to change current working directory using a batch file

Specify /D to change the drive also.

CD /D %root%

How to add row of data to Jtable from values received from jtextfield and comboboxes

you can use this code as template please customize it as per your requirement.

DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();

list.add(textField.getText());
list.add(comboBox.getSelectedItem());

model.addRow(list.toArray());

table.setModel(model);

here DefaultTableModel is used to add rows in JTable, you can get more info here.

SQL count rows in a table

Why don't you just right click on the table and then properties -> Storage and it would tell you the row count. You can use the below for row count in a view

SELECT SUM (row_count) 
FROM sys.dm_db_partition_stats 
WHERE object_id=OBJECT_ID('Transactions')    
AND (index_id=0 or index_id=1)`

How do I efficiently iterate over each entry in a Java Map?

There are several ways to iterate over map.

Here is comparison of their performances for a common data set stored in map by storing a million key value pairs in map and will iterate over map.

1) Using entrySet() in for each loop

for (Map.Entry<String,Integer> entry : testMap.entrySet()) {
    entry.getKey();
    entry.getValue();
}

50 milliseconds

2) Using keySet() in for each loop

for (String key : testMap.keySet()) {
    testMap.get(key);
}

76 milliseconds

3) Using entrySet() and iterator

Iterator<Map.Entry<String,Integer>> itr1 = testMap.entrySet().iterator();
while(itr1.hasNext()) {
    Map.Entry<String,Integer> entry = itr1.next();
    entry.getKey();
    entry.getValue();
}

50 milliseconds

4) Using keySet() and iterator

Iterator itr2 = testMap.keySet().iterator();
while(itr2.hasNext()) {
    String key = itr2.next();
    testMap.get(key);
}

75 milliseconds

I have referred this link.

C# convert int to string with padding zeros?

i.ToString().PadLeft(4, '0') - okay, but doesn't work for negative numbers
i.ToString("0000"); - explicit form
i.ToString("D4"); - short form format specifier
$"{i:0000}"; - string interpolation (C# 6.0+)

How to remove duplicate values from an array in PHP

$result = array();
foreach ($array as $key => $value){
  if(!in_array($value, $result))
    $result[$key]=$value;
}

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

1)check the package name is the same in google-services.json file

2)make sure that no other project exist with same package name

3)make sure that there is internet access

4)try syncing project and running it again

How to insert array of data into mysql using php

First of all you should stop using mysql_*. MySQL supports multiple inserting like

INSERT INTO example
VALUES
  (100, 'Name 1', 'Value 1', 'Other 1'),
  (101, 'Name 2', 'Value 2', 'Other 2'),
  (102, 'Name 3', 'Value 3', 'Other 3'),
  (103, 'Name 4', 'Value 4', 'Other 4');

You just have to build one string in your foreach loop which looks like that

$values = "(100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1')";

and then insert it after the loop

$sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) VALUES ".$values;

Another way would be Prepared Statements, which are even more suited for your situation.

With CSS, use "..." for overflowed block of multi-lines

Just want to add to this question for completeness sake.

Linux shell script for database backup

Create a script similar to this:

#!/bin/sh -e

location=~/`date +%Y%m%d_%H%M%S`.db

mysqldump -u root --password=<your password> database_name > $location

gzip $location

Then you can edit the crontab of the user that the script is going to run as:

$> crontab -e

And append the entry

01 * * * * ~/script_path.sh

This will make it run on the first minute of every hour every day.

Then you just have to add in your rolls and other functionality and you are good to go.

Split list into smaller lists (split in half)

B,C=A[:len(A)/2],A[len(A)/2:]

JavaScript Form Submit - Confirm or Cancel Submission Dialog Box

If you want to apply some condition on form submit then you can use this method

<form onsubmit="return checkEmpData();" method="post" action="process.html">
  <input type="text" border="0" name="submit" />
  <button value="submit">submit</button>
</form>

One thing always keep in mind that method and action attribute write after onsubmit attributes

javascript code

function checkEmpData()
{
  var a = 0;

  if(a != 0)
  {
    return confirm("Do you want to generate attendance?");
  }
   else
   {
      alert('Please Select Employee First');
      return false;
   }  
}

Calculating number of full months between two dates in SQL

SELECT dateadd(dd,number,DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)) AS gun FROM master..spt_values
WHERE type = 'p'
AND year(dateadd(dd,number,DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)))=year(DATEADD(yy, DATEDIFF(yy,0,getdate()), 0))

Using :after to clear floating elements

Use

.wrapper:after {
    content : '\n';
}

Much like solution provided by Roko. It allows to insert/change content using : after and :before psuedo. For details check http://www.quirksmode.org/css/content.html

How do I use sudo to redirect output to a location I don't have permission to write to?

Whenever I have to do something like this I just become root:

# sudo -s
# ls -hal /root/ > /root/test.out
# exit

It's probably not the best way, but it works.

How to strip HTML tags from string in JavaScript?

var html = "<p>Hello, <b>World</b>";
var div = document.createElement("div");
div.innerHTML = html;
alert(div.innerText); // Hello, World

That pretty much the best way of doing it, you're letting the browser do what it does best -- parse HTML.


Edit: As noted in the comments below, this is not the most cross-browser solution. The most cross-browser solution would be to recursively go through all the children of the element and concatenate all text nodes that you find. However, if you're using jQuery, it already does it for you:

alert($("<p>Hello, <b>World</b></p>").text());

Check out the text method.

Parsing JSON Array within JSON Object

This could be an answer to your question:

JSONArray msg1 = (JSONArray) json.get("source");
for(int i = 0; i < msg1.length(); i++){
  String name = msg1.getString("name");
  int age     = msg1.getInt("age");
}

WCF gives an unsecured or incorrectly secured fault error

For what it's worth - I also had this error and found it was caused by the connection string in the web services web.config being set to connect to the wrong machine.

Count lines in large files

Try: sed -n '$=' filename

Also cat is unnecessary: wc -l filename is enough in your present way.

How to save select query results within temporary table?

select *
into #TempTable
from SomeTale

select *
from #TempTable

Get HTML code from website in C#

Try this solution. It works fine.

 try{
        String url = textBox1.Text;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader sr = new StreamReader(response.GetResponseStream());
        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        doc.Load(sr);
        var aTags = doc.DocumentNode.SelectNodes("//a");
        int counter = 1;
        if (aTags != null)
        {
            foreach (var aTag in aTags)
            {
                richTextBox1.Text +=  aTag.InnerHtml +  "\n" ;
                counter++;
            }
        }
        sr.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Failed to retrieve related keywords." + ex);
        }

How to join multiple lines of file names into one with custom delimiter?

To avoid potential newline confusion for tr we could add the -b flag to ls:

ls -1b | tr '\n' ';'

PHP - Getting the index of a element from a array

You should use the key() function.

key($array)

should return the current key.

If you need the position of the current key:

array_search($key, array_keys($array));

How do I redirect to the previous action in ASP.NET MVC?

I'm using .Net Core 2 MVC , and this one worked for me, in the controller use HttpContext.Request.Headers["Referer"];

What is unit testing and how do you do it?

What exactly IS unit testing? Is it built into code or run as separate programs? Or something else?

From MSDN: The primary goal of unit testing is to take the smallest piece of testable software in the application, isolate it from the remainder of the code, and determine whether it behaves exactly as you expect.

Essentially, you are writing small bits of code to test the individual bits of your code. In the .net world, you would run these small bits of code using something like NUnit or MBunit or even the built in testing tools in visual studio. In Java you might use JUnit. Essentially the test runners will build your project, load and execute the unit tests and then let you know if they pass or fail.

How do you do it?

Well it's easier said than done to unit test. It takes quite a bit of practice to get good at it. You need to structure your code in a way that makes it easy to unit test to make your tests effective.

When should it be done? Are there times or projects not to do it? Is everything unit-testable?

You should do it where it makes sense. Not everything is suited to unit testing. For example UI code is very hard to unit test and you often get little benefit from doing so. Business Layer code however is often very suitable for tests and that is where most unit testing is focused.

Unit testing is a massive topic and to fully get an understanding of how it can best benefit you I'd recommend getting hold of a book on unit testing such as "Test Driven Development by Example" which will give you a good grasp on the concepts and how you can apply them to your code.

Display calendar to pick a date in java

Another easy method in Netbeans is also avaiable here, There are libraries inside Netbeans itself,where the solutions for this type of situations are available.Select the relevant one as well.It is much easier.After doing the prescribed steps in the link,please restart Netbeans.

Step1:- Select Tools->Palette->Swing/AWT Components
Step2:- Click 'Add from JAR'in Palette Manager
Step3:- Browse to [NETBEANS HOME]\ide\modules\ext and select swingx-0.9.5.jar
Step4:- This will bring up a list of all the components available for the palette.  Lots of goodies here!  Select JXDatePicker.
Step5:- Select Swing Controls & click finish
Step6:- Restart NetBeans IDE and see the magic :)

Python: access class property from string

A picture's worth a thousand words:

>>> class c:
        pass
o = c()
>>> setattr(o, "foo", "bar")
>>> o.foo
'bar'
>>> getattr(o, "foo")
'bar'

Remove all elements contained in another array

var myArray = [
  {name: 'deepak', place: 'bangalore'}, 
  {name: 'chirag', place: 'bangalore'}, 
  {name: 'alok', place: 'berhampur'}, 
  {name: 'chandan', place: 'mumbai'}
];
var toRemove = [
  {name: 'deepak', place: 'bangalore'},
  {name: 'alok', place: 'berhampur'}
];



myArray = myArray.filter(ar => !toRemove.find(rm => (rm.name === ar.name && ar.place === rm.place) ))