Programs & Examples On #Wiki engine

Wiki-Engine (aka Wiki Software)

Check if DataRow exists by column name in c#?

if (drMyRow.Table.Columns["ColNameToCheck"] != null)
{
   doSomethingUseful;
{
else { return; }

Although the DataRow does not have a Columns property, it does have a Table that the column can be checked for.

How to set a time zone (or a Kind) of a DateTime value?

You can try this as well, it is easy to implement

TimeZone time2 = TimeZone.CurrentTimeZone;
DateTime test = time2.ToUniversalTime(DateTime.Now);
var singapore = TimeZoneInfo.FindSystemTimeZoneById("Singapore Standard Time");
var singaporetime = TimeZoneInfo.ConvertTimeFromUtc(test, singapore);

Change the text to which standard time you want to change.

Use TimeZone feature of C# to implement.

Update multiple rows in same query using PostgreSQL

Yes, you can:

UPDATE foobar SET column_a = CASE
   WHEN column_b = '123' THEN 1
   WHEN column_b = '345' THEN 2
END
WHERE column_b IN ('123','345')

And working proof: http://sqlfiddle.com/#!2/97c7ea/1

Retrieving the text of the selected <option> in <select> element

If you found this thread and wanted to know how to get the selected option text via event here is sample code:

alert(event.target.options[event.target.selectedIndex].text);

How to use terminal commands with Github?

You can't push into other people's repositories. This is because push permanently gets code into their repository, which is not cool.

What you should do, is to ask them to pull from your repository. This is done in GitHub by going to the other repository and sending a "pull request".

There is a very informative article on the GitHub's help itself: https://help.github.com/articles/using-pull-requests


To interact with your own repository, you have the following commands. I suggest you start reading on Git a bit more for these instructions (lots of materials online).

To add new files to the repository or add changed files to staged area:

$ git add <files>

To commit them:

$ git commit

To commit unstaged but changed files:

$ git commit -a

To push to a repository (say origin):

$ git push origin

To push only one of your branches (say master):

$ git push origin master

To fetch the contents of another repository (say origin):

$ git fetch origin

To fetch only one of the branches (say master):

$ git fetch origin master

To merge a branch with the current branch (say other_branch):

$ git merge other_branch

Note that origin/master is the name of the branch you fetched in the previous step from origin. Therefore, updating your master branch from origin is done by:

$ git fetch origin master
$ git merge origin/master

You can read about all of these commands in their manual pages (either on your linux or online), or follow the GitHub helps:

How do I make a self extract and running installer

Okay I have got it working, hope this information is useful.

  1. First of all I now realize that not only do self-extracting zip start extracting with doubleclick, but they require no extraction application to be installed on the users computer because the extractor code is in the archive itself. This means that you will get a different user experience depending on what you application you use to create the sfx

  2. I went with WinRar as follows, this does not require you to create an sfx file, everything can be created via the gui:

    • Select files, right click and select Add to Archive
    • Use Browse.. to create the archive in the folder above
    • Change Archive Format to Zip
    • Enable Create SFX archive
    • Select Advanced tab
    • Select SFX Options
    • Select Setup tab
    • Enter setup.exe into the Run after Extraction field
    • Select Modes tab
    • Enable Unpack to temporary folder
    • Select text and Icon tab
    • Enter a more appropriate title for your task
    • Select OK
    • Select OK

The resultant exe unzips to a temporary folder and then starts the installer

Default port for SQL Server

SQL Server default port is 1434.

To allow remote access I had to release those ports on my firewall:

Protocol  |   Port
---------------------
UDP       |   1050
TCP       |   1050
TCP       |   1433
UDP       |   1434

Resolve absolute path from relative path and/or file name

I have not seen many solutions to this problem. Some solutions make use of directory traversal using CD and others make use of batch functions. My personal preference has been for batch functions and in particular, the MakeAbsolute function as provided by DosTips.

The function has some real benefits, primarily that it does not change your current working directory and secondly that the paths being evaluated don't even have to exist. You can find some helpful tips on how to use the function here too.

Here is an example script and its outputs:

@echo off

set scriptpath=%~dp0
set siblingfile=sibling.bat
set siblingfolder=sibling\
set fnwsfolder=folder name with spaces\
set descendantfolder=sibling\descendant\
set ancestorfolder=..\..\
set cousinfolder=..\uncle\cousin

call:MakeAbsolute siblingfile      "%scriptpath%"
call:MakeAbsolute siblingfolder    "%scriptpath%"
call:MakeAbsolute fnwsfolder       "%scriptpath%"
call:MakeAbsolute descendantfolder "%scriptpath%"
call:MakeAbsolute ancestorfolder   "%scriptpath%"
call:MakeAbsolute cousinfolder     "%scriptpath%"

echo scriptpath:       %scriptpath%
echo siblingfile:      %siblingfile%
echo siblingfolder:    %siblingfolder%
echo fnwsfolder:       %fnwsfolder%
echo descendantfolder: %descendantfolder%
echo ancestorfolder:   %ancestorfolder%
echo cousinfolder:     %cousinfolder%
GOTO:EOF

::----------------------------------------------------------------------------------
:: Function declarations
:: Handy to read http://www.dostips.com/DtTutoFunctions.php for how dos functions
:: work.
::----------------------------------------------------------------------------------
:MakeAbsolute file base -- makes a file name absolute considering a base path
::                      -- file [in,out] - variable with file name to be converted, or file name itself for result in stdout
::                      -- base [in,opt] - base path, leave blank for current directory
:$created 20060101 :$changed 20080219 :$categories Path
:$source http://www.dostips.com
SETLOCAL ENABLEDELAYEDEXPANSION
set "src=%~1"
if defined %1 set "src=!%~1!"
set "bas=%~2"
if not defined bas set "bas=%cd%"
for /f "tokens=*" %%a in ("%bas%.\%src%") do set "src=%%~fa"
( ENDLOCAL & REM RETURN VALUES
    IF defined %1 (SET %~1=%src%) ELSE ECHO.%src%
)
EXIT /b

And the output:

C:\Users\dayneo\Documents>myscript
scriptpath:       C:\Users\dayneo\Documents\
siblingfile:      C:\Users\dayneo\Documents\sibling.bat
siblingfolder:    C:\Users\dayneo\Documents\sibling\
fnwsfolder:       C:\Users\dayneo\Documents\folder name with spaces\
descendantfolder: C:\Users\dayneo\Documents\sibling\descendant\
ancestorfolder:   C:\Users\
cousinfolder:     C:\Users\dayneo\uncle\cousin

I hope this helps... It sure helped me :) P.S. Thanks again to DosTips! You rock!

what is the use of xsi:schemaLocation?

According to the spec for locating Schemas

there may or may not be a schema retrievable via the namespace name... User community and/or consumer/provider agreements may establish circumstances in which [trying to retrieve an xsd from the namespace url] is a sensible default strategy

(thanks for being unambiguous, spec!)

and

in case a document author (human or not) created a document with a particular schema in view, and warrants that some or all of the document conforms to that schema, the schemaLocation and noNamespaceSchemaLocation [attributes] are provided.

So basically with specifying just a namespace, your XML "might" be attempted to be validated against an xsd at that location (even if it lacks a schemaLocation attribute), depending on your "community." If you specify a specific schemaLocation, then it basically is implying that the xml document "should" be conformant to said xsd, so "please validate it" (as I read it). My guess is that if you don't do a schemaLocation or noNamespaceSchemaLocation attribute it just "isn't validated" most of the time (based on the other answers, appears java does it this way).

Another wrinkle here is that typically, with xsd validation in java libraries [ex: spring config xml files], if your XML files specifies a particular schemaLocation xsd url in an XML file, like xsi:schemaLocation="http://somewhere http://somewhere/something.xsd" typically within one of your dependency jars it will contain a copy of that xsd file, in its resources section, and spring has a "mapping" capability saying to treat that xsd file as if it maps to the url http://somewhere/something.xsd (so you never end up going to web and downloading the file, it just exists locally). See also https://stackoverflow.com/a/41225329/32453 for slightly more info.

Remove HTML tags from string including &nbsp in C#

If you can't use an HTML parser oriented solution to filter out the tags, here's a simple regex for it.

string noHTML = Regex.Replace(inputHTML, @"<[^>]+>|&nbsp;", "").Trim();

You should ideally make another pass through a regex filter that takes care of multiple spaces as

string noHTMLNormalised = Regex.Replace(noHTML, @"\s{2,}", " ");

How to do perspective fixing?

The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.

The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.

Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.

:before and background-image... should it work?

 color: transparent; 

make the tricks for me

#videos-part:before{
    font-size: 35px;
    line-height: 33px;
    width: 16px;
    color: transparent;
    content: 'AS YOU LIKE';
    background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjwhRE9DVFlQRSBzdmcgIFBVQkxJQyAnLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4nICAnaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkJz48c3ZnIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDUwIDUwIiBoZWlnaHQ9IjUwcHgiIGlkPSJMYXllcl8xIiB2ZXJzaW9uPSIxLjEiIHZpZXdCb3g9IjAgMCA1MCA1MCIgd2lkdGg9IjUwcHgiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxwYXRoIGQ9Ik04LDE0TDQsNDloNDJsLTQtMzVIOHoiIGZpbGw9Im5vbmUiIHN0cm9rZT0iIzAwMDAwMCIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbWl0ZXJsaW1pdD0iMTAiIHN0cm9rZS13aWR0aD0iMiIvPjxyZWN0IGZpbGw9Im5vbmUiIGhlaWdodD0iNTAiIHdpZHRoPSI1MCIvPjxwYXRoIGQ9Ik0zNCwxOWMwLTEuMjQxLDAtNi43NTksMC04ICBjMC00Ljk3MS00LjAyOS05LTktOXMtOSw0LjAyOS05LDljMCwxLjI0MSwwLDYuNzU5LDAsOCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjMDAwMDAwIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1taXRlcmxpbWl0PSIxMCIgc3Ryb2tlLXdpZHRoPSIyIi8+PGNpcmNsZSBjeD0iMzQiIGN5PSIxOSIgcj0iMiIvPjxjaXJjbGUgY3g9IjE2IiBjeT0iMTkiIHI9IjIiLz48L3N2Zz4=');
    background-size: 25px;
    background-repeat: no-repeat;
    }

Is <img> element block level or inline level?

An img element is a replaced inline element.

It behaves like an inline element (because it is), but some generalizations about inline elements do not apply to img elements.

e.g.

Generalization: "Width does not apply to inline elements"

What the spec actually says: "Applies to: all elements but non-replaced inline elements, table rows, and row groups "

Since an image is a replaced inline element, it does apply.

About the Full Screen And No Titlebar from manifest

To set your App or any individual activity display in Full Screen mode, insert the code

<application 
    android:icon="@drawable/icon" 
    android:label="@string/app_name" 
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen">

in AndroidManifest.xml, under application or activity tab.

How to delete a cookie?

Try this:

function delete_cookie( name, path, domain ) {
  if( get_cookie( name ) ) {
    document.cookie = name + "=" +
      ((path) ? ";path="+path:"")+
      ((domain)?";domain="+domain:"") +
      ";expires=Thu, 01 Jan 1970 00:00:01 GMT";
  }
}

You can define get_cookie() like this:

function get_cookie(name){
    return document.cookie.split(';').some(c => {
        return c.trim().startsWith(name + '=');
    });
}

How do I paste multi-line bash codes into terminal and run it all at once?

In addition to backslash, if a line ends with | or && or ||, it will be continued on the next line.

I keep getting "Uncaught SyntaxError: Unexpected token o"

Another hints for Unexpected token errors. There are two major differences between javascript objects and json:

  1. json data must be always quoted with double quotes.
  2. keys must be quoted

Correct JSON

 {
    "english": "bag",
    "kana": "kaban",
    "kanji": "K"
}

Error JSON 1

 {
    'english': 'bag',
    'kana': 'kaban',
    'kanji': 'K'
 }

Error JSON 2

 {
    english: "bag",
    kana: "kaban",
    kanji: "K"
}

Remark

This is not a direct answer for that question. But it's an answer for Unexpected token errors. So it may be help others who stumple upon that question.

Using Pipes within ngModel on INPUT Elements in Angular

because of two way binding, To prevent error of:

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was 
checked.

you can call a function to change model like this:

<input [ngModel]="item.value" 
  (ngModelChange)="getNewValue($event)" name="inputField" type="text" />


import { UseMyPipeToFormatThatValuePipe } from './path';

constructor({
    private UseMyPipeToFormatThatValue: UseMyPipeToFormatThatValuePipe,
})

getNewValue(ev: any): any {
    item.value= this.useMyPipeToFormatThatValue.transform(ev);
}

it'll be good if there is a better solution to prevent this error.

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed

For my VB.Net Friends -

Dim scriptManager As ScriptManager = scriptManager.GetCurrent(Me.Page)
scriptManager.RegisterPostBackControl(Me.YourButtonNameHere)

PHP Error: Function name must be a string

Using parenthesis in a programming language or a scripting language usually means that it is a function.

However $_COOKIE in php is not a function, it is an Array. To access data in arrays you use square braces ('[' and ']') which symbolize which index to get the data from. So by doing $_COOKIE['test'] you are basically saying: "Give me the data from the index 'test'.

Now, in your case, you have two possibilities: (1) either you want to see if it is false--by looking inside the cookie or (2) see if it is not even there.

For this, you use the isset function which basically checks if the variable is set or not.

Example

if ( isset($_COOKIE['test'] ) )

And if you want to check if the value is false and it is set you can do the following:

if ( isset($_COOKIE['test']) && $_COOKIE['test'] == "false" )

One thing that you can keep in mind is that if the first test fails, it wont even bother checking the next statement if it is AND ( && ).

And to explain why you actually get the error "Function must be a string", look at this page. It's about basic creation of functions in PHP, what you must remember is that a function in PHP can only contain certain types of characters, where $ is not one of these. Since in PHP $ represents a variable.

A function could look like this: _myFunction _myFunction123 myFunction and in many other patterns as well, but mixing it with characters like $ and % will not work.

How to connect html pages to mysql database?

HTML are markup languages, basically they are set of tags like <html>, <body>, which is used to present a website using , and as a whole. All these, happen in the clients system or the user you will be browsing the website.

Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.

So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like , , etc.

Now, lets see a snippet of connection using MYSQLi Extension of PHP

$db = mysqli_connect('hostname','username','password','databasename');

This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:

<?php
    $db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
    <body>
          <?php
                $query = "SELECT * FROM `mytable`;";
                $result = mysqli_query($db, $query);
                while($row = mysqli_fetch_assoc($result)) {
                      // Display your datas on the page
                }
          ?>
    </body>
</html>

In order to insert new data into the database, you can use phpMyAdmin or write a INSERT query and execute them.

Can not connect to local PostgreSQL

Try uninstalling the pg gem (gem uninstall pg) then reinstalling -- if you use bundler, then bundle install, else gem install pg. Also, make sure path picks up the right version: Lion has a version of posgresql (prior versions didn't) and it may be in the path before your locally installed version (e.g. MacPorts, homebrew).

In my case: homebrew install of postgresql, updated postgresql, rails, etc. and then got this error. Uninstalling and reinstalling the pg gem did it for me.

Python: Checking if a 'Dictionary' is empty doesn't seem to work

dict = {}
print(len(dict.keys()))

if length is zero means that dict is empty

Find Java classes implementing an interface

In full generality, this functionality is impossible. The Java ClassLoader mechanism guarantees only the ability to ask for a class with a specific name (including pacakge), and the ClassLoader can supply a class, or it can state that it does not know that class.

Classes can be (and frequently are) loaded from remote servers, and they can even be constructed on the fly; it is not difficult at all to write a ClassLoader that returns a valid class that implements a given interface for any name you ask from it; a List of the classes that implement that interface would then be infinite in length.

In practice, the most common case is an URLClassLoader that looks for classes in a list of filesystem directories and JAR files. So what you need is to get the URLClassLoader, then iterate through those directories and archives, and for each class file you find in them, request the corresponding Class object and look through the return of its getInterfaces() method.

What does FETCH_HEAD in Git mean?

As mentioned in Jonathan's answer, FETCH_HEAD corresponds to the file .git/FETCH_HEAD. Typically, the file will look like this:

71f026561ddb57063681109aadd0de5bac26ada9                        branch 'some-branch' of <remote URL>
669980e32769626587c5f3c45334fb81e5f44c34        not-for-merge   branch 'some-other-branch' of <remote URL>
b858c89278ab1469c71340eef8cf38cc4ef03fed        not-for-merge   branch 'yet-some-other-branch' of <remote URL>

Note how all branches but one are marked not-for-merge. The odd one out is the branch that was checked out before the fetch. In summary: FETCH_HEAD essentially corresponds to the remote version of the branch that's currently checked out.

How to get jQuery dropdown value onchange event

$('#drop').change(
    function() {
        var val1 = $('#pick option:selected').val();
        var val2 = $('#drop option:selected').val();

        // Do something with val1 and val2 ...
    }
);

Random record from MongoDB

MongoDB now has $rand

To pick n non repeat items, aggregate with { $addFields: { _f: { $rand: {} } } } then $sort by _f and $limit n.

Label encoding across multiple columns in scikit-learn

Using Neuraxle

TLDR; You here can use the FlattenForEach wrapper class to simply transform your df like: FlattenForEach(LabelEncoder(), then_unflatten=True).fit_transform(df).

With this method, your label encoder will be able to fit and transform within a regular scikit-learn Pipeline. Let's simply import:

from sklearn.preprocessing import LabelEncoder
from neuraxle.steps.column_transformer import ColumnTransformer
from neuraxle.steps.loop import FlattenForEach

Same shared encoder for columns:

Here is how one shared LabelEncoder will be applied on all the data to encode it:

    p = FlattenForEach(LabelEncoder(), then_unflatten=True)

Result:

    p, predicted_output = p.fit_transform(df.values)
    expected_output = np.array([
        [6, 7, 6, 8, 7, 7],
        [1, 3, 0, 1, 5, 3],
        [4, 2, 2, 4, 4, 2]
    ]).transpose()
    assert np.array_equal(predicted_output, expected_output)

Different encoders per column:

And here is how a first standalone LabelEncoder will be applied on the pets, and a second will be shared for the columns owner and location. So to be precise, we here have a mix of different and shared label encoders:

    p = ColumnTransformer([
        # A different encoder will be used for column 0 with name "pets":
        (0, FlattenForEach(LabelEncoder(), then_unflatten=True)),
        # A shared encoder will be used for column 1 and 2, "owner" and "location":
        ([1, 2], FlattenForEach(LabelEncoder(), then_unflatten=True)),
    ], n_dimension=2)

Result:

    p, predicted_output = p.fit_transform(df.values)
    expected_output = np.array([
        [0, 1, 0, 2, 1, 1],
        [1, 3, 0, 1, 5, 3],
        [4, 2, 2, 4, 4, 2]
    ]).transpose()
    assert np.array_equal(predicted_output, expected_output)

How to make use of SQL (Oracle) to count the size of a string?

you need length() function

select length(customer_name) from ar.ra_customers

Python data structure sort list alphabetically

>>> a = ()
>>> type(a)
<type 'tuple'>
>>> a = []
>>> type(a)
<type 'list'>
>>> a = {}
>>> type(a)
<type 'dict'>
>>> a =  ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue'] 
>>> a.sort()
>>> a
['Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim', 'constitute']
>>> 

SSL handshake fails with - a verisign chain certificate - that contains two CA signed certificates and one self-signed certificate

Root certificates issued by CAs are just self-signed certificates (which may in turn be used to issue intermediate CA certificates). They have not much special about them, except that they've managed to be imported by default in many browsers or OS trust anchors.

While browsers and some tools are configured to look for the trusted CA certificates (some of which may be self-signed) in location by default, as far as I'm aware the openssl command isn't.

As such, any server that presents the full chain of certificate, from its end-entity certificate (the server's certificate) to the root CA certificate (possibly with intermediate CA certificates) will have a self-signed certificate in the chain: the root CA.

openssl s_client -connect myweb.com:443 -showcerts doesn't have any particular reason to trust Verisign's root CA certificate, and because it's self-signed you'll get "self signed certificate in certificate chain".

If your system has a location with a bundle of certificates trusted by default (I think /etc/pki/tls/certs on RedHat/Fedora and /etc/ssl/certs on Ubuntu/Debian), you can configure OpenSSL to use them as trust anchors, for example like this:

openssl s_client -connect myweb.com:443 -showcerts -CApath /etc/ssl/certs

Magento - Retrieve products with a specific attribute value

This is a follow up to my original question to help out others with the same problem. If you need to filter by an attribute, rather than manually looking up the id you can use the following code to retrieve all the id, value pairs for an attribute. The data is returned as an array with the attribute name as the key.

function getAttributeOptions($attributeName) {
    $product = Mage::getModel('catalog/product');
    $collection = Mage::getResourceModel('eav/entity_attribute_collection')
              ->setEntityTypeFilter($product->getResource()->getTypeId())
              ->addFieldToFilter('attribute_code', $attributeName);

    $_attribute = $collection->getFirstItem()->setEntity($product->getResource());
    $attribute_options  = $_attribute->getSource()->getAllOptions(false);
    foreach($attribute_options as $val) {
        $attrList[$val['label']] = $val['value'];
    }   

    return $attrList;
}

Here is a function you can use to get products by their attribute set id. Retrieved using the previous function.

function getProductsByAttributeSetId($attributeSetId) {
   $products = Mage::getModel('catalog/product')->getCollection();
   $products->addAttributeToFilter('attribute_set_id',$attributeSetId);

   $products->addAttributeToSelect('*');

   $products->load();
   foreach($products as $val) {
     $productsArray[] = $val->getData();
  }

  return $productsArray;
}

Getting Serial Port Information

I'm not quite sure what you mean by "sorting the items after index 0", but if you just want to sort the array of strings returned by SerialPort.GetPortNames(), you can use Array.Sort.

Return multiple values from a function in swift

Also:

func getTime() -> (hour: Int, minute: Int,second: Int) {
    let hour = 1
    let minute = 2
    let second = 3
    return ( hour, minute, second)
}

Then it's invoked as:

let time = getTime()
print("hour: \(time.hour), minute: \(time.minute), second: \(time.second)")

This is the standard way how to use it in the book The Swift Programming Language written by Apple.

or just like:

let time = getTime()
print("hour: \(time.0), minute: \(time.1), second: \(time.2)")

it's the same but less clearly.

How to hide element label by element id in CSS?

You have to give a separate id to the label too.

<label for="foo" id="foo_label">text</label>

#foo_label {display: none;}

Or hide the whole row

<tr id="foo_row">/***/</tr>

#foo_row {display: none;}

anaconda - graphviz - can't import after installation

I am using anaconda for the same.

I installed graphviz using conda install graphviz in anaconda prompt. and then installed pip install graphviz in the same command prompt. It worked for me.

Move a view up only when the keyboard covers an input field

Since there were no answer on how to do this in Combine, here is the approach i used.

  1. We create a publisher to listen to both Notifications, show and hide.
  2. For show we get the frame of the keyboard from the notifications userInfo and check if the current active responder is contained in it. If it's covered return keyboard frame height. If it is not covered return 0, we don't want to move the frame. For the hide notification we simply return 0.
private var keyboardHeightPublisher: AnyPublisher<CGFloat, Never> {
    Publishers.Merge(
        NotificationCenter.default
            .publisher(for: UIResponder.keyboardWillShowNotification)
            .compactMap { $0.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect }
            .map { $0.intersects(self.view.firstResponder!.frame) ? $0.height : 0 }
            .map { $0 * -1 },
        NotificationCenter.default
            .publisher(for: UIResponder.keyboardWillHideNotification)
            .map { _ in CGFloat(0) }
    ).eraseToAnyPublisher()
}

In the viewDidLoad we simply subscribe to the publisher changing the views frame accordingly.

override func viewDidLoad() {
    super.viewDidLoad()

    keyboardHeightPublisher.sink{ [weak self] height in
        self?.view.frame.origin.y = height
    }.store(in: &cancelables)
}

EDIT
Be careful! If the firstResponder is in a subview, you have to calculate the frame corresponding to the whole screen to check if they actually intersect.
Example:

let myViewGlobalFrame = myView.convert(myView.frame, to: parentView)

What is the difference between Scrum and Agile Development?

As mentioned above by others,

Scrum is an iterative and incremental agile software development method for managing software projects and product or application development. So Scrum is in fact a type of Agile approach which is used widely in software developments.

So, Scrum is a specific flavor of Agile, specifically it is referred to as an agile project management framework.

Also Scrum has mainly two roles inside it, which are: 1. Main/Core Role 2. Ancillary Role

Main/Core role: It consists of mainly three roles: a). Scrum Master, b). Product Owner, c). Development Team.

Ancillary Role: The ancillary roles in Scrum teams are those with no formal role and infrequent involvement in the Scrum procession but nonetheless, they must be taken into account. viz. Stakeholders, Managers.

Scrum Master:- There are 6 types of meetings in scrum:

  • Daily Scrum / Standup
  • Backlog grooming: storyline
  • Scrum of Scrums
  • Sprint Planning meeting
  • Sprint review meeting
  • Sprint retrospective

Let me know if any one need more inputs on this.

How can I close a Twitter Bootstrap popover with a click from anywhere (else) on the page?

Presuming that only one popover can be visible at any time, you can use a set of flags to mark when there's a popover visible, and only then hide them.

If you set the event listener on the document body, it will trigger when you click the element marked with 'popup-marker'. So you'll have to call stopPropagation() on the event object. And apply the same trick when clicking on the popover itself.

Below is a working JavaScript code that does this. It uses jQuery >= 1.7

jQuery(function() {
    var isVisible = false;

    var hideAllPopovers = function() {
       $('.popup-marker').each(function() {
            $(this).popover('hide');
        });  
    };

    $('.popup-marker').popover({
        html: true,
        trigger: 'manual'
    }).on('click', function(e) {
        // if any other popovers are visible, hide them
        if(isVisible) {
            hideAllPopovers();
        }

        $(this).popover('show');

        // handle clicking on the popover itself
        $('.popover').off('click').on('click', function(e) {
            e.stopPropagation(); // prevent event for bubbling up => will not get caught with document.onclick
        });

        isVisible = true;
        e.stopPropagation();
    });


    $(document).on('click', function(e) {
        hideAllPopovers();
        isVisible = false;
    });
});

http://jsfiddle.net/AFffL/539/

The only caveat is that you won't be able to open 2 popovers at the same time. But I think that would be confusing for the user, anyway :-)

How do I order my SQLITE database in descending order, for an android app?

SQLite ORDER BY clause is used to sort the data in an ascending or descending order, based on one or more columns. Cursor c = scoreDb.query(DATABASE_TABLE, rank, null, null, null, null, yourColumn+" DESC");

SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(
            TABLE_NAME,
            rank,
            null,
            null,
            null,
            null,
            COLUMN + " DESC",
            null);

Get started with Latex on Linux

I would personally use a complete editing package such as:

  • TexWorks
  • TexStudio

Then I would install "MikTeX" as the compiling package, which allows you to generate a PDF from your document, using the pdfLaTeX compiler.

Copy/Paste from Excel to a web page

On OSX and Windows , there are multiple types of clipboards for different types of content. When you copy content in Excel, data is stored in the plaintext and in the html clipboard.

The right way (that doesn't get tripped up by delimiter issues) is to parse the HTML. http://jsbin.com/uwuvan/5 is a simple demo that shows how to get the HTML clipboard. The key is to bind to the onpaste event and read

event.clipboardData.getData('text/html')

How do I resolve git saying "Commit your changes or stash them before you can merge"?

This is probably being caused by CRLF issues.

See: Why should I use core.autocrlf=true in Git?

Use this to pull and force update:

git pull origin master
git checkout origin/master -f

Lua - Current time in milliseconds

Kevlar is correct.

An alternative to a custom DLL is Lua Alien

Using Python, find anagrams for a list of words

import collections

def find_anagrams(x):
    anagrams = [''.join(sorted(list(i))) for i in x]
    anagrams_counts = [item for item, count in collections.Counter(anagrams).items() if count > 1]
    return [i for i in x if ''.join(sorted(list(i))) in anagrams_counts]

Scala: what is the best way to append an element to an Array?

You can use :+ to append element to array and +: to prepend it:

0 +: array :+ 4

should produce:

res3: Array[Int] = Array(0, 1, 2, 3, 4)

It's the same as with any other implementation of Seq.

Chosen Jquery Plugin - getting selected values

If anyone wants to get only the selected value on click to an option, he can do the follow:

$('.chosen-select').on('change', function(evt, params) {
    var selectedValue = params.selected;
    console.log(selectedValue);
});

File path for project files?

You would do something like this to get the path "Data\ich_will.mp3" inside your application environments folder.

string fileName = "ich_will.mp3";
string path = Path.Combine(Environment.CurrentDirectory, @"Data\", fileName);

In my case it would return the following:

C:\MyProjects\Music\MusicApp\bin\Debug\Data\ich_will.mp3

I use Path.Combine and Environment.CurrentDirectory in my example. These are very useful and allows you to build a path based on the current location of your application. Path.Combine combines two or more strings to create a location, and Environment.CurrentDirectory provides you with the working directory of your application.

The working directory is not necessarily the same path as where your executable is located, but in most cases it should be, unless specified otherwise.

How do I make an html link look like a button?

Much belated answer:

I've been wrestling with this on and off since I first started working in ASP. Here's the best I've come up with:

Concept: I create a custom control that has a tag. Then in the button I put an onclick event that sets document.location to the desired value with JavaScript.

I called the control ButtonLink, so that I could easily get if confused with LinkButton.

aspx:

<%@ Control Language="VB" AutoEventWireup="false" CodeFile="ButtonLink.ascx.vb" Inherits="controls_ButtonLink" %>

<asp:Button runat="server" ID="button"/>

code behind:

Partial Class controls_ButtonLink
Inherits System.Web.UI.UserControl

Dim _url As String
Dim _confirm As String

Public Property NavigateUrl As String
    Get
        Return _url
    End Get
    Set(value As String)
        _url = value
        BuildJs()
    End Set
End Property
Public Property confirm As String
    Get
        Return _confirm
    End Get
    Set(value As String)
        _confirm = value
        BuildJs()
    End Set
End Property
Public Property Text As String
    Get
        Return button.Text
    End Get
    Set(value As String)
        button.Text = value
    End Set
End Property
Public Property enabled As Boolean
    Get
        Return button.Enabled
    End Get
    Set(value As Boolean)
        button.Enabled = value
    End Set
End Property
Public Property CssClass As String
    Get
        Return button.CssClass
    End Get
    Set(value As String)
        button.CssClass = value
    End Set
End Property

Sub BuildJs()
    ' This is a little kludgey in that if the user gives a url and a confirm message, we'll build the onclick string twice.
    ' But it's not that big a deal.
    If String.IsNullOrEmpty(_url) Then
        button.OnClientClick = Nothing
    ElseIf String.IsNullOrEmpty(_confirm) Then
        button.OnClientClick = String.Format("document.location='{0}';return false;", ResolveClientUrl(_url))
    Else
        button.OnClientClick = String.Format("if (confirm('{0}')) {{document.location='{1}';}} return false;", _confirm, ResolveClientUrl(_url))
    End If
End Sub
End Class

Advantages of this scheme: It looks like a control. You write a single tag for it, <ButtonLink id="mybutton" navigateurl="blahblah"/>

The resulting button is a "real" HTML button and so looks just like a real button. You don't have to try to simulate the look of a button with CSS and then struggle with different looks on different browsers.

While the abilities are limited, you can easily extend it by adding more properties. It's likely that most properties would just have to "pass thru" to the underlying button, like I did for text, enabled and cssclass.

If anybody's got a simpler, cleaner or otherwise better solution, I'd be happy to hear it. This is a pain, but it works.

Get only the date in timestamp in mysql

You can convert that time in Unix timestamp by using

select UNIX_TIMESTAMP('2013-11-26 01:24:34')

then convert it in the readable format in whatever format you need

select from_unixtime(UNIX_TIMESTAMP('2013-11-26 01:24:34'),"%Y-%m-%d");

For in detail you can visit link

Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on

The data received in your serialPort1_DataReceived method is coming from another thread context than the UI thread, and that's the reason you see this error.
To remedy this, you will have to use a dispatcher as descibed in the MSDN article:
How to: Make Thread-Safe Calls to Windows Forms Controls

So instead of setting the text property directly in the serialport1_DataReceived method, use this pattern:

delegate void SetTextCallback(string text);

private void SetText(string text)
{
  // InvokeRequired required compares the thread ID of the
  // calling thread to the thread ID of the creating thread.
  // If these threads are different, it returns true.
  if (this.textBox1.InvokeRequired)
  { 
    SetTextCallback d = new SetTextCallback(SetText);
    this.Invoke(d, new object[] { text });
  }
  else
  {
    this.textBox1.Text = text;
  }
}

So in your case:

private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
  txt += serialPort1.ReadExisting().ToString();
  SetText(txt.ToString());
}

How to set JVM parameters for Junit Unit Tests?

I agree with the others who said that there is no simple way to distribute these settings.

For Eclipse: ask your colleagues to set the following:

  • Windows Preferences / Java / Installed JREs:
  • Select the proper JRE/JDK (or do it for all of them)
  • Edit
  • Default VM arguments: -Xmx1024m
  • Finish, OK.

After that all test will run with -Xmx1024m but unfortunately you have set it in every Eclipse installation. Maybe you could create a custom Eclipse package which contains this setting and give it to you co-workers.

The following working process also could help: If the IDE cannot run a test the developer should check that Maven could run this test or not.

  • If Maven could run it the cause of the failure usually is the settings of the developer's IDE. The developer should check these settings.
  • If Maven also could not run the test the developer knows that the cause of the failure is not the IDE, so he/she could use the IDE to debug the test.

jQuery counter to count up to a target number

I do not know about any existing plugins, but it seems fairly easy to write one yourself using the JavaScript Timing Events.

In a javascript array, how do I get the last 5 elements, excluding the first element?

If you are using lodash, its even simpler with takeRight.

_.takeRight(arr, 5);

Opening a remote machine's Windows C drive

If you need a drive letter (some applications don't like UNC style paths that start with a machine-name) you can "map a drive" to a UNC path. Right-click on "My Computer" and select Map Network Drive... or use this command line:

NET USE z: \server\c$\folder1\folder2

NET USE y: \server\d$

Note that you can map drive-to-drive or drill down and map to sub-folder.

Injecting @Autowired private field during testing

I believe in order to have auto-wiring work on your MyLauncher class (for myService), you will need to let Spring initialize it instead of calling the constructor, by auto-wiring myLauncher. Once that is being auto-wired (and myService is also getting auto-wired), Spring (1.4.0 and up) provides a @MockBean annotation you can put in your test. This will replace a matching single beans in context with a mock of that type. You can then further define what mocking you want, in a @Before method.

public class MyLauncherTest
    @MockBean
    private MyService myService;

    @Autowired
    private MyLauncher myLauncher;

    @Before
    private void setupMockBean() {
        doNothing().when(myService).someVoidMethod();
        doReturn("Some Value").when(myService).someStringMethod();
    }

    @Test
    public void someTest() {
        myLauncher.doSomething();
    }
}

Your MyLauncher class can then remain unmodified, and your MyService bean will be a mock whose methods return values as you defined:

@Component
public class MyLauncher {
    @Autowired
    MyService myService;

    public void doSomething() {
        myService.someVoidMethod();
        myService.someMethodThatCallsSomeStringMethod();
    }

    //other methods
}

A couple advantages of this over other methods mentioned is that:

  1. You don't need to manually inject myService.
  2. You don't need use the Mockito runner or rules.

Jquery get input array field

You can give your input textboxes class names, like so:

<input type="text" value="2" name="pages_title[1]" class="pages_title">
<input type="text" value="1" name="pages_title[2]" class="pages_title">

and iterate like so:

$('input.pages_title').each(function() {
    alert($(this).val()); 
});

How do I compile the asm generated by GCC?

Yes, gcc can also compile assembly source code. Alternatively, you can invoke as, which is the assembler. (gcc is just a "driver" program that uses heuristics to call C compiler, C++ compiler, assembler, linker, etc..)

python how to "negate" value : if true return false, if false return true

In python, not is a boolean operator which gets the opposite of a value:

>>> myval = 0
>>> nyvalue = not myval
>>> nyvalue
True
>>> myval = 1
>>> nyvalue = not myval
>>> nyvalue
False

And True == 1 and False == 0 (if you need to convert it to an integer, you can use int())

How can you debug a CORS request with cURL?

Here's how you can debug CORS requests using curl.

Sending a regular CORS request using cUrl:

curl -H "Origin: http://example.com" --verbose \
  https://www.googleapis.com/discovery/v1/apis?fields=

The -H "Origin: http://example.com" flag is the third party domain making the request. Substitute in whatever your domain is.

The --verbose flag prints out the entire response so you can see the request and response headers.

The url I'm using above is a sample request to a Google API that supports CORS, but you can substitute in whatever url you are testing.

The response should include the Access-Control-Allow-Origin header.

Sending a preflight request using cUrl:

curl -H "Origin: http://example.com" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: X-Requested-With" \
  -X OPTIONS --verbose \
  https://www.googleapis.com/discovery/v1/apis?fields=

This looks similar to the regular CORS request with a few additions:

The -H flags send additional preflight request headers to the server

The -X OPTIONS flag indicates that this is an HTTP OPTIONS request.

If the preflight request is successful, the response should include the Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers response headers. If the preflight request was not successful, these headers shouldn't appear, or the HTTP response won't be 200.

You can also specify additional headers, such as User-Agent, by using the -H flag.

Can I access constants in settings.py from templates in Django?

Add this code to a file called context_processors.py:

from django.conf import settings as django_settings


def settings(request):
    return {
        'settings': django_settings,
    }

And then, in your settings file, include a path such as 'speedy.core.base.context_processors.settings' (with your app name and path) in the 'context_processors' settings in TEMPLATES.

(You can see for example settings/base.py and context_processors.py).

Then you can use the specific setting in any template code. For example:

{% if settings.SITE_ID == settings.SPEEDY_MATCH_SITE_ID %}

Update: The code above exposes all the settings to templates, including sensitive information such as your SECRET_KEY. A hacker might abuse this feature to display such information in the templates. If you want to expose only specific settings to the templates, use this code instead:

def settings(request):
    settings_in_templates = {}
    for attr in ["SITE_ID", ...]: # Write here the settings you want to expose to the templates.
        if (hasattr(django_settings, attr)):
            settings_in_templates[attr] = getattr(django_settings, attr)
    return {
        'settings': settings_in_templates,
    }

check if a string matches an IP address pattern in python?

Install netaddr package

sudo pip install netaddr

And then you can do this

>>> from netaddr import valid_ipv4
>>> valid_ipv4('11.1.1.2') 
True
>>> valid_ipv4('11.1.1.a')
False

Also you create a IPAddress object from that string and a lot more ip related operations

>>> from netaddr import IPAddress
>>> ip = IPAddress('11.1.1.1')
>>> [f for f in dir(ip) if '__' not in f]
['_module', '_set_value', '_value', 'bin', 'bits', 'format', 'info', 'ipv4', 'ipv6', 'is_hostmask', 'is_ipv4_compat', 'is_ipv4_mapped', 'is_link_local', 'is_loopback', 'is_multicast', 'is_netmask', 'is_private', 'is_reserved', 'is_unicast', 'key', 'netmask_bits', 'packed', 'reverse_dns', 'sort_key', 'value', 'version', 'words']

PHP: Update multiple MySQL fields in single query

Add your multiple columns with comma separations:

UPDATE settings SET postsPerPage = $postsPerPage, style= $style WHERE id = '1'

However, you're not sanitizing your inputs?? This would mean any random hacker could destroy your database. See this question: What's the best method for sanitizing user input with PHP?

Also, is style a number or a string? I'm assuming a string, so it would need to be quoted.

How Spring Security Filter Chain works

The Spring security filter chain is a very complex and flexible engine.

Key filters in the chain are (in the order)

  • SecurityContextPersistenceFilter (restores Authentication from JSESSIONID)
  • UsernamePasswordAuthenticationFilter (performs authentication)
  • ExceptionTranslationFilter (catch security exceptions from FilterSecurityInterceptor)
  • FilterSecurityInterceptor (may throw authentication and authorization exceptions)

Looking at the current stable release 4.2.1 documentation, section 13.3 Filter Ordering you could see the whole filter chain's filter organization:

13.3 Filter Ordering

The order that filters are defined in the chain is very important. Irrespective of which filters you are actually using, the order should be as follows:

  1. ChannelProcessingFilter, because it might need to redirect to a different protocol

  2. SecurityContextPersistenceFilter, so a SecurityContext can be set up in the SecurityContextHolder at the beginning of a web request, and any changes to the SecurityContext can be copied to the HttpSession when the web request ends (ready for use with the next web request)

  3. ConcurrentSessionFilter, because it uses the SecurityContextHolder functionality and needs to update the SessionRegistry to reflect ongoing requests from the principal

  4. Authentication processing mechanisms - UsernamePasswordAuthenticationFilter, CasAuthenticationFilter, BasicAuthenticationFilter etc - so that the SecurityContextHolder can be modified to contain a valid Authentication request token

  5. The SecurityContextHolderAwareRequestFilter, if you are using it to install a Spring Security aware HttpServletRequestWrapper into your servlet container

  6. The JaasApiIntegrationFilter, if a JaasAuthenticationToken is in the SecurityContextHolder this will process the FilterChain as the Subject in the JaasAuthenticationToken

  7. RememberMeAuthenticationFilter, so that if no earlier authentication processing mechanism updated the SecurityContextHolder, and the request presents a cookie that enables remember-me services to take place, a suitable remembered Authentication object will be put there

  8. AnonymousAuthenticationFilter, so that if no earlier authentication processing mechanism updated the SecurityContextHolder, an anonymous Authentication object will be put there

  9. ExceptionTranslationFilter, to catch any Spring Security exceptions so that either an HTTP error response can be returned or an appropriate AuthenticationEntryPoint can be launched

  10. FilterSecurityInterceptor, to protect web URIs and raise exceptions when access is denied

Now, I'll try to go on by your questions one by one:

I'm confused how these filters are used. Is it that for the spring provided form-login, UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not? Does the form-login namespace element auto-configure these filters? Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

Once you are configuring a <security-http> section, for each one you must at least provide one authentication mechanism. This must be one of the filters which match group 4 in the 13.3 Filter Ordering section from the Spring Security documentation I've just referenced.

This is the minimum valid security:http element which can be configured:

<security:http authentication-manager-ref="mainAuthenticationManager" 
               entry-point-ref="serviceAccessDeniedHandler">
    <security:intercept-url pattern="/sectest/zone1/**" access="hasRole('ROLE_ADMIN')"/>
</security:http>

Just doing it, these filters are configured in the filter chain proxy:

{
        "1": "org.springframework.security.web.context.SecurityContextPersistenceFilter",
        "2": "org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter",
        "3": "org.springframework.security.web.header.HeaderWriterFilter",
        "4": "org.springframework.security.web.csrf.CsrfFilter",
        "5": "org.springframework.security.web.savedrequest.RequestCacheAwareFilter",
        "6": "org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter",
        "7": "org.springframework.security.web.authentication.AnonymousAuthenticationFilter",
        "8": "org.springframework.security.web.session.SessionManagementFilter",
        "9": "org.springframework.security.web.access.ExceptionTranslationFilter",
        "10": "org.springframework.security.web.access.intercept.FilterSecurityInterceptor"
    }

Note: I get them by creating a simple RestController which @Autowires the FilterChainProxy and returns it's contents:

    @Autowired
    private FilterChainProxy filterChainProxy;

    @Override
    @RequestMapping("/filterChain")
    public @ResponseBody Map<Integer, Map<Integer, String>> getSecurityFilterChainProxy(){
        return this.getSecurityFilterChainProxy();
    }

    public Map<Integer, Map<Integer, String>> getSecurityFilterChainProxy(){
        Map<Integer, Map<Integer, String>> filterChains= new HashMap<Integer, Map<Integer, String>>();
        int i = 1;
        for(SecurityFilterChain secfc :  this.filterChainProxy.getFilterChains()){
            //filters.put(i++, secfc.getClass().getName());
            Map<Integer, String> filters = new HashMap<Integer, String>();
            int j = 1;
            for(Filter filter : secfc.getFilters()){
                filters.put(j++, filter.getClass().getName());
            }
            filterChains.put(i++, filters);
        }
        return filterChains;
    }

Here we could see that just by declaring the <security:http> element with one minimum configuration, all the default filters are included, but none of them is of a Authentication type (4th group in 13.3 Filter Ordering section). So it actually means that just by declaring the security:http element, the SecurityContextPersistenceFilter, the ExceptionTranslationFilter and the FilterSecurityInterceptor are auto-configured.

In fact, one authentication processing mechanism should be configured, and even security namespace beans processing claims for that, throwing an error during startup, but it can be bypassed adding an entry-point-ref attribute in <http:security>

If I add a basic <form-login> to the configuration, this way:

<security:http authentication-manager-ref="mainAuthenticationManager">
    <security:intercept-url pattern="/sectest/zone1/**" access="hasRole('ROLE_ADMIN')"/>
    <security:form-login />
</security:http>

Now, the filterChain will be like this:

{
        "1": "org.springframework.security.web.context.SecurityContextPersistenceFilter",
        "2": "org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter",
        "3": "org.springframework.security.web.header.HeaderWriterFilter",
        "4": "org.springframework.security.web.csrf.CsrfFilter",
        "5": "org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter",
        "6": "org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter",
        "7": "org.springframework.security.web.savedrequest.RequestCacheAwareFilter",
        "8": "org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter",
        "9": "org.springframework.security.web.authentication.AnonymousAuthenticationFilter",
        "10": "org.springframework.security.web.session.SessionManagementFilter",
        "11": "org.springframework.security.web.access.ExceptionTranslationFilter",
        "12": "org.springframework.security.web.access.intercept.FilterSecurityInterceptor"
    }

Now, this two filters org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter and org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter are created and configured in the FilterChainProxy.

So, now, the questions:

Is it that for the spring provided form-login, UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not?

Yes, it is used to try to complete a login processing mechanism in case the request matches the UsernamePasswordAuthenticationFilter url. This url can be configured or even changed it's behaviour to match every request.

You could too have more than one Authentication processing mechanisms configured in the same FilterchainProxy (such as HttpBasic, CAS, etc).

Does the form-login namespace element auto-configure these filters?

No, the form-login element configures the UsernamePasswordAUthenticationFilter, and in case you don't provide a login-page url, it also configures the org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter, which ends in a simple autogenerated login page.

The other filters are auto-configured by default just by creating a <security:http> element with no security:"none" attribute.

Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

Every request should reach it, as it is the element which takes care of whether the request has the rights to reach the requested url. But some of the filters processed before might stop the filter chain processing just not calling FilterChain.doFilter(request, response);. For example, a CSRF filter might stop the filter chain processing if the request has not the csrf parameter.

What if I want to secure my REST API with JWT-token, which is retrieved from login? I must configure two namespace configuration http tags, rights? Other one for /login with UsernamePasswordAuthenticationFilter, and another one for REST url's, with custom JwtAuthenticationFilter.

No, you are not forced to do this way. You could declare both UsernamePasswordAuthenticationFilter and the JwtAuthenticationFilter in the same http element, but it depends on the concrete behaviour of each of this filters. Both approaches are possible, and which one to choose finnally depends on own preferences.

Does configuring two http elements create two springSecurityFitlerChains?

Yes, that's true

Is UsernamePasswordAuthenticationFilter turned off by default, until I declare form-login?

Yes, you could see it in the filters raised in each one of the configs I posted

How do I replace SecurityContextPersistenceFilter with one, which will obtain Authentication from existing JWT-token rather than JSESSIONID?

You could avoid SecurityContextPersistenceFilter, just configuring session strategy in <http:element>. Just configure like this:

<security:http create-session="stateless" >

Or, In this case you could overwrite it with another filter, this way inside the <security:http> element:

<security:http ...>  
   <security:custom-filter ref="myCustomFilter" position="SECURITY_CONTEXT_FILTER"/>    
</security:http>
<beans:bean id="myCustomFilter" class="com.xyz.myFilter" />

EDIT:

One question about "You could too have more than one Authentication processing mechanisms configured in the same FilterchainProxy". Will the latter overwrite the authentication performed by first one, if declaring multiple (Spring implementation) authentication filters? How this relates to having multiple authentication providers?

This finally depends on the implementation of each filter itself, but it's true the fact that the latter authentication filters at least are able to overwrite any prior authentication eventually made by preceding filters.

But this won't necesarily happen. I have some production cases in secured REST services where I use a kind of authorization token which can be provided both as a Http header or inside the request body. So I configure two filters which recover that token, in one case from the Http Header and the other from the request body of the own rest request. It's true the fact that if one http request provides that authentication token both as Http header and inside the request body, both filters will try to execute the authentication mechanism delegating it to the manager, but it could be easily avoided simply checking if the request is already authenticated just at the begining of the doFilter() method of each filter.

Having more than one authentication filter is related to having more than one authentication providers, but don't force it. In the case I exposed before, I have two authentication filter but I only have one authentication provider, as both of the filters create the same type of Authentication object so in both cases the authentication manager delegates it to the same provider.

And opposite to this, I too have a scenario where I publish just one UsernamePasswordAuthenticationFilter but the user credentials both can be contained in DB or LDAP, so I have two UsernamePasswordAuthenticationToken supporting providers, and the AuthenticationManager delegates any authentication attempt from the filter to the providers secuentially to validate the credentials.

So, I think it's clear that neither the amount of authentication filters determine the amount of authentication providers nor the amount of provider determine the amount of filters.

Also, documentation states SecurityContextPersistenceFilter is responsible of cleaning the SecurityContext, which is important due thread pooling. If I omit it or provide custom implementation, I have to implement the cleaning manually, right? Are there more similar gotcha's when customizing the chain?

I did not look carefully into this filter before, but after your last question I've been checking it's implementation, and as usually in Spring, nearly everything could be configured, extended or overwrited.

The SecurityContextPersistenceFilter delegates in a SecurityContextRepository implementation the search for the SecurityContext. By default, a HttpSessionSecurityContextRepository is used, but this could be changed using one of the constructors of the filter. So it may be better to write an SecurityContextRepository which fits your needs and just configure it in the SecurityContextPersistenceFilter, trusting in it's proved behaviour rather than start making all from scratch.

Using lambda expressions for event handlers

There are no performance implications since the compiler will translate your lambda expression into an equivalent delegate. Lambda expressions are nothing more than a language feature that the compiler translates into the exact same code that you are used to working with.

The compiler will convert the code you have to something like this:

public partial class MyPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //snip
        MyButton.Click += new EventHandler(delegate (Object o, EventArgs a) 
        {
            //snip
        });
    }
}

WCF Service Returning "Method Not Allowed"

you need to add in web.config

<endpoint address="customBinding" binding="customBinding" bindingConfiguration="basicConfig" contract="WcfRest.IService1"/>  

<bindings>  
    <customBinding>  
        <binding name="basicConfig">  
            <binaryMessageEncoding/>  
            <httpTransport transferMode="Streamed" maxReceivedMessageSize="67108864"/>  
        </binding>  
    </customBinding> 

Converting a byte array to PNG/JPG

There are two problems with this question:

Assuming you have a gray scale bitmap, you have two factors to consider:

  1. For JPGS... what loss of quality is tolerable?
  2. For pngs... what level of compression is tolerable? (Although for most things I've seen, you don't have that much of a choice, so this choice might be negligible.) For anybody thinking this question doesn't make sense: yes, you can change the amount of compression/number of passes attempted to compress; check out either Ifranview or some of it's plugins.

Answer those questions, and then you might be able to find your original answer.

How can I add a username and password to Jenkins?

You need to Enable security and set the security realm on the Configure Global Security page (see: Standard Security Setup) and choose the appropriate Authorization method (Security Realm).

Jenkins Security Realm, Hudson's own user database

Depending on your selection, create the user using appropriate method. Recommended method is to select Jenkins’ own user database and tick Allow users to sign up, hit Save button, then you should be able to create user from the Jenkins interface. Otherwise if you've chosen external database, you need to create the user there (e.g. if it's Unix database, use credentials of existing Linux/Unix users or create a standard user using shell interface).

See also: Creating user in Jenkins via API

What is the fastest way to send 100,000 HTTP requests in Python?

Things have changed quite a bit since 2010 when this was posted and I haven't tried all the other answers but I have tried a few, and I found this to work the best for me using python3.6.

I was able to fetch about ~150 unique domains per second running on AWS.

import pandas as pd
import concurrent.futures
import requests
import time

out = []
CONNECTIONS = 100
TIMEOUT = 5

tlds = open('../data/sample_1k.txt').read().splitlines()
urls = ['http://{}'.format(x) for x in tlds[1:]]

def load_url(url, timeout):
    ans = requests.head(url, timeout=timeout)
    return ans.status_code

with concurrent.futures.ThreadPoolExecutor(max_workers=CONNECTIONS) as executor:
    future_to_url = (executor.submit(load_url, url, TIMEOUT) for url in urls)
    time1 = time.time()
    for future in concurrent.futures.as_completed(future_to_url):
        try:
            data = future.result()
        except Exception as exc:
            data = str(type(exc))
        finally:
            out.append(data)

            print(str(len(out)),end="\r")

    time2 = time.time()

print(f'Took {time2-time1:.2f} s')
print(pd.Series(out).value_counts())

Declare variable in table valued function

There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.

This can not have a variable:

create function Func() returns table
as
return
select 10 as ColName

You have to do like this instead:

create function Func()
returns @T table(ColName int)
as
begin
  declare @Var int
  set @Var = 10
  insert into @T(ColName) values (@Var)
  return
end

Using (Ana)conda within PyCharm

Change the project interpreter to ~/anaconda2/python/bin by going to File -> Settings -> Project -> Project Interpreter. Also update the run configuration to use the project default Python interpreter via Run -> Edit Configurations. This makes PyCharm use Anaconda instead of the default Python interpreter under usr/bin/python27.

How do I get the backtrace for all the threads in GDB?

Generally, the backtrace is used to get the stack of the current thread, but if there is a necessity to get the stack trace of all the threads, use the following command.

thread apply all bt

How to create a dynamic array of integers

dynamically allocate some memory using new:

int* array = new int[SIZE];

Convert hex color value ( #ffffff ) to integer value

The real answer is to use:

Color.parseColor(myPassedColor) in Android, myPassedColor being the hex value like #000 or #000000 or #00000000.

However, this function does not support shorthand hex values such as #000.

Label word wrapping

Just set Label AutoSize property to False. Then the text will be wrapped and you can re-size the control manually to show the text.

How to allow remote access to my WAMP server for Mobile(Android)

I assume you are using windows. Open the command prompt and type ipconfig and find out your local address (on your pc) it should look something like 192.168.1.13 or 192.168.0.5 where the end digit is the one that changes. It should be next to IPv4 Address.

If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13 If you have a virtual host then you will need root to edit the hosts file.

If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.

See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.

Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).

If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow to allow,deny in the httpd.conf file. You can access this by the WAMP menu.

To eliminate possible causes of the issue for now set your config file to

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
    <RequireAll>
        Require all granted
    </RequireAll>
</Directory>

As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.

Config file that fixed the problem:

https://gist.github.com/samvaughton/6790739

Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.

What's the difference between struct and class in .NET?

Just to make it complete, there is another difference when using the Equals method, which is inherited by all classes and structures.

Lets's say we have a class and a structure:

class A{
  public int a, b;
}
struct B{
  public int a, b;
}

and in the Main method, we have 4 objects.

static void Main{
  A c1 = new A(), c2 = new A();
  c1.a = c1.b = c2.a = c2.b = 1;
  B s1 = new B(), s2 = new B();
  s1.a = s1.b = s2.a = s2.b = 1;
}

Then:

s1.Equals(s2) // true
s1.Equals(c1) // false
c1.Equals(c2) // false
c1 == c2 // false

So, structures are suited for numeric-like objects, like points (save x and y coordinates). And classes are suited for others. Even if 2 people have same name, height, weight..., they are still 2 people.

Html.DropDownList - Disabled/Readonly

Regarding the catch 22:

If we use @disabled, the field is not sent to the action (Mamoud) And if we use @readonly, the drop down bug still lets you change the value

Workaround: use @disabled, and add the field hidden after the drop down:

@Html.HiddenFor(model => model.xxxxxxxx)

Then it is truly disabled, and sent to the to the action too.

Which version of C# am I using

From developer command prompt type

csc -langversion:?

That will display all C# versions supported including the default:

1
2
3
4
5
6
7.0 (default)
7.1
7.2
7.3 (latest)

How to add a new audio (not mixing) into a video using ffmpeg?

Replace audio

diagram of audio stream replacement

ffmpeg -i video.mp4 -i audio.wav -map 0:v -map 1:a -c:v copy -shortest output.mp4
  • The -map option allows you to manually select streams / tracks. See FFmpeg Wiki: Map for more info.
  • This example uses -c:v copy to stream copy (mux) the video. No re-encoding of the video occurs. Quality is preserved and the process is fast.
    • If your input audio format is compatible with the output format then change -c:v copy to -c copy to stream copy both the video and audio.
    • If you want to re-encode video and audio then remove -c:v copy / -c copy.
  • The -shortest option will make the output the same duration as the shortest input.

Add audio

diagram of audio stream addition

ffmpeg -i video.mkv -i audio.mp3 -map 0 -map 1:a -c:v copy -shortest output.mkv
  • The -map option allows you to manually select streams / tracks. See FFmpeg Wiki: Map for more info.
  • This example uses -c:v copy to stream copy (mux) the video. No re-encoding of the video occurs. Quality is preserved and the process is fast.
    • If your input audio format is compatible with the output format then change -c:v copy to -c copy to stream copy both the video and audio.
    • If you want to re-encode video and audio then remove -c:v copy / -c copy.
  • The -shortest option will make the output the same duration as the shortest input.

Mixing/combining two audio inputs into one

diagram of audio downmix

Use video from video.mkv. Mix audio from video.mkv and audio.m4a using the amerge filter:

ffmpeg -i video.mkv -i audio.m4a -filter_complex "[0:a][1:a]amerge=inputs=2[a]" -map 0:v -map "[a]" -c:v copy -ac 2 -shortest output.mkv

See FFmpeg Wiki: Audio Channels for more info.

Generate silent audio

You can use the anullsrc filter to make a silent audio stream. The filter allows you to choose the desired channel layout (mono, stereo, 5.1, etc) and the sample rate.

ffmpeg -i video.mp4 -f lavfi -i anullsrc=channel_layout=stereo:sample_rate=44100 \
-c:v copy -shortest output.mp4

Also see

Forking vs. Branching in GitHub

You cannot always make a branch or pull an existing branch and push back to it, because you are not registered as a collaborator for that specific project.

Forking is nothing more than a clone on the GitHub server side:

  • without the possibility to directly push back
  • with fork queue feature added to manage the merge request

You keep a fork in sync with the original project by:

  • adding the original project as a remote
  • fetching regularly from that original project
  • rebase your current development on top of the branch of interest you got updated from that fetch.

The rebase allows you to make sure your changes are straightforward (no merge conflict to handle), making your pulling request that more easy when you want the maintainer of the original project to include your patches in his project.

The goal is really to allow collaboration even though direct participation is not always possible.


The fact that you clone on the GitHub side means you have now two "central" repository ("central" as "visible from several collaborators).
If you can add them directly as collaborator for one project, you don't need to manage another one with a fork.

fork on GitHub

The merge experience would be about the same, but with an extra level of indirection (push first on the fork, then ask for a pull, with the risk of evolutions on the original repo making your fast-forward merges not fast-forward anymore).
That means the correct workflow is to git pull --rebase upstream (rebase your work on top of new commits from upstream), and then git push --force origin, in order to rewrite the history in such a way your own commits are always on top of the commits from the original (upstream) repo.

See also:

Suppress Scientific Notation in Numpy When Creating Array From Nested List

for 1D and 2D arrays you can use np.savetxt to print using a specific format string:

>>> import sys
>>> x = numpy.arange(20).reshape((4,5))
>>> numpy.savetxt(sys.stdout, x, '%5.2f')
 0.00  1.00  2.00  3.00  4.00
 5.00  6.00  7.00  8.00  9.00
10.00 11.00 12.00 13.00 14.00
15.00 16.00 17.00 18.00 19.00

Your options with numpy.set_printoptions or numpy.array2string in v1.3 are pretty clunky and limited (for example no way to suppress scientific notation for large numbers). It looks like this will change with future versions, with numpy.set_printoptions(formatter=..) and numpy.array2string(style=..).

Node.js global proxy setting

While not a Nodejs setting, I suggest you use proxychains which I find rather convenient. It is probably available in your package manager.

After setting the proxy in the config file (/etc/proxychains.conf for me), you can run proxychains npm start or proxychains4 npm start (i.e. proxychains [command_to_proxy_transparently]) and all your requests will be proxied automatically.

Config settings for me:

These are the minimal settings you will have to append

## Exclude all localhost connections (dbs and stuff)
localnet 0.0.0.0/0.0.0.0
## Set the proxy type, ip and port here
http    10.4.20.103 8080

(You can get the ip of the proxy by using nslookup [proxyurl])

C non-blocking keyboard input

If you are happy just catching Control-C, it's a done deal. If you really want non-blocking I/O but you don't want the curses library, another alternative is to move lock, stock, and barrel to the AT&T sfio library. It's nice library patterned on C stdio but more flexible, thread-safe, and performs better. (sfio stands for safe, fast I/O.)

How do I find the duplicates in a list and create another list with them?

this is the way I had to do it because I challenged myself not to use other methods:

def dupList(oldlist):
    if type(oldlist)==type((2,2)):
        oldlist=[x for x in oldlist]
    newList=[]
    newList=newList+oldlist
    oldlist=oldlist
    forbidden=[]
    checkPoint=0
    for i in range(len(oldlist)):
        #print 'start i', i
        if i in forbidden:
            continue
        else:
            for j in range(len(oldlist)):
                #print 'start j', j
                if j in forbidden:
                    continue
                else:
                    #print 'after Else'
                    if i!=j: 
                        #print 'i,j', i,j
                        #print oldlist
                        #print newList
                        if oldlist[j]==oldlist[i]:
                            #print 'oldlist[i],oldlist[j]', oldlist[i],oldlist[j]
                            forbidden.append(j)
                            #print 'forbidden', forbidden
                            del newList[j-checkPoint]
                            #print newList
                            checkPoint=checkPoint+1
    return newList

so your sample works as:

>>>a = [1,2,3,3,3,4,5,6,6,7]
>>>dupList(a)
[1, 2, 3, 4, 5, 6, 7]

How do I find and replace all occurrences (in all files) in Visual Studio Code?

Update for 2020

If you are using the search feature to search across files (Ctrl + Shift + F) it can be easy to miss how to convert your search to a search and replace within the UI.

Here's a typical search result:

search result image

To convert this to a search and replace you need to click the arrow icon to the left of the search input field. This will open the replace options as seen below. Note the arrow icon is now pointed down.

search and replace image

The keyboard shortcut Ctrl + Shift + H will also work as well to access the search and replace.

Link to VSCode docs on search and replace: https://code.visualstudio.com/docs/editor/codebasics#_search-and-replace

Can I have an IF block in DOS batch file?

Logically, Cody's answer should work. However I don't think the command prompt handles a code block logically. For the life of me I can't get that to work properly with any more than a single command within the block. In my case, extensive testing revealed that all of the commands within the block are being cached, and executed simultaneously at the end of the block. This of course doesn't yield the expected results. Here is an oversimplified example:

if %ERRORLEVEL%==0 (
set var1=blue
set var2=cheese
set var3=%var1%_%var2%
)

This should provide var3 with the following value:

blue_cheese

but instead yields:

_

because all 3 commands are cached and executed simultaneously upon exiting the code block.

I was able to overcome this problem by re-writing the if block to only execute one command - goto - and adding a few labels. Its clunky, and I don't much like it, but at least it works.

if %ERRORLEVEL%==0 goto :error0
goto :endif

:error0
set var1=blue
set var2=cheese
set var3=%var1%_%var2%

:endif

jquery background-color change on focus and blur

#FFFFEEE is not a correct color code. Try with #FFFFEE instead.

Fixed point vs Floating point number

The term ‘fixed point’ refers to the corresponding manner in which numbers are represented, with a fixed number of digits after, and sometimes before, the decimal point. With floating-point representation, the placement of the decimal point can ‘float’ relative to the significant digits of the number. For example, a fixed-point representation with a uniform decimal point placement convention can represent the numbers 123.45, 1234.56, 12345.67, etc, whereas a floating-point representation could in addition represent 1.234567, 123456.7, 0.00001234567, 1234567000000000, etc.

Convert True/False value read from file to boolean

If your data is from json, you can do that

import json

json.loads('true')

True

What is the difference between an int and an Integer in Java and C#?

int is predefined in library function c# but in java we can create object of Integer

Jenkins - how to build a specific branch

Best solution can be:

Add a string parameter in the existing job enter image description here

Then in the Source Code Management section update Branches to build to use the string parameter you defined enter image description here

If you see a checkbox labeled Lightweight checkout, make sure it is unchecked.

The configuration indicated in the images will tell the jenkins job to use master as the default branch, and for manual builds it will ask you to enter branch details (FYI: by default it's set to master)enter image description here

Random "Element is no longer attached to the DOM" StaleElementReferenceException

I think I found convenient approach to handle StaleElementReferenceException. Usually you have to write wrappers for every WebElement method to retry actions, which is frustrating and wastes lots of time.

Adding this code

webDriverWait.until((webDriver1) -> (((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete")));

if ((Boolean) ((JavascriptExecutor) webDriver).executeScript("return window.jQuery != undefined")) {
    webDriverWait.until((webDriver1) -> (((JavascriptExecutor) webDriver).executeScript("return jQuery.active == 0")));
}

before every WebElement action can increase stability of your tests but you still can get StaleElementReferenceException from time to time.

So this is what I came up with (using AspectJ):

package path.to.your.aspects;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.pagefactory.DefaultElementLocator;
import org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Aspect
public class WebElementAspect {
    private static final Logger LOG = LogManager.getLogger(WebElementAspect.class);
    /**
     * Get your WebDriver instance from some kind of manager
     */
    private WebDriver webDriver = DriverManager.getWebDriver();
    private WebDriverWait webDriverWait = new WebDriverWait(webDriver, 10);

    /**
     * This will intercept execution of all methods from WebElement interface
     */
    @Pointcut("execution(* org.openqa.selenium.WebElement.*(..))")
    public void webElementMethods() {}

    /**
     * @Around annotation means that you can insert additional logic
     * before and after execution of the method
     */
    @Around("webElementMethods()")
    public Object webElementHandler(ProceedingJoinPoint joinPoint) throws Throwable {
        /**
         * Waiting until JavaScript and jQuery complete their stuff
         */
        waitUntilPageIsLoaded();

        /**
         * Getting WebElement instance, method, arguments
         */
        WebElement webElement = (WebElement) joinPoint.getThis();
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        Object[] args = joinPoint.getArgs();

        /**
         * Do some logging if you feel like it
         */
        String methodName = method.getName();

        if (methodName.contains("click")) {
            LOG.info("Clicking on " + getBy(webElement));
        } else if (methodName.contains("select")) {
            LOG.info("Selecting from " + getBy(webElement));
        } else if (methodName.contains("sendKeys")) {
            LOG.info("Entering " + args[0].toString() + " into " + getBy(webElement));
        }

        try {
            /**
             * Executing WebElement method
             */
            return joinPoint.proceed();
        } catch (StaleElementReferenceException ex) {
            LOG.debug("Intercepted StaleElementReferenceException");

            /**
             * Refreshing WebElement
             * You can use implementation from this blog
             * http://www.sahajamit.com/post/mystery-of-stale-element-reference-exception/
             * but remove staleness check in the beginning (if(!isElementStale(elem))), because we already caught exception
             * and it will result in an endless loop
             */
            webElement = StaleElementUtil.refreshElement(webElement);

            /**
             * Executing method once again on the refreshed WebElement and returning result
             */
            return method.invoke(webElement, args);
        }
    }

    private void waitUntilPageIsLoaded() {
        webDriverWait.until((webDriver1) -> (((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete")));

        if ((Boolean) ((JavascriptExecutor) webDriver).executeScript("return window.jQuery != undefined")) {
            webDriverWait.until((webDriver1) -> (((JavascriptExecutor) webDriver).executeScript("return jQuery.active == 0")));
        }
    }

    private static String getBy(WebElement webElement) {
        try {
            if (webElement instanceof RemoteWebElement) {
                try {
                    Field foundBy = webElement.getClass().getDeclaredField("foundBy");
                    foundBy.setAccessible(true);
                    return (String) foundBy.get(webElement);
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
            } else {
                LocatingElementHandler handler = (LocatingElementHandler) Proxy.getInvocationHandler(webElement);

                Field locatorField = handler.getClass().getDeclaredField("locator");
                locatorField.setAccessible(true);

                DefaultElementLocator locator = (DefaultElementLocator) locatorField.get(handler);

                Field byField = locator.getClass().getDeclaredField("by");
                byField.setAccessible(true);

                return byField.get(locator).toString();
            }
        } catch (IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
        }

        return null;
    }
}

To enable this aspect create file src\main\resources\META-INF\aop-ajc.xml and write

<aspectj>
    <aspects>
        <aspect name="path.to.your.aspects.WebElementAspect"/>
    </aspects>
</aspectj>

Add this to your pom.xml

<properties>
    <aspectj.version>1.9.1</aspectj.version>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.0</version>
            <configuration>
                <argLine>
                    -javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
                </argLine>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.aspectj</groupId>
                    <artifactId>aspectjweaver</artifactId>
                    <version>${aspectj.version}</version>
                </dependency>
            </dependencies>
        </plugin>
</build>

And thats all. Hope it helps.

'Connect-MsolService' is not recognized as the name of a cmdlet

I had to do this in that order:

Install-Module MSOnline
Install-Module AzureAD
Import-Module AzureAD

How to test if string exists in file with Bash?

If you just want to check the existence of one line, you do not need to create a file. E.g.,

if grep -xq "LINE_TO_BE_MATCHED" FILE_TO_LOOK_IN ; then
  # code for if it exists
else
  # code for if it does not exist
fi  

Using getResources() in non-activity class

We can use context Like this try now Where the parent is the ViewGroup.

Context context = parent.getContext();

onSaveInstanceState () and onRestoreInstanceState ()

In my case, onRestoreInstanceState was called when the activity was reconstructed after changing the device orientation. onCreate(Bundle) was called first, but the bundle didn't have the key/values I set with onSaveInstanceState(Bundle).

Right after, onRestoreInstanceState(Bundle) was called with a bundle that had the correct key/values.

image.onload event and browser cache

I have met the same issue today. After trying various method, I realize that just put the code of sizing inside $(window).load(function() {}) instead of document.ready would solve part of issue (if you are not ajaxing the page).

How to kill a process in MacOS?

I recently faced similar issue where the atom editor will not close. Neither was responding. Kill / kill -9 / force exit from Activity Monitor - didn't work. Finally had to restart my mac to close the app.

How to split a string in shell and get the last field

Using Bash.

$ var1="1:2:3:4:0"
$ IFS=":"
$ set -- $var1
$ eval echo  \$${#}
0

Email and phone Number Validation in android

Android has build-in patterns for email, phone number, etc, that you can use if you are building for Android API level 8 and above.

private boolean isValidEmail(CharSequence email) {
    if (!TextUtils.isEmpty(email)) {
        return Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }
    return false;
}

private boolean isValidPhoneNumber(CharSequence phoneNumber) {
    if (!TextUtils.isEmpty(phoneNumber)) {
        return Patterns.PHONE.matcher(phoneNumber).matches();
    }
    return false;
}

How to clear a textbox once a button is clicked in WPF?

There is one possible pitfall with using textBoxName.Text = string.Empty; and that is if you are using Text binding for your TextBox (i.e. <TextBox Text="{Binding Path=Description}"></TextBox>). In this case, setting an empty string will actually override and break your binding.

To prevent this behavior you have to use the Clear method:

textBoxName.Clear();

This way the TextBox will be cleared, but the binding will be kept intact.

"The page you are requesting cannot be served because of the extension configuration." error message

I've just had the same situation with my customer. We have our own product which installs a web site. The installer configures everything: the IIS pool, the site, web.config, etc.

We installed another web site using our installer. We entered the same parameters, so web.configs happened to be the same in both sites.

However, the newly installed site worked fine, while the old one didn't. Then I opened 2 IIS Manager windows and started comparing the difference in web site settings. And I found a problem.

Somebody deleted all the Handler Mappings with the old site. If you go to "Handler mappings", you should see there aspx, asmx and other extensions and names of the handlers. So, in the old site all those records were missing.

So, I would suggest first to check the "Handler mappings" - there must be a lot of records there. Create a new web site and compare to know how many should there be.

Who deleted them, a person or another program, I have no idea. If somebody can tell if there exists some tracking application which would tell that user domain\john was modifying web site at date "07.03.2012 12:34" that would be useful.

Loop Through Each HTML Table Column and Get the Data using jQuery

My first post...

I tried this: change 'tr' for 'td' and you will get all HTMLRowElements into an Array, and using textContent will change from Object into String

var dataArray = [];
var data = table.find('td'); //Get All HTML td elements

// Save important data into new Array
for (var i = 0; i <= data.size() - 1; i = i + 4)
{
  dataArray.push(data[i].textContent, data[i + 1].textContent, data[i + 2].textContent);
}

Finding all cycles in a directed graph

DFS c++ version for the pseudo-code in second floor's answer:

void findCircleUnit(int start, int v, bool* visited, vector<int>& path) {
    if(visited[v]) {
        if(v == start) {
            for(auto c : path)
                cout << c << " ";
            cout << endl;
            return;
        }
        else 
            return;
    }
    visited[v] = true;
    path.push_back(v);
    for(auto i : G[v])
        findCircleUnit(start, i, visited, path);
    visited[v] = false;
    path.pop_back();
}

Convert all strings in a list to int

Here is a simple solution with explanation for your query.

 a=['1','2','3','4','5'] #The integer represented as a string in this list
 b=[] #Fresh list
 for i in a: #Declaring variable (i) as an item in the list (a).
     b.append(int(i)) #Look below for explanation
 print(b)

Here, append() is used to add items ( i.e integer version of string (i) in this program ) to the end of the list (b).

Note: int() is a function that helps to convert an integer in the form of string, back to its integer form.

Output console:

[1, 2, 3, 4, 5]

So, we can convert the string items in the list to an integer only if the given string is entirely composed of numbers or else an error will be generated.

How to configure the web.config to allow requests of any length

I had a similar issue trying to deploy an ASP Web Application to IIS 8. To fix it I did as Matt and Leniel suggested above. But also had to configure the Authentication setting of my site to enable Anonymous Authentication. And that Worked for me.

Why can't DateTime.Parse parse UTC date

I've put together a utility method which employs all tips shown here plus some more:

    static private readonly string[] MostCommonDateStringFormatsFromWeb = {
        "yyyy'-'MM'-'dd'T'hh:mm:ssZ",  //     momentjs aka universal sortable with 'T'     2008-04-10T06:30:00Z          this is default format employed by moment().utc().format()
        "yyyy'-'MM'-'dd'T'hh:mm:ss.fffZ", //  syncfusion                                   2008-04-10T06:30:00.000Z      retarded string format for dates that syncfusion libs churn out when invoked by ejgrid for odata filtering and so on
        "O", //                               iso8601                                      2008-04-10T06:30:00.0000000
        "s", //                               sortable                                     2008-04-10T06:30:00
        "u"  //                               universal sortable                           2008-04-10 06:30:00Z
    };

    static public bool TryParseWebDateStringExactToUTC(
        out DateTime date,
        string input,
        string[] formats = null,
        DateTimeStyles? styles = null,
        IFormatProvider formatProvider = null
    )
    {
        formats = formats ?? MostCommonDateStringFormatsFromWeb;
        return TryParseDateStringExactToUTC(out date, input, formats, styles, formatProvider);
    }

    static public bool TryParseDateStringExactToUTC(
        out DateTime date,
        string input,
        string[] formats = null,
        DateTimeStyles? styles = null,
        IFormatProvider formatProvider = null
    )
    {
        styles = styles ?? DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal; //0 utc
        formatProvider = formatProvider ?? CultureInfo.InvariantCulture;

        var verdict = DateTime.TryParseExact(input, result: out date, style: styles.Value, formats: formats, provider: formatProvider);
        if (verdict && date.Kind == DateTimeKind.Local) //1
        {
            date = date.ToUniversalTime();
        }

        return verdict;

        //0 employing adjusttouniversal is vital in order for the resulting date to be in utc when the 'Z' flag is employed at the end of the input string
        //  like for instance in   2008-04-10T06:30.000Z
        //1 local should never happen with the default settings but it can happen when settings get overriden   we want to forcibly return utc though
    }

Notice the use of '-' and 'T' (single-quoted). This is done as a matter of best practice since regional settings interfere with the interpretation of chars such as '-' causing it to be interpreted as '/' or '.' or whatever your regional settings denote as date-components-separator. I have also included a second utility method which show-cases how to parse most commonly seen date-string formats fed to rest-api backends from web clients. Enjoy.

Define global variable with webpack

You can use define window.myvar = {}. When you want to use it, you can use like window.myvar = 1

Why does one use dependency injection?

I think the classic answer is to create a more decoupled application, which has no knowledge of which implementation will be used during runtime.

For example, we're a central payment provider, working with many payment providers around the world. However, when a request is made, I have no idea which payment processor I'm going to call. I could program one class with a ton of switch cases, such as:

class PaymentProcessor{

    private String type;

    public PaymentProcessor(String type){
        this.type = type;
    }

    public void authorize(){
        if (type.equals(Consts.PAYPAL)){
            // Do this;
        }
        else if(type.equals(Consts.OTHER_PROCESSOR)){
            // Do that;
        }
    }
}

Now imagine that now you'll need to maintain all this code in a single class because it's not decoupled properly, you can imagine that for every new processor you'll support, you'll need to create a new if // switch case for every method, this only gets more complicated, however, by using Dependency Injection (or Inversion of Control - as it's sometimes called, meaning that whoever controls the running of the program is known only at runtime, and not complication), you could achieve something very neat and maintainable.

class PaypalProcessor implements PaymentProcessor{

    public void authorize(){
        // Do PayPal authorization
    }
}

class OtherProcessor implements PaymentProcessor{

    public void authorize(){
        // Do other processor authorization
    }
}

class PaymentFactory{

    public static PaymentProcessor create(String type){

        switch(type){
            case Consts.PAYPAL;
                return new PaypalProcessor();

            case Consts.OTHER_PROCESSOR;
                return new OtherProcessor();
        }
    }
}

interface PaymentProcessor{
    void authorize();
}

** The code won't compile, I know :)

Difference between "process.stdout.write" and "console.log" in node.js?


Console.log implement process.sdout.write, process.sdout.write is a buffer/stream that will directly output in your console.

According to my puglin serverline : console = new Console(consoleOptions) you can rewrite Console class with your own readline system.

You can see code source of console.log:


See more :

Push eclipse project to GitHub with EGit

I have the same issue and solved it by reading this post, while solving it, I hitted a problem: auth failed.

And I finally solved it by using a ssh key way to authorize myself. I found the EGit offical guide very useful and I configured the ssh way successfully by refer to the Eclipse SSH Configuration section in the link provided.

Hope it helps.

Mailbox unavailable. The server response was: 5.7.1 Unable to relay for [email protected]

If you have Exchange 2010:

(In my case, the error message didn't contain " for [email protected]")

This shows how to add a receive connector: http://exchangeserverpro.com/how-to-configure-a-relay-connector-for-exchange-server-2010/

But I also needed to perform a step found here: http://recover-email.blogspot.com.au/2013/12/how-to-solve-exchange-smtp-server-error.html

  • Go to Exchange Management Shell and run the command
  • Get-ReceiveConnector "JiraTest" | Add-ADPermission -User "NT AUTHORITY\ANONYMOUS LOGON" -ExtendedRights "ms-Exch-SMTP-Accept-Any-Recipient"

While working on this, I ran the following on the affected server's PowerShell console until the error went away:

Send-MailMessage -From "[email protected]" -To "[email protected]" -Subject "Test Email" -Body "This is a test"

SQLite - UPSERT *not* INSERT or REPLACE

Following Aristotle Pagaltzis and the idea of COALESCE from Eric B’s answer, here it is an upsert option to update only few columns or insert full row if it does not exist.

In this case, imagine that title and content should be updated, keeping the other old values when existing and inserting supplied ones when name not found:

NOTE id is forced to be NULL when INSERT as it is supposed to be autoincrement. If it is just a generated primary key then COALESCE can also be used (see Aristotle Pagaltzis comment).

WITH new (id, name, title, content, author)
     AS ( VALUES(100, 'about', 'About this site', 'Whatever new content here', 42) )
INSERT OR REPLACE INTO page (id, name, title, content, author)
SELECT
     old.id, COALESCE(old.name, new.name),
     new.title, new.content,
     COALESCE(old.author, new.author)
FROM new LEFT JOIN page AS old ON new.name = old.name;

So the general rule would be, if you want to keep old values, use COALESCE, when you want to update values, use new.fieldname

MS Excel showing the formula in a cell instead of the resulting value

If all else fails, Ctrl-H (search and replace) with "=" in both boxes (in other words, search on = and replace it with the same =). Seems to do the trick.

What is difference between Axios and Fetch?

With fetch, we need to deal with two promises. With axios, we can directly access the JSON result inside the response object data property.

How do I calculate a point on a circle’s circumference?

Who needs trig when you have complex numbers:

#include <complex.h>
#include <math.h>

#define PI      3.14159265358979323846

typedef complex double Point;

Point point_on_circle ( double radius, double angle_in_degrees, Point centre )
{
    return centre + radius * cexp ( PI * I * ( angle_in_degrees  / 180.0 ) );
}

"%%" and "%/%" for the remainder and the quotient

Have a look at the examples below for a clearer understanding of the differences between the different operators:

> # Floating Division:
> 5/2
[1] 2.5
> 
> # Integer Division:
> 5%/%2
[1] 2
> 
> # Remainder:
> 5%%2
[1] 1

How to check if $? is not equal to zero in unix shell scripting?

if [ $var1 != $var2 ] 
then 
echo "$var1"
else 
echo "$var2"
fi

Is there any way to show a countdown on the lockscreen of iphone?

A today extension would be the most fitting solution.

Also you could do something on the lock screen with local notifications queued up to fire at regular intervals showing the latest countdown value.

Run R script from command line

One more way of running an R script from the command line would be:

R < scriptName.R --no-save  

or with --save.

See also What's the best way to use R scripts on the command line (terminal)?.

How to create a inset box-shadow only on one side?

Quite a bit late, but a duplicate answer that doesn't require altering the padding or adding extra divs can be found here: Have an issue with box-shadow Inset bottom only. It says, "Use a negative value for the fourth length which defines the spread distance. This is often overlooked, but supported by all major browsers"

From the answerer's fiddle:

box-shadow: inset 0 -10px 10px -10px #000000;

Exception in thread "main" java.lang.UnsupportedClassVersionError: a (Unsupported major.minor version 51.0)

Copy the contents of the PATH settings to a notepad and check if the location for the 1.4.2 comes before that of the 7. If so, remove the path to 1.4.2 in the PATH setting and save it.

After saving and applying "Environment Variables" close and reopen the cmd line. In XP the path does no get reflected in already running programs.

How to empty (clear) the logcat buffer in Android

The following command will clear only non-rooted buffers (main, system ..etc).

adb logcat -c

If you want to clear all the buffers (like radio, kernel..etc), Please use the following commands

adb root
adb logcat -b all -c

or

adb root
adb shell logcat -b all -c 

Use the following commands to know the list of buffers that device supports

adb logcat -g
adb logcat -b all -g
adb shell logcat -b all -g

How do I setup the InternetExplorerDriver so it works

Here is the exact solution, which worked in my case:

  1. On IE 7 or higher on Windows Vista or Windows 7, you must set the Protected Mode settings for each zone to be the same value. The value can be on or off, as long as it is the same for every zone. To set the Protected Mode settings, choose "Internet Options..." from the Tools menu, and click on the Security tab. For each zone, there will be a check box at the bottom of the tab labeled "Enable Protected Mode". Additionally, "Enhanced Protected Mode" must be disabled for IE 10 and higher. This option is found in the Advanced tab of the Internet Options dialog.

  2. System.setProperty("webdriver.ie.driver","C:\\Users\\ssin22\\Downloads\\IEDriverServer_x64_2.48.0\\IEDriverServer.exe");


package Testing;

import java.io.File;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class LaunchIE {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.setProperty("webdriver.ie.driver","C:\\Users\\ssin22\\Downloads\\IEDriverServer_x64_2.48.0\\IEDriverServer.exe");

    WebDriver driver=new InternetExplorerDriver();
    driver.get("http://google.com");

    }

}

Convert all first letter to upper case, rest lower for each word

If you're using on a web page, you can also use CSS:

style="text-transform:capitalize;"

How to create a shortcut using PowerShell

Beginning PowerShell 5.0 New-Item, Remove-Item, and Get-ChildItem have been enhanced to support creating and managing symbolic links. The ItemType parameter for New-Item accepts a new value, SymbolicLink. Now you can create symbolic links in a single line by running the New-Item cmdlet.

New-Item -ItemType SymbolicLink -Path "C:\temp" -Name "calc.lnk" -Value "c:\windows\system32\calc.exe"

Be Carefull a SymbolicLink is different from a Shortcut, shortcuts are just a file. They have a size (A small one, that just references where they point) and they require an application to support that filetype in order to be used. A symbolic link is filesystem level, and everything sees it as the original file. An application needs no special support to use a symbolic link.

Anyway if you want to create a Run As Administrator shortcut using Powershell you can use

$file="c:\temp\calc.lnk"
$bytes = [System.IO.File]::ReadAllBytes($file)
$bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON (Use –bor to set RunAsAdministrator option and –bxor to unset)
[System.IO.File]::WriteAllBytes($file, $bytes)

If anybody want to change something else in a .LNK file you can refer to official Microsoft documentation.

Creating a fixed sidebar alongside a centered Bootstrap 3 grid

As drew_w said, you can find a good example here.

HTML

<div id="wrapper">
    <div id="sidebar-wrapper">
        <ul class="sidebar-nav">
            <li class="sidebar-brand"><a href="#">Home</a></li>
            <li><a href="#">Another link</a></li>
            <li><a href="#">Next link</a></li>
            <li><a href="#">Last link</a></li>
        </ul>
    </div>
    <div id="page-content-wrapper">
        <div class="page-content">
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <!-- content of page -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

#wrapper {
  padding-left: 250px;
  transition: all 0.4s ease 0s;
}

#sidebar-wrapper {
  margin-left: -250px;
  left: 250px;
  width: 250px;
  background: #CCC;
  position: fixed;
  height: 100%;
  overflow-y: auto;
  z-index: 1000;
  transition: all 0.4s ease 0s;
}

#page-content-wrapper {
  width: 100%;
}

.sidebar-nav {
  position: absolute;
  top: 0;
  width: 250px;
  list-style: none;
  margin: 0;
  padding: 0;
}

@media (max-width:767px) {

    #wrapper {
      padding-left: 0;
    }

    #sidebar-wrapper {
      left: 0;
    }

    #wrapper.active {
      position: relative;
      left: 250px;
    }

    #wrapper.active #sidebar-wrapper {
      left: 250px;
      width: 250px;
      transition: all 0.4s ease 0s;
    }

}

JSFIDDLE

How do I find duplicates across multiple columns?

Duplicated id for pairs name and city:

select s.id, t.* 
from [stuff] s
join (
    select name, city, count(*) as qty
    from [stuff]
    group by name, city
    having count(*) > 1
) t on s.name = t.name and s.city = t.city

Twitter - share button, but with image

Look into twitter cards.

The trick is not in the button but rather the page you are sharing. Twitter Cards pull the image from the meta tags similar to facebook sharing.

Example:

<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="@site_username">
<meta name="twitter:title" content="Top 10 Things Ever">
<meta name="twitter:description" content="Up than 200 characters.">
<meta name="twitter:creator" content="@creator_username">
<meta name="twitter:image" content="http://placekitten.com/250/250">
<meta name="twitter:domain" content="YourDomain.com">

Generics/templates in python?

Python uses duck typing, so it doesn't need special syntax to handle multiple types.

If you're from a C++ background, you'll remember that, as long as the operations used in the template function/class are defined on some type T (at the syntax level), you can use that type T in the template.

So, basically, it works the same way:

  1. define a contract for the type of items you want to insert in the binary tree.
  2. document this contract (i.e. in the class documentation)
  3. implement the binary tree using only operations specified in the contract
  4. enjoy

You'll note however, that unless you write explicit type checking (which is usually discouraged), you won't be able to enforce that a binary tree contains only elements of the chosen type.

Python conversion between coordinates

If your coordinates are stored as complex numbers you can use cmath

reading HttpwebResponse json response, C#

I'd use RestSharp - https://github.com/restsharp/RestSharp

Create class to deserialize to:

public class MyObject {
    public string Id { get; set; }
    public string Text { get; set; }
    ...
}

And the code to get that object:

RestClient client = new RestClient("http://whatever.com");
RestRequest request = new RestRequest("path/to/object");
request.AddParameter("id", "123");

// The above code will make a request URL of 
// "http://whatever.com/path/to/object?id=123"
// You can pick and choose what you need

var response = client.Execute<MyObject>(request);

MyObject obj = response.Data;

Check out http://restsharp.org/ to get started.

How to determine the version of the C++ standard used by the compiler?

From the Bjarne Stroustrup C++0x FAQ:

__cplusplus

In C++11 the macro __cplusplus will be set to a value that differs from (is greater than) the current 199711L.

Although this isn't as helpful as one would like. gcc (apparently for nearly 10 years) had this value set to 1, ruling out one major compiler, until it was fixed when gcc 4.7.0 came out.

These are the C++ standards and what value you should be able to expect in __cplusplus:

  • C++ pre-C++98: __cplusplus is 1.
  • C++98: __cplusplus is 199711L.
  • C++98 + TR1: This reads as C++98 and there is no way to check that I know of.
  • C++11: __cplusplus is 201103L.
  • C++14: __cplusplus is 201402L.
  • C++17: __cplusplus is 201703L.

If the compiler might be an older gcc, we need to resort to compiler specific hackery (look at a version macro, compare it to a table with implemented features) or use Boost.Config (which provides relevant macros). The advantage of this is that we actually can pick specific features of the new standard, and write a workaround if the feature is missing. This is often preferred over a wholesale solution, as some compilers will claim to implement C++11, but only offer a subset of the features.

The Stdcxx Wiki hosts a comprehensive matrix for compiler support of C++0x features (archive.org link) (if you dare to check for the features yourself).

Unfortunately, more finely-grained checking for features (e.g. individual library functions like std::copy_if) can only be done in the build system of your application (run code with the feature, check if it compiled and produced correct results - autoconf is the tool of choice if taking this route).

Spark: Add column to dataframe conditionally

My bad, I had missed one part of the question.

Best, cleanest way is to use a UDF. Explanation within the code.

// create some example data...BY DataFrame
// note, third record has an empty string
case class Stuff(a:String,b:Int)
val d= sc.parallelize(Seq( ("a",1),("b",2),
     ("",3) ,("d",4)).map { x => Stuff(x._1,x._2)  }).toDF

// now the good stuff.
import org.apache.spark.sql.functions.udf
// function that returns 0 is string empty 
val func = udf( (s:String) => if(s.isEmpty) 0 else 1 )
// create new dataframe with added column named "notempty"
val r = d.select( $"a", $"b", func($"a").as("notempty") )

    scala> r.show
+---+---+--------+
|  a|  b|notempty|
+---+---+--------+
|  a|  1|    1111|
|  b|  2|    1111|
|   |  3|       0|
|  d|  4|    1111|
+---+---+--------+

Installing Bower on Ubuntu

on Ubuntu 12.04 and the packaged version of NodeJs is too old to install Bower using the PPA

sudo add-apt-repository ppa:chris-lea/node.js 
sudo apt-get update
sudo apt-get -y install nodejs

When this has installed, check the version:

npm --version
1.4.3

Now install Bower:

sudo npm install -g bower

This will fetch and install Bower globally.

Can PHP cURL retrieve response headers AND body in a single request?

Just set options :

  • CURLOPT_HEADER, 0

  • CURLOPT_RETURNTRANSFER, 1

and use curl_getinfo with CURLINFO_HTTP_CODE (or no opt param and you will have an associative array with all the informations you want)

More at : http://php.net/manual/fr/function.curl-getinfo.php

What is time(NULL) in C?

You can pass in a pointer to a time_t object that time will fill up with the current time (and the return value is the same one that you pointed to). If you pass in NULL, it just ignores it and merely returns a new time_t object that represents the current time.

Nb:time(&timer); is equivalent to timer = time(NULL);

How to update npm

You can try:

sudo npm i -g npm

What IDE to use for Python?

Results

Spreadsheet version

spreadsheet screenshot

Alternatively, in plain text: (also available as a a screenshot)

                         Bracket Matching -.  .- Line Numbering
                          Smart Indent -.  |  |  .- UML Editing / Viewing
         Source Control Integration -.  |  |  |  |  .- Code Folding
                    Error Markup -.  |  |  |  |  |  |  .- Code Templates
  Integrated Python Debugging -.  |  |  |  |  |  |  |  |  .- Unit Testing
    Multi-Language Support -.  |  |  |  |  |  |  |  |  |  |  .- GUI Designer (Qt, Eric, etc)
   Auto Code Completion -.  |  |  |  |  |  |  |  |  |  |  |  |  .- Integrated DB Support
     Commercial/Free -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  .- Refactoring
   Cross Platform -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom              |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |  |  |  |  |*many plugins
Editra            |Y |F |Y |Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |
Emacs             |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
Eric Ide          |Y |F |Y |  |Y |Y |  |Y |  |Y |  |Y |  |Y |  |  |  |
Geany             |Y |F |Y*|Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |*very limited
Gedit             |Y |F |Y¹|Y |  |  |  |Y |Y |Y |  |  |Y²|  |  |  |  |¹with plugin; ²sort of
Idle              |Y |F |Y |  |Y |  |  |Y |Y |  |  |  |  |  |  |  |  |
IntelliJ          |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit             |Y |F |  |Y |  |  |  |  |Y |Y |  |Y |  |  |  |  |  |
KDevelop          |Y |F |Y*|Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |*no type inference
Komodo            |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |Y |  |
NetBeans*         |Y |F |Y |Y |Y |  |Y |Y |Y |Y |Y |Y |Y |Y |  |  |Y |*pre-v7.0
Notepad++         |W |F |Y |Y |  |Y*|Y*|Y*|Y |Y |  |Y |Y*|  |  |  |  |*with plugin
Pfaide            |W |C |Y |Y |  |  |  |Y |Y |Y |  |Y |Y |  |  |  |  |
PIDA              |LW|F |Y |Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |VIM based
PTVS              |W |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |  |  |Y*|  |Y |*WPF bsed
PyCharm           |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse)   |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
PyScripter        |W |F |Y |  |Y |Y |  |Y |Y |Y |  |Y |Y |Y |  |  |  |
PythonWin         |W |F |Y |  |Y |  |  |Y |Y |  |  |Y |  |  |  |  |  |
SciTE             |Y |F¹|  |Y |  |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |¹Mac version is
ScriptDev         |W |C |Y |Y |Y |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |    commercial
Spyder            |Y |F |Y |  |Y |Y |  |Y |Y |Y |  |  |  |  |  |  |  |
Sublime Text      |Y |CF|Y |Y |  |Y |Y |Y |Y |Y |  |Y |Y |Y*|  |  |  |extensible w/Python,
TextMate          |M |F |  |Y |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |    *PythonTestRunner
UliPad            |Y |F |Y |Y |Y |  |  |Y |Y |  |  |  |Y |Y |  |  |  |
Vim               |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |
Visual Studio     |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde           |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |*support for C
Zeus              |W |C |  |  |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
   Cross Platform -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
     Commercial/Free -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  '- Refactoring
   Auto Code Completion -'  |  |  |  |  |  |  |  |  |  |  |  |  '- Integrated DB Support
    Multi-Language Support -'  |  |  |  |  |  |  |  |  |  |  '- GUI Designer (Qt, Eric, etc)
  Integrated Python Debugging -'  |  |  |  |  |  |  |  |  '- Unit Testing
                    Error Markup -'  |  |  |  |  |  |  '- Code Templates
         Source Control Integration -'  |  |  |  |  '- Code Folding
                          Smart Indent -'  |  |  '- UML Editing / Viewing
                         Bracket Matching -'  '- Line Numbering

Acronyms used:

 L  - Linux
 W  - Windows
 M  - Mac
 C  - Commercial
 F  - Free
 CF - Commercial with Free limited edition
 ?  - To be confirmed

I don't mention basics like syntax highlighting as I expect these by default.


This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.

PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?

We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments

Submit edits to the spreadsheet

Does Java support default parameter values?

NO, But we have alternative in the form of function overloading.

called when no parameter passed

void operation(){

int a = 0;
int b = 0;

} 

called when "a" parameter was passed

void operation(int a){

int b = 0;
//code

} 

called when parameter b passed

void operation(int a , int b){
//code
} 

Laravel Eloquent where field is X or null

Using coalesce() converts null to 0:

$query = Model::where('field1', 1)
    ->whereNull('field2')
    ->where(DB::raw('COALESCE(datefield_at,0)'), '<', $date)
;

Print commit message of a given commit in git

Not plumbing, but I have these in my .gitconfig:

lsum = log -n 1 --pretty=format:'%s'
lmsg = log -n 1 --pretty=format:'%s%n%n%b'

That's "last summary" and "last message". You can provide a commit to get the summary or message of that commit. (I'm using 1.7.0.5 so don't have %B.)

How to link home brew python version and set it as default

brew switch to python3 by default, so if you want to still set python2 as default bin python, running:

brew unlink python && brew link python2 --force

Test if a property is available on a dynamic variable

If you control the type being used as dynamic, couldn't you return a tuple instead of a value for every property access? Something like...

public class DynamicValue<T>
{
    internal DynamicValue(T value, bool exists)
    {
         Value = value;
         Exists = exists;
    }

    T Value { get; private set; }
    bool Exists { get; private set; }
}

Possibly a naive implementation, but if you construct one of these internally each time and return that instead of the actual value, you can check Exists on every property access and then hit Value if it does with value being default(T) (and irrelevant) if it doesn't.

That said, I might be missing some knowledge on how dynamic works and this might not be a workable suggestion.

Reference list item by index within Django template?

A better way: custom template filter: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

such as get my_list[x] in templates:

in template

{% load index %}
{{ my_list|index:x }}

templatetags/index.py

from django import template
register = template.Library()

@register.filter
def index(indexable, i):
    return indexable[i]

if my_list = [['a','b','c'], ['d','e','f']], you can use {{ my_list|index:x|index:y }} in template to get my_list[x][y]

It works fine with "for"

{{ my_list|index:forloop.counter0 }}

Tested and works well ^_^

In Python, how do I create a string of n characters in one line of code?

Why "one line"? You can fit anything onto one line.

Assuming you want them to start with 'a', and increment by one character each time (with wrapping > 26), here's a line:

>>> mkstring = lambda(x): "".join(map(chr, (ord('a')+(y%26) for y in range(x))))
>>> mkstring(10)
'abcdefghij'
>>> mkstring(30)
'abcdefghijklmnopqrstuvwxyzabcd'

Loading and parsing a JSON file with multiple JSON objects

That is ill-formatted. You have one JSON object per line, but they are not contained in a larger data structure (ie an array). You'll either need to reformat it so that it begins with [ and ends with ] with a comma at the end of each line, or parse it line by line as separate dictionaries.

How to loop through key/value object in Javascript?

Beware of properties inherited from the object's prototype (which could happen if you're including any libraries on your page, such as older versions of Prototype). You can check for this by using the object's hasOwnProperty() method. This is generally a good idea when using for...in loops:

var user = {};

function setUsers(data) {
    for (var k in data) {
        if (data.hasOwnProperty(k)) {
           user[k] = data[k];
        }
    }
}

How do you get the contextPath from JavaScript, the right way?

I render context path to attribute of link tag with id="contextPahtHolder" and then obtain it in JS code. For example:

<html>
    <head>
        <link id="contextPathHolder" data-contextPath="${pageContext.request.contextPath}"/>
    <body>
        <script src="main.js" type="text/javascript"></script>
    </body>
</html>

main.js

var CONTEXT_PATH = $('#contextPathHolder').attr('data-contextPath');
$.get(CONTEXT_PATH + '/action_url', function() {});

If context path is empty (like in embedded servlet container istance), it will be empty string. Otherwise it contains contextPath string

What is the simplest method of inter-process communication between 2 C# processes?

If your processes in same computer, you can simply use stdio.

This is my usage, a web page screenshooter:

var jobProcess = new Process();

jobProcess.StartInfo.FileName = Assembly.GetExecutingAssembly().Location;
jobProcess.StartInfo.Arguments = "job";

jobProcess.StartInfo.CreateNoWindow = false;
jobProcess.StartInfo.UseShellExecute = false;

jobProcess.StartInfo.RedirectStandardInput = true;
jobProcess.StartInfo.RedirectStandardOutput = true;
jobProcess.StartInfo.RedirectStandardError = true;

// Just Console.WriteLine it.
jobProcess.ErrorDataReceived += jp_ErrorDataReceived;

jobProcess.Start();

jobProcess.BeginErrorReadLine();

try
{
    jobProcess.StandardInput.WriteLine(url);
    var buf = new byte[int.Parse(jobProcess.StandardOutput.ReadLine())];
    jobProcess.StandardOutput.BaseStream.Read(buf, 0, buf.Length);
    return Deserz<Bitmap>(buf);
}
finally
{
    if (jobProcess.HasExited == false)
        jobProcess.Kill();
}

Detect args on Main

static void Main(string[] args)
{
    if (args.Length == 1 && args[0]=="job")
    {
        //because stdout has been used by send back, our logs should put to stderr
        Log.SetLogOutput(Console.Error); 

        try
        {
            var url = Console.ReadLine();
            var bmp = new WebPageShooterCr().Shoot(url);
            var buf = Serz(bmp);
            Console.WriteLine(buf.Length);
            System.Threading.Thread.Sleep(100);
            using (var o = Console.OpenStandardOutput())
                o.Write(buf, 0, buf.Length);
        }
        catch (Exception ex)
        {
            Log.E("Err:" + ex.Message);
        }
    }
    //...
}

ElasticSearch, Sphinx, Lucene, Solr, Xapian. Which fits for which usage?

Try indextank.

As the case of elastic search, it was conceived to be much easier to use than lucene/solr. It also includes very flexible scoring system that can be tweaked without reindexing.

How to add minutes to my Date

There's an error in the pattern of your SimpleDateFormat. it should be

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");

Modify request parameter with servlet filter

Try request.setAttribute("param",value);. It worked fine for me.

Please find this code sample:

private void sanitizePrice(ServletRequest request){
        if(request.getParameterValues ("price") !=  null){
            String price[] = request.getParameterValues ("price");

            for(int i=0;i<price.length;i++){
                price[i] = price[i].replaceAll("[^\\dA-Za-z0-9- ]", "").trim();
                System.out.println(price[i]);
            }
            request.setAttribute("price", price);
            //request.getParameter("numOfBooks").re
        }
    }

How to determine one year from now in Javascript

You should use getFullYear() instead of getYear(). getYear() returns the actual year minus 1900 (and so is fairly useless).

Thus a date marking exactly one year from the present moment would be:

var oneYearFromNow = new Date();
oneYearFromNow.setFullYear(oneYearFromNow.getFullYear() + 1);

Note that the date will be adjusted if you do that on February 29.

Similarly, you can get a date that's a month from now via getMonth() and setMonth(). You don't have to worry about "rolling over" from the current year into the next year if you do it in December; the date will be adjusted automatically. Same goes for day-of-month via getDate() and setDate().

How do I call a JavaScript function on page load?

If you want the onload method to take parameters, you can do something similar to this:

window.onload = function() {
  yourFunction(param1, param2);
};

This binds onload to an anonymous function, that when invoked, will run your desired function, with whatever parameters you give it. And, of course, you can run more than one function from inside the anonymous function.

Determining the current foreground application from a background task or service

Taking into account that getRunningTasks() is deprecated and getRunningAppProcesses() is not reliable, I came to decision to combine 2 approaches mentioned in StackOverflow:

   private boolean isAppInForeground(Context context)
    {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
        {
            ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
            ActivityManager.RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
            String foregroundTaskPackageName = foregroundTaskInfo.topActivity.getPackageName();

            return foregroundTaskPackageName.toLowerCase().equals(context.getPackageName().toLowerCase());
        }
        else
        {
            ActivityManager.RunningAppProcessInfo appProcessInfo = new ActivityManager.RunningAppProcessInfo();
            ActivityManager.getMyMemoryState(appProcessInfo);
            if (appProcessInfo.importance == IMPORTANCE_FOREGROUND || appProcessInfo.importance == IMPORTANCE_VISIBLE)
            {
                return true;
            }

            KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
            // App is foreground, but screen is locked, so show notification
            return km.inKeyguardRestrictedInputMode();
        }
    }

C# loop - break vs. continue

Break

Break forces a loop to exit immediately.

Continue

This does the opposite of break. Instead of terminating the loop, it immediately loops again, skipping the rest of the code.

How to run specific test cases in GoogleTest

Summarising @Rasmi Ranjan Nayak and @nogard answers and adding another option:

On the console

You should use the flag --gtest_filter, like

--gtest_filter=Test_Cases1*

(You can also do this in Properties|Configuration Properties|Debugging|Command Arguments)

On the environment

You should set the variable GTEST_FILTER like

export GTEST_FILTER = "Test_Cases1*"

On the code

You should set a flag filter, like

::testing::GTEST_FLAG(filter) = "Test_Cases1*";

such that your main function becomes something like

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    ::testing::GTEST_FLAG(filter) = "Test_Cases1*";
    return RUN_ALL_TESTS();
}

See section Running a Subset of the Tests for more info on the syntax of the string you can use.

How to schedule a stored procedure in MySQL

You can use mysql scheduler to run it each 5 seconds. You can find samples at http://dev.mysql.com/doc/refman/5.1/en/create-event.html

Never used it but I hope this would work:

CREATE EVENT myevent
    ON SCHEDULE EVERY 5 SECOND
    DO
      CALL delete_rows_links();

How to convert DateTime to a number with a precision greater than days in T-SQL?

Well, I would do it like this:

select datediff(minute,'1990-1-1',datetime)

where '1990-1-1' is an arbitrary base datetime.

Abstraction vs Encapsulation in Java

Abstraction is about identifying commonalities and reducing features that you have to work with at different levels of your code.

e.g. I may have a Vehicle class. A Car would derive from a Vehicle, as would a Motorbike. I can ask each Vehicle for the number of wheels, passengers etc. and that info has been abstracted and identified as common from Cars and Motorbikes.

In my code I can often just deal with Vehicles via common methods go(), stop() etc. When I add a new Vehicle type later (e.g. Scooter) the majority of my code would remain oblivious to this fact, and the implementation of Scooter alone worries about Scooter particularities.

How to get GET (query string) variables in Express.js on Node.js?

For Express.js you want to do req.params:

app.get('/user/:id', function(req, res) {
  res.send('user' + req.params.id);    
});

LaTeX source code listing like in professional books

I wonder why nobody mentioned the Minted package. It has far better syntax highlighting than the LaTeX listing package. It uses Pygments.

$ pip install Pygments

Example in LaTeX:

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}

\usepackage{minted}

\begin{document}
\begin{minted}{python}
import numpy as np

def incmatrix(genl1,genl2):
    m = len(genl1)
    n = len(genl2)
    M = None #to become the incidence matrix
    VT = np.zeros((n*m,1), int)  #dummy variable

    #compute the bitwise xor matrix
    M1 = bitxormatrix(genl1)
    M2 = np.triu(bitxormatrix(genl2),1) 

    for i in range(m-1):
        for j in range(i+1, m):
            [r,c] = np.where(M2 == M1[i,j])
            for k in range(len(r)):
                VT[(i)*n + r[k]] = 1;
                VT[(i)*n + c[k]] = 1;
                VT[(j)*n + r[k]] = 1;
                VT[(j)*n + c[k]] = 1;

                if M is None:
                    M = np.copy(VT)
                else:
                    M = np.concatenate((M, VT), 1)

                VT = np.zeros((n*m,1), int)

    return M
\end{minted}
\end{document}

Which results in:

enter image description here

You need to use the flag -shell-escape with the pdflatex command.

For more information: https://www.sharelatex.com/learn/Code_Highlighting_with_minted

How can I make a Python script standalone executable to run without ANY dependency?

I also recommend PyInstaller for better backward compatibility such as Python 2.3 - 2.7.

For py2exe, you have to have Python 2.6.

Java: Date from unix timestamp

For kotlin

fun unixToDate(timeStamp: Long) : String? {
    val time = java.util.Date(timeStamp as Long * 1000)
    val sdf = SimpleDateFormat("yyyy-MM-dd")
    return sdf.format(time)

}

What is the correct way to check for string equality in JavaScript?

String Objects can be checked using JSON.stringify() trick.

_x000D_
_x000D_
var me = new String("me");
var you = new String("me");
var isEquel = JSON.stringify(me) === JSON.stringify(you);
console.log(isEquel);
_x000D_
_x000D_
_x000D_

How do I obtain a list of all schemas in a Sql Server database

You can also query the INFORMATION_SCHEMA.SCHEMATA view:

SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA

I believe querying the INFORMATION_SCHEMA views is recommended as they protect you from changes to the underlying sys tables. From the SQL Server 2008 R2 Help:

Information schema views provide an internal, system table-independent view of the SQL Server metadata. Information schema views enable applications to work correctly although significant changes have been made to the underlying system tables. The information schema views included in SQL Server comply with the ISO standard definition for the INFORMATION_SCHEMA.

Ironically, this is immediately preceded by this note:

Some changes have been made to the information schema views that break backward compatibility. These changes are described in the topics for the specific views.

How do I use InputFilter to limit characters in an EditText in Android?

I found this on another forum. Works like a champ.

InputFilter filter = new InputFilter() {
    public CharSequence filter(CharSequence source, int start, int end,
            Spanned dest, int dstart, int dend) {
        for (int i = start; i < end; i++) {
            if (!Character.isLetterOrDigit(source.charAt(i))) {
                return "";
            }
        }
        return null;
    }
};
edit.setFilters(new InputFilter[] { filter });

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

next - it's like return, but for blocks! (So you can use this in any proc/lambda too.)

That means you can also say next n to "return" n from the block. For instance:

puts [1, 2, 3].map do |e|
  next 42 if e == 2
  e
end.inject(&:+)

This will yield 46.

Note that return always returns from the closest def, and never a block; if there's no surrounding def, returning is an error.

Using return from within a block intentionally can be confusing. For instance:

def my_fun
  [1, 2, 3].map do |e|
    return "Hello." if e == 2
    e
  end
end

my_fun will result in "Hello.", not [1, "Hello.", 2], because the return keyword pertains to the outer def, not the inner block.

Using If else in SQL Select statement

You can also use a union construct. I'm not sure if CASE is a common SQL construct ...

SELECT ID FROM tabName WHERE IDParent<1 OR IDParent IS NULL
UNION 
SELECT IDParent FROM tabName WHERE IDParent>1

IIS7 folder permissions for web application

If it's any help to anyone, give permission to "IIS_IUSRS" group.

Note that if you can't find "IIS_IUSRS", try prepending it with your server's name, like "MySexyServer\IIS_IUSRS".

Which HTML elements can receive focus?

Here I have a CSS-selector based on bobince's answer to select any focusable HTML element:

  a[href]:not([tabindex='-1']),
  area[href]:not([tabindex='-1']),
  input:not([disabled]):not([tabindex='-1']),
  select:not([disabled]):not([tabindex='-1']),
  textarea:not([disabled]):not([tabindex='-1']),
  button:not([disabled]):not([tabindex='-1']),
  iframe:not([tabindex='-1']),
  [tabindex]:not([tabindex='-1']),
  [contentEditable=true]:not([tabindex='-1'])
  {
      /* your CSS for focusable elements goes here */
  }

or a little more beautiful in SASS:

a[href],
area[href],
input:not([disabled]),
select:not([disabled]),
textarea:not([disabled]),
button:not([disabled]),
iframe,
[tabindex],
[contentEditable=true]
{
    &:not([tabindex='-1'])
    {
        /* your SCSS for focusable elements goes here */
    }
}

I've added it as an answer, because that was, what I was looking for, when Google redirected me to this Stackoverflow question.

EDIT: There is one more selector, which is focusable:

[contentEditable=true]

However, this is used very rarely.

Need to install urllib2 for Python 3.5.1

WARNING: Security researches have found several poisoned packages on PyPI, including a package named urllib, which will 'phone home' when installed. If you used pip install urllib some time after June 2017, remove that package as soon as possible.

You can't, and you don't need to.

urllib2 is the name of the library included in Python 2. You can use the urllib.request library included with Python 3, instead. The urllib.request library works the same way urllib2 works in Python 2. Because it is already included you don't need to install it.

If you are following a tutorial that tells you to use urllib2 then you'll find you'll run into more issues. Your tutorial was written for Python 2, not Python 3. Find a different tutorial, or install Python 2.7 and continue your tutorial on that version. You'll find urllib2 comes with that version.

Alternatively, install the requests library for a higher-level and easier to use API. It'll work on both Python 2 and 3.

Placeholder Mixin SCSS/CSS

You're looking for the @content directive:

@mixin placeholder {
  ::-webkit-input-placeholder {@content}
  :-moz-placeholder           {@content}
  ::-moz-placeholder          {@content}
  :-ms-input-placeholder      {@content}  
}

@include placeholder {
    font-style:italic;
    color: white;
    font-weight:100;
}

SASS Reference has more information, which can be found here: http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#mixin-content


As of Sass 3.4, this mixin can be written like so to work both nested and unnested:

@mixin optional-at-root($sel) {
  @at-root #{if(not &, $sel, selector-append(&, $sel))} {
    @content;
  }
}

@mixin placeholder {
  @include optional-at-root('::-webkit-input-placeholder') {
    @content;
  }

  @include optional-at-root(':-moz-placeholder') {
    @content;
  }

  @include optional-at-root('::-moz-placeholder') {
    @content;
  }

  @include optional-at-root(':-ms-input-placeholder') {
    @content;
  }
}

Usage:

.foo {
  @include placeholder {
    color: green;
  }
}

@include placeholder {
  color: red;
}

Output:

.foo::-webkit-input-placeholder {
  color: green;
}
.foo:-moz-placeholder {
  color: green;
}
.foo::-moz-placeholder {
  color: green;
}
.foo:-ms-input-placeholder {
  color: green;
}

::-webkit-input-placeholder {
  color: red;
}
:-moz-placeholder {
  color: red;
}
::-moz-placeholder {
  color: red;
}
:-ms-input-placeholder {
  color: red;
}

How to find the last day of the month from date?

I know this is a little bit late but i think there is a more elegant way of doing this with PHP 5.3+ by using the DateTime class :

$date = new DateTime('now');
$date->modify('last day of this month');
echo $date->format('Y-m-d');

How do you uninstall the package manager "pip", if installed from source?

If you installed pip like this:

 - sudo apt install python-pip
 - sudo apt install python3-pip

Uninstall them like this:

 - sudo apt remove python-pip
 - sudo apt remove python3-pip

How to POST a FORM from HTML to ASPX page

The Request.Form.Keys collection will be empty if none of your html inputs have NAMEs. It's easy to forget to put them there after you've been doing .NET for a while. Just name them and you'll be good to go.

Amazon S3 boto - how to create a folder?

With AWS SDK .Net works perfectly, just add "/" at the end of the folder name string:

var folderKey =  folderName + "/"; //end the folder name with "/"
AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(AWSAccessKey, AWSSecretKey);
var request = new PutObjectRequest();
request.WithBucketName(AWSBucket);
request.WithKey(folderKey);
request.WithContentBody(string.Empty);
S3Response response = client.PutObject(request);

Then refresh your AWS console, and you will see the folder

Python script header

From the manpage for env (GNU coreutils 6.10):

env - run a program in a modified environment

In theory you could use env to reset the environment (removing many of the existing environment variables) or add additional environment variables in the script header. Practically speaking, the two versions you mentioned are identical. (Though others have mentioned a good point: specifying python through env lets you abstractly specify python without knowing its path.)

Is it possible to center text in select box?

2020, Im using:

select {
    text-align: center;
    text-align-last: center;
    -moz-text-align-last: center;
}

Android ADB doesn't see device

For Windows 8 64 bit with a Nexus 10 device, this worked for me:

https://github.com/koush/UniversalAdbDriver

It has a link at the bottom to this:

http://download.clockworkmod.com/test/UniversalAdbDriverSetup.msi

Copy Files from Windows to the Ubuntu Subsystem

You should be able to access your windows system under the /mnt directory. For example inside of bash, use this to get to your pictures directory:

cd /mnt/c/Users/<ubuntu.username>/Pictures

Hope this helps!

.bashrc: Permission denied

.bashrc is not meant to be executed but sourced. Try this instead:

. ~/.bashrc

Cheers!

Does C have a string type?

C does not and never has had a native string type. By convention, the language uses arrays of char terminated with a null char, i.e., with '\0'. Functions and macros in the language's standard libraries provide support for the null-terminated character arrays, e.g., strlen iterates over an array of char until it encounters a '\0' character and strcpy copies from the source string until it encounters a '\0'.

The use of null-terminated strings in C reflects the fact that C was intended to be only a little more high-level than assembly language. Zero-terminated strings were already directly supported at that time in assembly language for the PDP-10 and PDP-11.

It is worth noting that this property of C strings leads to quite a few nasty buffer overrun bugs, including serious security flaws. For example, if you forget to null-terminate a character string passed as the source argument to strcpy, the function will keep copying sequential bytes from whatever happens to be in memory past the end of the source string until it happens to encounter a 0, potentially overwriting whatever valuable information follows the destination string's location in memory.

In your code example, the string literal "Hello, world!" will be compiled into a 14-byte long array of char. The first 13 bytes will hold the letters, comma, space, and exclamation mark and the final byte will hold the null-terminator character '\0', automatically added for you by the compiler. If you were to access the array's last element, you would find it equal to 0. E.g.:

const char foo[] = "Hello, world!";
assert(foo[12] == '!');
assert(foo[13] == '\0');

However, in your example, message is only 10 bytes long. strcpy is going to write all 14 bytes, including the null-terminator, into memory starting at the address of message. The first 10 bytes will be written into the memory allocated on the stack for message and the remaining four bytes will simply be written on to the end of the stack. The consequence of writing those four extra bytes onto the stack is hard to predict in this case (in this simple example, it might not hurt a thing), but in real-world code it usually leads to corrupted data or memory access violation errors.

Is there an Eclipse plugin to run system shell in the Console?

In Eclipse 3.7, I found a terminal view plugin that I installed through Eclipse Marketplace. Details are as follow:

Local Terminal (Incubation) http://market.eclipsesource.com/yoxos/node/org.eclipse.tm.terminal.local.feature.group

A terminal emulation for local shells and external tools. Requires CDT Core 7.0 or later. Works on Linux, Solaris and Mac. Includes Source.

Side note, this terminal does not execute .bash_profile or .bashrc so you can do

source ~/.bash_profile

and (if this isn't sourced by `.bash_profile)

source ~/.bashrc

Update:

This is actually was base for Terminal plug-in for Eclipse fork. Quote from http://alexruiz.developerblogs.com/?p=2428

Uwe Stieber July 23, 2013 at 12:57 am

Alex, why not aiming for rejoining your work with the original TM Terminal? I’ve checked and haven’t found any bugzilla asking for missing features or pointing out bugs. There had been changes to the original Terminal control, so I’m not sure if all of your original reasons to clone it are still true.

How to resize superview to fit all subviews with autolayout?

Eric Baker's comment tipped me off to the core idea that in order for a view to have its size be determined by the content placed within it, then the content placed within it must have an explicit relationship with the containing view in order to drive its height (or width) dynamically. "Add subview" does not create this relationship as you might assume. You have to choose which subview is going to drive the height and/or width of the container... most commonly whatever UI element you have placed in the lower right hand corner of your overall UI. Here's some code and inline comments to illustrate the point.

Note, this may be of particular value to those working with scroll views since it's common to design around a single content view that determines its size (and communicates this to the scroll view) dynamically based on whatever you put in it. Good luck, hope this helps somebody out there.

//
//  ViewController.m
//  AutoLayoutDynamicVerticalContainerHeight
//

#import "ViewController.h"

@interface ViewController ()
@property (strong, nonatomic) UIView *contentView;
@property (strong, nonatomic) UILabel *myLabel;
@property (strong, nonatomic) UILabel *myOtherLabel;
@end

@implementation ViewController

- (void)viewDidLoad
{
    // INVOKE SUPER
    [super viewDidLoad];

    // INIT ALL REQUIRED UI ELEMENTS
    self.contentView = [[UIView alloc] init];
    self.myLabel = [[UILabel alloc] init];
    self.myOtherLabel = [[UILabel alloc] init];
    NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(_contentView, _myLabel, _myOtherLabel);

    // TURN AUTO LAYOUT ON FOR EACH ONE OF THEM
    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    self.myLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.myOtherLabel.translatesAutoresizingMaskIntoConstraints = NO;

    // ESTABLISH VIEW HIERARCHY
    [self.view addSubview:self.contentView]; // View adds content view
    [self.contentView addSubview:self.myLabel]; // Content view adds my label (and all other UI... what's added here drives the container height (and width))
    [self.contentView addSubview:self.myOtherLabel];

    // LAYOUT

    // Layout CONTENT VIEW (Pinned to left, top. Note, it expects to get its vertical height (and horizontal width) dynamically based on whatever is placed within).
    // Note, if you don't want horizontal width to be driven by content, just pin left AND right to superview.
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to left, no horizontal width yet
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to top, no vertical height yet

    /* WHATEVER WE ADD NEXT NEEDS TO EXPLICITLY "PUSH OUT ON" THE CONTAINING CONTENT VIEW SO THAT OUR CONTENT DYNAMICALLY DETERMINES THE SIZE OF THE CONTAINING VIEW */
    // ^To me this is what's weird... but okay once you understand...

    // Layout MY LABEL (Anchor to upper left with default margin, width and height are dynamic based on text, font, etc (i.e. UILabel has an intrinsicContentSize))
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];

    // Layout MY OTHER LABEL (Anchored by vertical space to the sibling label that comes before it)
    // Note, this is the view that we are choosing to use to drive the height (and width) of our container...

    // The LAST "|" character is KEY, it's what drives the WIDTH of contentView (red color)
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];

    // Again, the LAST "|" character is KEY, it's what drives the HEIGHT of contentView (red color)
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_myLabel]-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];

    // COLOR VIEWS
    self.view.backgroundColor = [UIColor purpleColor];
    self.contentView.backgroundColor = [UIColor redColor];
    self.myLabel.backgroundColor = [UIColor orangeColor];
    self.myOtherLabel.backgroundColor = [UIColor greenColor];

    // CONFIGURE VIEWS

    // Configure MY LABEL
    self.myLabel.text = @"HELLO WORLD\nLine 2\nLine 3, yo";
    self.myLabel.numberOfLines = 0; // Let it flow

    // Configure MY OTHER LABEL
    self.myOtherLabel.text = @"My OTHER label... This\nis the UI element I'm\narbitrarily choosing\nto drive the width and height\nof the container (the red view)";
    self.myOtherLabel.numberOfLines = 0;
    self.myOtherLabel.font = [UIFont systemFontOfSize:21];
}

@end

How to resize superview to fit all subviews with autolayout.png

Drawing rotated text on a HTML5 canvas

Like others have mentioned, you probably want to look at reusing an existing graphing solution, but rotating text isn't too difficult. The somewhat confusing bit (to me) is that you rotate the whole context and then draw on it:

ctx.rotate(Math.PI*2/(i*6));

The angle is in radians. The code is taken from this example, which I believe was made for the transformations part of the MDC canvas tutorial.

Please see the answer below for a more complete solution.

Android ADB device offline, can't issue commands

Try running adb devices after running adb kill-server. Security question pops up after that. Worked for me.

How to assign Php variable value to Javascript variable?

The most secure way (in terms of special character and data type handling) is using json_encode():

var spge = <?php echo json_encode($cname); ?>;

Detect if string contains any spaces

A secondary option would be to check otherwise, with not space (\S), using an expression similar to:

^\S+$

Test

_x000D_
_x000D_
function has_any_spaces(regex, str) {_x000D_
 if (regex.test(str) || str === '') {_x000D_
  return false;_x000D_
 }_x000D_
 return true;_x000D_
}_x000D_
_x000D_
const expression = /^\S+$/g;_x000D_
const string = 'foo  baz bar';_x000D_
_x000D_
console.log(has_any_spaces(expression, string));
_x000D_
_x000D_
_x000D_

Here, we can for instance push strings without spaces into an array:

_x000D_
_x000D_
const regex = /^\S+$/gm;_x000D_
const str = `_x000D_
foo_x000D_
foo baz_x000D_
bar_x000D_
foo baz bar_x000D_
abc_x000D_
abc abc_x000D_
abc abc abc_x000D_
`;_x000D_
let m, arr = [];_x000D_
_x000D_
while ((m = regex.exec(str)) !== null) {_x000D_
 // This is necessary to avoid infinite loops with zero-width matches_x000D_
 if (m.index === regex.lastIndex) {_x000D_
  regex.lastIndex++;_x000D_
 }_x000D_
_x000D_
 // Here, we push those strings without spaces in an array_x000D_
 m.forEach((match, groupIndex) => {_x000D_
  arr.push(match);_x000D_
 });_x000D_
}_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

MVC 4 Razor File Upload

Clarifying it. Model:

public class ContactUsModel
{
    public string FirstName { get; set; }             
    public string LastName { get; set; }              
    public string Email { get; set; }                 
    public string Phone { get; set; }                 
    public HttpPostedFileBase attachment { get; set; }

Post Action

public virtual ActionResult ContactUs(ContactUsModel Model)
{
 if (Model.attachment.HasFile())
 {
   //save the file

   //Send it as an attachment 
    Attachment messageAttachment = new Attachment(Model.attachment.InputStream,       Model.attachment.FileName);
  }
}

Finally the Extension method for checking the hasFile

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AtlanticCMS.Web.Common
{
     public static class ExtensionMethods 
     {
         public static bool HasFile(this HttpPostedFileBase file)
         {
             return file != null && file.ContentLength > 0;
         }        
     }
 }

In Python, how do I read the exif data for an image?

import sys
import PIL
import PIL.Image as PILimage
from PIL import ImageDraw, ImageFont, ImageEnhance
from PIL.ExifTags import TAGS, GPSTAGS



class Worker(object):
    def __init__(self, img):
        self.img = img
        self.exif_data = self.get_exif_data()
        self.lat = self.get_lat()
        self.lon = self.get_lon()
        self.date =self.get_date_time()
        super(Worker, self).__init__()

    @staticmethod
    def get_if_exist(data, key):
        if key in data:
            return data[key]
        return None

    @staticmethod
    def convert_to_degress(value):
        """Helper function to convert the GPS coordinates
        stored in the EXIF to degress in float format"""
        d0 = value[0][0]
        d1 = value[0][1]
        d = float(d0) / float(d1)
        m0 = value[1][0]
        m1 = value[1][1]
        m = float(m0) / float(m1)

        s0 = value[2][0]
        s1 = value[2][1]
        s = float(s0) / float(s1)

        return d + (m / 60.0) + (s / 3600.0)

    def get_exif_data(self):
        """Returns a dictionary from the exif data of an PIL Image item. Also
        converts the GPS Tags"""
        exif_data = {}
        info = self.img._getexif()
        if info:
            for tag, value in info.items():
                decoded = TAGS.get(tag, tag)
                if decoded == "GPSInfo":
                    gps_data = {}
                    for t in value:
                        sub_decoded = GPSTAGS.get(t, t)
                        gps_data[sub_decoded] = value[t]

                    exif_data[decoded] = gps_data
                else:
                    exif_data[decoded] = value
        return exif_data

    def get_lat(self):
        """Returns the latitude and longitude, if available, from the 
        provided exif_data (obtained through get_exif_data above)"""
        # print(exif_data)
        if 'GPSInfo' in self.exif_data:
            gps_info = self.exif_data["GPSInfo"]
            gps_latitude = self.get_if_exist(gps_info, "GPSLatitude")
            gps_latitude_ref = self.get_if_exist(gps_info, 'GPSLatitudeRef')
            if gps_latitude and gps_latitude_ref:
                lat = self.convert_to_degress(gps_latitude)
                if gps_latitude_ref != "N":
                    lat = 0 - lat
                lat = str(f"{lat:.{5}f}")
                return lat
        else:
            return None

    def get_lon(self):
        """Returns the latitude and longitude, if available, from the 
        provided exif_data (obtained through get_exif_data above)"""
        # print(exif_data)
        if 'GPSInfo' in self.exif_data:
            gps_info = self.exif_data["GPSInfo"]
            gps_longitude = self.get_if_exist(gps_info, 'GPSLongitude')
            gps_longitude_ref = self.get_if_exist(gps_info, 'GPSLongitudeRef')
            if gps_longitude and gps_longitude_ref:
                lon = self.convert_to_degress(gps_longitude)
                if gps_longitude_ref != "E":
                    lon = 0 - lon
                lon = str(f"{lon:.{5}f}")
                return lon
        else:
            return None

    def get_date_time(self):
        if 'DateTime' in self.exif_data:
            date_and_time = self.exif_data['DateTime']
            return date_and_time 

if __name__ == '__main__':
    try:
        img = PILimage.open(sys.argv[1])
        image = Worker(img)
        lat = image.lat
        lon = image.lon
        date = image.date
        print(date, lat, lon)

    except Exception as e:
        print(e)

How to get address of a pointer in c/c++?

Having this C source:

int a = 10;
int * ptr = &a;

Use this

printf("The address of ptr is %p\n", (void *) &ptr);

to print the address of ptr.

Please note that the conversion specifier p is the only conversion specifier to print a pointer's value and it is defined to be used with void* typed pointers only.

From man printf:

p

The void * pointer argument is printed in hexadecimal (as if by %#x or %#lx).

<> And Not In VB.NET

The C# and VB.NET compilers often generate different IL for operations that are apparently equivalent in both languages. It just so happens that C# does the "expected" thing when you write stringvar == null, but VB.NET does not. To get the same effect in VB.NET you have to force true reference equality with the Is operator.

Checking if a variable is initialized

Variable that is not defined will cause compilation error.

What you're asking is about checking if it is initialized. But initialization is just a value, that you should choose and assign in the constructor.

For example:

class MyClass
{
    MyClass() : mCharacter('0'), mDecimal(-1.0){};
    void SomeMethod();

    char mCharacter;
    double mDecimal;
};

void MyClass::SomeMethod()
{
    if ( mCharacter != '0')
    {
        // touched after the constructor
        // do something with mCharacter.
    }

    if ( mDecimal != -1.0 )
    {
        // touched after the constructor
        // define mDecimal.
    }
}

You should initialize to a default value that will mean something in the context of your logic, of course.

What's the best way to override a user agent CSS stylesheet rule that gives unordered-lists a 1em margin?

put this in your "head" of your index.html

 <style>
  html body{
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    margin: 0;
  }
  </style>

How do I drop a foreign key constraint only if it exists in sql server?

ALTER TABLE [dbo].[TableName]
    DROP CONSTRAINT FK_TableName_TableName2

How can I print out C++ map values?

Since C++17 you can use range-based for loops together with structured bindings for iterating over your map. This improves readability, as you reduce the amount of needed first and second members in your code:

std::map<std::string, std::pair<std::string, std::string>> myMap;
myMap["x"] = { "a", "b" };
myMap["y"] = { "c", "d" };

for (const auto &[k, v] : myMap)
    std::cout << "m[" << k << "] = (" << v.first << ", " << v.second << ") " << std::endl;

Output:

m[x] = (a, b)
m[y] = (c, d)

Code on Coliru

SQL providerName in web.config

 WebConfigurationManager.ConnectionStrings["YourConnectionString"].ProviderName;