Programs & Examples On #Concrete inheritance

passing several arguments to FUN of lapply (and others *apply)

If you look up the help page, one of the arguments to lapply is the mysterious .... When we look at the Arguments section of the help page, we find the following line:

...: optional arguments to ‘FUN’.

So all you have to do is include your other argument in the lapply call as an argument, like so:

lapply(input, myfun, arg1=6)

and lapply, recognizing that arg1 is not an argument it knows what to do with, will automatically pass it on to myfun. All the other apply functions can do the same thing.

An addendum: You can use ... when you're writing your own functions, too. For example, say you write a function that calls plot at some point, and you want to be able to change the plot parameters from your function call. You could include each parameter as an argument in your function, but that's annoying. Instead you can use ... (as an argument to both your function and the call to plot within it), and have any argument that your function doesn't recognize be automatically passed on to plot.

Writing string to a file on a new line every time

If you use it extensively (a lot of written lines), you can subclass 'file':

class cfile(file):
    #subclass file to have a more convienient use of writeline
    def __init__(self, name, mode = 'r'):
        self = file.__init__(self, name, mode)

    def wl(self, string):
        self.writelines(string + '\n')

Now it offers an additional function wl that does what you want:

fid = cfile('filename.txt', 'w')
fid.wl('appends newline charachter')
fid.wl('is written on a new line')
fid.close()

Maybe I am missing something like different newline characters (\n, \r, ...) or that the last line is also terminated with a newline, but it works for me.

How to create a directory in Java?

After ~7 year, I will update it to better approach which is suggested by Bozho.

File theDir = new File("/path/directory");
if (!theDir.exists()){
    theDir.mkdirs();
}

Angular 4/5/6 Global Variables

I use environment for that. It works automatically and you don't have to create new injectable service and most usefull for me, don't need to import via constructor.

1) Create environment variable in your environment.ts

export const environment = {
    ...
    // runtime variables
    isContentLoading: false,
    isDeployNeeded: false
}

2) Import environment.ts in *.ts file and create public variable (i.e. "env") to be able to use in html template

import { environment } from 'environments/environment';

@Component(...)
export class TestComponent {
    ...
    env = environment;
}

3) Use it in template...

<app-spinner *ngIf='env.isContentLoading'></app-spinner>

in *.ts ...

env.isContentLoading = false 

(or just environment.isContentLoading in case you don't need it for template)


You can create your own set of globals within environment.ts like so:

export const globals = {
    isContentLoading: false,
    isDeployNeeded: false
}

and import directly these variables (y)

How to get terminal's Character Encoding

Check encoding and language:

$ echo $LC_CTYPE
ISO-8859-1
$ echo $LANG
pt_BR

Get all languages:

$ locale -a

Change to pt_PT.utf8:

$ export LC_ALL=pt_PT.utf8 
$ export LANG="$LC_ALL"

Use underscore inside Angular controllers

you can use this module -> https://github.com/jiahut/ng.lodash

this is for lodash so does underscore

Execution order of events when pressing PrimeFaces p:commandButton

I just love getting information like BalusC gives here - and he is kind enough to help SO many people with such GOOD information that I regard his words as gospel, but I was not able to use that order of events to solve this same kind of timing issue in my project. Since BalusC put a great general reference here that I even bookmarked, I thought I would donate my solution for some advanced timing issues in the same place since it does solve the original poster's timing issues as well. I hope this code helps someone:

        <p:pickList id="formPickList" 
                    value="#{mediaDetail.availableMedia}" 
                    converter="MediaPicklistConverter" 
                    widgetVar="formsPicklistWidget" 
                    var="mediaFiles" 
                    itemLabel="#{mediaFiles.mediaTitle}" 
                    itemValue="#{mediaFiles}" >
            <f:facet name="sourceCaption">Available Media</f:facet>
            <f:facet name="targetCaption">Chosen Media</f:facet>
        </p:pickList>

        <p:commandButton id="viewStream_btn" 
                         value="Stream chosen media" 
                         icon="fa fa-download"
                         ajax="true"
                         action="#{mediaDetail.prepareStreams}"                                              
                         update=":streamDialogPanel"
                         oncomplete="PF('streamingDialog').show()"
                         styleClass="ui-priority-primary"
                         style="margin-top:5px" >
            <p:ajax process="formPickList"  />
        </p:commandButton>

The dialog is at the top of the XHTML outside this form and it has a form of its own embedded in the dialog along with a datatable which holds additional commands for streaming the media that all needed to be primed and ready to go when the dialog is presented. You can use this same technique to do things like download customized documents that need to be prepared before they are streamed to the user's computer via fileDownload buttons in the dialog box as well.

As I said, this is a more complicated example, but it hits all the high points of your problem and mine. When the command button is clicked, the result is to first insure the backing bean is updated with the results of the pickList, then tell the backing bean to prepare streams for the user based on their selections in the pick list, then update the controls in the dynamic dialog with an update, then show the dialog box ready for the user to start streaming their content.

The trick to it was to use BalusC's order of events for the main commandButton and then to add the <p:ajax process="formPickList" /> bit to ensure it was executed first - because nothing happens correctly unless the pickList updated the backing bean first (something that was not happening for me before I added it). So, yea, that commandButton rocks because you can affect previous, pending and current components as well as the backing beans - but the timing to interrelate all of them is not easy to get a handle on sometimes.

Happy coding!

Swift 3: Display Image from URL

Use this extension and download image faster.

extension UIImageView {
    public func imageFromURL(urlString: String) {

        let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        activityIndicator.frame = CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
        activityIndicator.startAnimating()
        if self.image == nil{
            self.addSubview(activityIndicator)
        }

        URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in

            if error != nil {
                print(error ?? "No Error")
                return
            }
            DispatchQueue.main.async(execute: { () -> Void in
                let image = UIImage(data: data!)
                activityIndicator.removeFromSuperview()
                self.image = image
            })

        }).resume()
    }
}

How to add colored border on cardview?

Start From the material design update, it support app:strokeColor and also app:strokeWidth. see more

to use material design update. add following code to build.gradle(:app)

dependencies {
    // ...
    implementation 'com.google.android.material:material:1.0.0'
    // ...
  }

and Change CardView to MaterialCardView

Calling a phone number in swift

Swift 3.0 & iOS 10+

UIApplication.shared.openURL(url) was changed to UIApplication.shared.open(_ url: URL, options:[:], completionHandler completion: nil)

options and completion handler are optional, rendering:

UIApplication.shared.open(url)

https://developer.apple.com/reference/uikit/uiapplication/1648685-open

HTML Input Box - Disable

<input type="text" required="true" value="" readonly="true">

This will make a text box in readonly mode, might be helpful in generating passwords and datepickers.

for each loop in Objective-C for accessing NSMutable dictionary

If you need to mutate the dictionary while enumerating:

for (NSString* key in xyz.allKeys) {
    [xyz setValue:[NSNumber numberWithBool:YES] forKey:key];
}

Npm Error - No matching version found for

first, in C:\users\your PC write npm uninstall -g create-react-app then, create your project folder with npx create-react-app folder-name.

How do I pretty-print existing JSON data with Java?

Use gson. https://www.mkyong.com/java/how-to-enable-pretty-print-json-output-gson/

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(my_bean);

output

{
  "name": "mkyong",
  "age": 35,
  "position": "Founder",
  "salary": 10000,
  "skills": [
    "java",
    "python",
    "shell"
  ]
}

How do I pull files from remote without overwriting local files?

Well, yes, and no...

I understand that you want your local copies to "override" what's in the remote, but, oh, man, if someone has modified the files in the remote repo in some different way, and you just ignore their changes and try to "force" your own changes without even looking at possible conflicts, well, I weep for you (and your coworkers) ;-)

That said, though, it's really easy to do the "right thing..."

Step 1:

git stash

in your local repo. That will save away your local updates into the stash, then revert your modified files back to their pre-edit state.

Step 2:

git pull

to get any modified versions. Now, hopefully, that won't get any new versions of the files you're worried about. If it doesn't, then the next step will work smoothly. If it does, then you've got some work to do, and you'll be glad you did.

Step 3:

git stash pop

That will merge your modified versions that you stashed away in Step 1 with the versions you just pulled in Step 2. If everything goes smoothly, then you'll be all set!

If, on the other hand, there were real conflicts between what you pulled in Step 2 and your modifications (due to someone else editing in the interim), you'll find out and be told to resolve them. Do it.

Things will work out much better this way - it will probably keep your changes without any real work on your part, while alerting you to serious, serious issues.

Calendar Recurring/Repeating Events - Best Storage Method

Storing "Simple" Repeating Patterns

For my PHP/MySQL based calendar, I wanted to store repeating/recurring event information as efficiently as possibly. I didn't want to have a large number of rows, and I wanted to easily lookup all events that would take place on a specific date.

The method below is great at storing repeating information that occurs at regular intervals, such as every day, every n days, every week, every month every year, etc etc. This includes every Tuesday and Thursday type patterns as well, because they are stored separately as every week starting on a Tuesday and every week starting on a Thursday.

Assuming I have two tables, one called events like this:

ID    NAME
1     Sample Event
2     Another Event

And a table called events_meta like this:

ID    event_id      meta_key           meta_value
1     1             repeat_start       1299132000
2     1             repeat_interval_1  432000

With repeat_start being a date with no time as a unix timestamp, and repeat_interval an amount in seconds between intervals (432000 is 5 days).

repeat_interval_1 goes with repeat_start of the ID 1. So if I have an event that repeats every Tuesday and every Thursday, the repeat_interval would be 604800 (7 days), and there would be 2 repeat_starts and 2 repeat_intervals. The table would look like this:

ID    event_id      meta_key           meta_value
1     1             repeat_start       1298959200 -- This is for the Tuesday repeat
2     1             repeat_interval_1  604800
3     1             repeat_start       1299132000 -- This is for the Thursday repeat
4     1             repeat_interval_3  604800
5     2             repeat_start       1299132000
6     2             repeat_interval_5  1          -- Using 1 as a value gives us an event that only happens once

Then, if you have a calendar that loops through every day, grabbing the events for the day it's at, the query would look like this:

SELECT EV.*
FROM `events` EV
RIGHT JOIN `events_meta` EM1 ON EM1.`event_id` = EV.`id`
RIGHT JOIN `events_meta` EM2 ON EM2.`meta_key` = CONCAT( 'repeat_interval_', EM1.`id` )
WHERE EM1.meta_key = 'repeat_start'
    AND (
        ( CASE ( 1299132000 - EM1.`meta_value` )
            WHEN 0
              THEN 1
            ELSE ( 1299132000 - EM1.`meta_value` )
          END
        ) / EM2.`meta_value`
    ) = 1
LIMIT 0 , 30

Replacing {current_timestamp} with the unix timestamp for the current date (Minus the time, so the hour, minute and second values would be set to 0).

Hopefully this will help somebody else too!


Storing "Complex" Repeating Patterns

This method is better suited for storing complex patterns such as

Event A repeats every month on the 3rd of the month starting on March 3, 2011

or

Event A repeats Friday of the 2nd week of the month starting on March 11, 2011

I'd recommend combining this with the above system for the most flexibility. The tables for this should like like:

ID    NAME
1     Sample Event
2     Another Event

And a table called events_meta like this:

ID    event_id      meta_key           meta_value
1     1             repeat_start       1299132000 -- March 3rd, 2011
2     1             repeat_year_1      *
3     1             repeat_month_1     *
4     1             repeat_week_im_1   2
5     1             repeat_weekday_1   6

repeat_week_im represents the week of the current month, which could be between 1 and 5 potentially. repeat_weekday in the day of the week, 1-7.

Now assuming you are looping through the days/weeks to create a month view in your calendar, you could compose a query like this:

SELECT EV . *
FROM `events` AS EV
JOIN `events_meta` EM1 ON EM1.event_id = EV.id
AND EM1.meta_key = 'repeat_start'
LEFT JOIN `events_meta` EM2 ON EM2.meta_key = CONCAT( 'repeat_year_', EM1.id )
LEFT JOIN `events_meta` EM3 ON EM3.meta_key = CONCAT( 'repeat_month_', EM1.id )
LEFT JOIN `events_meta` EM4 ON EM4.meta_key = CONCAT( 'repeat_week_im_', EM1.id )
LEFT JOIN `events_meta` EM5 ON EM5.meta_key = CONCAT( 'repeat_weekday_', EM1.id )
WHERE (
  EM2.meta_value =2011
  OR EM2.meta_value = '*'
)
AND (
  EM3.meta_value =4
  OR EM3.meta_value = '*'
)
AND (
  EM4.meta_value =2
  OR EM4.meta_value = '*'
)
AND (
  EM5.meta_value =6
  OR EM5.meta_value = '*'
)
AND EM1.meta_value >= {current_timestamp}
LIMIT 0 , 30

This combined with the above method could be combined to cover most repeating/recurring event patterns. If I've missed anything please leave a comment.

Add marker to Google Map on Click

In 2017, the solution is:

map.addListener('click', function(e) {
    placeMarker(e.latLng, map);
});

function placeMarker(position, map) {
    var marker = new google.maps.Marker({
        position: position,
        map: map
    });
    map.panTo(position);
}

How to modify WooCommerce cart, checkout pages (main theme portion)

Another way to totally override the cart.php is to copy:

woocommerce/templates/cart/cart.php to   
yourtheme/woocommerce/cart/cart.php

Then do whatever you need at the yourtheme/woocommerce/cart/cart.php

Control flow in T-SQL SP using IF..ELSE IF - are there other ways?

Also you can try to formulate your answer in the form of a SELECT CASE Statement. You can then later create simple if then's that use your results if needed as you have narrowed down the possibilities.

SELECT @Result =   
CASE @inputParam   
WHEN 1 THEN 1   
WHEN 2 THEN 2   
WHEN 3 THEN 1   
ELSE 4   
END  

IF @Result = 1   
BEGIN  
...  
END  

IF @Result = 2   
BEGIN   
....  
END  

IF @Result = 4   
BEGIN   
//Error handling code   
END   

Create patch or diff file from git repository and apply it to another different git repository

As a complementary, to produce patch for only one specific commit, use:

git format-patch -1 <sha>

When the patch file is generated, make sure your other repo knows where it is when you use git am ${patch-name}

Before adding the patch, use git apply --check ${patch-name} to make sure that there is no confict.

Get table names using SELECT statement in MySQL

Besides using the INFORMATION_SCHEMA table, to use SHOW TABLES to insert into a table you would use the following

<?php
 $sql = "SHOW TABLES FROM $dbname";
 $result = mysql_query($sql);
 $arrayCount = 0
 while ($row = mysql_fetch_row($result)) {
  $tableNames[$arrayCount] = $row[0];
  $arrayCount++; //only do this to make sure it starts at index 0
 }
 foreach ($tableNames as &$name {
  $query = "INSERT INTO metadata (table_name) VALUES ('".$name."')";
  mysql_query($query);
 }
?>

How to get selected path and name of the file opened with file dialog?

I think you want this:

Dim filename As String
filename = Application.GetOpenFilename

Dim cell As Range
cell = Application.Range("A1")
cell.Value = filename

How do I get cURL to not show the progress bar?

Not sure why it's doing that. Try -s with the -o option to set the output file instead of >.

An attempt was made to access a socket in a way forbidden by its access permissions

Just Restart-Service hns can change the port occupier by Hyper-V. It might release the port you need.

How to test code dependent on environment variables using JUnit?

If you want to retrieve informations about the environment variable in Java, you can call the method : System.getenv();. As the properties, this method returns a Map containing the variable names as keys and the variable values as the map values. Here is an example :

    import java.util.Map;

public class EnvMap {
    public static void main (String[] args) {
        Map<String, String> env = System.getenv();
        for (String envName : env.keySet()) {
            System.out.format("%s=%s%n", envName, env.get(envName));
        }
    }
}

The method getEnv() can also takes an argument. For instance :

String myvalue = System.getEnv("MY_VARIABLE");

For testing, I would do something like this :

public class Environment {
    public static String getVariable(String variable) {
       return  System.getenv(variable);
}

@Test
 public class EnvVariableTest {

     @Test testVariable1(){
         String value = Environment.getVariable("MY_VARIABLE1");
         doSometest(value); 
     }

    @Test testVariable2(){
       String value2 = Environment.getVariable("MY_VARIABLE2");
       doSometest(value); 
     }   
 }

When do you use POST and when do you use GET?

As answered by others, there's a limit on url size with get, and files can be submitted with post only.

I'd like to add that one can add things to a database with a get and perform actions with a post. When a script receives a post or a get, it can do whatever the author wants it to do. I believe the lack of understanding comes from the wording the book chose or how you read it.

A script author should use posts to change the database and use get only for retrieval of information.

Scripting languages provided many means with which to access the request. For example, PHP allows the use of $_REQUEST to retrieve either a post or a get. One should avoid this in favor of the more specific $_GET or $_POST.

In web programming, there's a lot more room for interpretation. There's what one should and what one can do, but which one is better is often up for debate. Luckily, in this case, there is no ambiguity. You should use posts to change data, and you should use get to retrieve information.

How do I get a range's address including the worksheet name, but not the workbook name, in Excel VBA?

Dim rg As Range
Set rg = Range("A1:E10")
Dim i As Integer
For i = 1 To rg.Rows.Count

    For j = 1 To rg.Columns.Count
    rg.Cells(i, j).Value = rg.Cells(i, j).Address(False, False)

    Next
Next

Starting a shell in the Docker Alpine container

ole@T:~$ docker run -it --rm alpine /bin/ash
(inside container) / # 

Options used above:

  • /bin/ash is Ash (Almquist Shell) provided by BusyBox
  • --rm Automatically remove the container when it exits (docker run --help)
  • -i Interactive mode (Keep STDIN open even if not attached)
  • -t Allocate a pseudo-TTY

How to randomly select rows in SQL?

In order to shuffle the SQL result set, you need to use a database-specific function call.

Note that sorting a large result set using a RANDOM function might turn out to be very slow, so make sure you do that on small result sets.

If you have to shuffle a large result set and limit it afterward, then it's better to use something like the Oracle SAMPLE(N) or the TABLESAMPLE in SQL Server or PostgreSQL instead of a random function in the ORDER BY clause.

So, assuming we have the following database table:

Song database table

And the following rows in the song table:

| id | artist                          | title                              |
|----|---------------------------------|------------------------------------|
| 1  | Miyagi & ???????? ft. ??? ????? | I Got Love                         |
| 2  | HAIM                            | Don't Save Me (Cyril Hahn Remix)   |
| 3  | 2Pac ft. DMX                    | Rise Of A Champion (GalilHD Remix) |
| 4  | Ed Sheeran & Passenger          | No Diggity (Kygo Remix)            |
| 5  | JP Cooper ft. Mali-Koa          | All This Love                      |

Oracle

On Oracle, you need to use the DBMS_RANDOM.VALUE function, as illustrated by the following example:

SELECT
    artist||' - '||title AS song
FROM song
ORDER BY DBMS_RANDOM.VALUE

When running the aforementioned SQL query on Oracle, we are going to get the following result set:

| song                                              |
|---------------------------------------------------|
| JP Cooper ft. Mali-Koa - All This Love            |
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |
| HAIM - Don't Save Me (Cyril Hahn Remix)           |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix)  |
| Miyagi & ???????? ft. ??? ????? - I Got Love      |

Notice that the songs are being listed in random order, thanks to the DBMS_RANDOM.VALUE function call used by the ORDER BY clause.

SQL Server

On SQL Server, you need to use the NEWID function, as illustrated by the following example:

SELECT
    CONCAT(CONCAT(artist, ' - '), title) AS song
FROM song
ORDER BY NEWID()

When running the aforementioned SQL query on SQL Server, we are going to get the following result set:

| song                                              |
|---------------------------------------------------|
| Miyagi & ???????? ft. ??? ????? - I Got Love      |
| JP Cooper ft. Mali-Koa - All This Love            |
| HAIM - Don't Save Me (Cyril Hahn Remix)           |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix)  |
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |

Notice that the songs are being listed in random order, thanks to the NEWID function call used by the ORDER BY clause.

PostgreSQL

On PostgreSQL, you need to use the random function, as illustrated by the following example:

SELECT
    artist||' - '||title AS song
FROM song
ORDER BY random()

When running the aforementioned SQL query on PostgreSQL, we are going to get the following result set:

| song                                              |
|---------------------------------------------------|
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |
| JP Cooper ft. Mali-Koa - All This Love            |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix)  |
| HAIM - Don't Save Me (Cyril Hahn Remix)           |
| Miyagi & ???????? ft. ??? ????? - I Got Love      |

Notice that the songs are being listed in random order, thanks to the random function call used by the ORDER BY clause.

MySQL

On MySQL, you need to use the RAND function, as illustrated by the following example:

SELECT
  CONCAT(CONCAT(artist, ' - '), title) AS song
FROM song
ORDER BY RAND()

When running the aforementioned SQL query on MySQL, we are going to get the following result set:

| song                                              |
|---------------------------------------------------|
| HAIM - Don't Save Me (Cyril Hahn Remix)           |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix)  |
| Miyagi & ???????? ft. ??? ????? - I Got Love      |
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |
| JP Cooper ft. Mali-Koa - All This Love            |

Notice that the songs are being listed in random order, thanks to the RAND function call used by the ORDER BY clause.

Remove a file from a Git repository without deleting it from the local filesystem

To remove an entire folder from the repo (like Resharper files), do this:

git rm -r --cached folderName

I had committed some resharper files, and did not want those to persist for other project users.

How can I hide/show a div when a button is clicked?

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Show and hide div with JavaScript</title>
<script>

    var button_beg = '<button id="button" onclick="showhide()">', button_end = '</button>';
    var show_button = 'Show', hide_button = 'Hide';
    function showhide() {
        var div = document.getElementById( "hide_show" );
        var showhide = document.getElementById( "showhide" );
        if ( div.style.display !== "none" ) {
            div.style.display = "none";
            button = show_button;
            showhide.innerHTML = button_beg + button + button_end;
        } else {
            div.style.display = "block";
            button = hide_button;
            showhide.innerHTML = button_beg + button + button_end;
        }
    }
    function setup_button( status ) {
        if ( status == 'show' ) {
            button = hide_button;
        } else {
            button = show_button;
        }
        var showhide = document.getElementById( "showhide" );
        showhide.innerHTML = button_beg + button + button_end;
    }
    window.onload = function () {
        setup_button( 'hide' );
        showhide(); // if setup_button is set to 'show' comment this line
    }
</script>
</head>
<body>
    <div id="showhide"></div>
    <div id="hide_show">
        <p>This div will be show and hide on button click</p>
    </div>
</body>
</html>

AVD Manager - No system image installed for this target

you should android sdk manager install 4.2 api 17 -> ARM EABI v7a System Image

if not installed ARM EABI v7a System Image, you should install all.

Using PHP Replace SPACES in URLS with %20

You've got several options how to do this, either:

strtr()

Assuming that you want to replace "\t" and " " with "%20":

$replace_pairs = array(
  "\t" => '%20',
  " " => '%20',
);
return strtr( $text, $replace_pairs)

preg_replace()

You've got few options here, either replacing just space ~ ~, again replacing space and tab ~[ \t]~ or all kinds of spaces ~\s~:

return preg_replace( '~\s~', '%20', $text);

Or when you need to replace string like this "\t \t \t \t" with just one %20:

return preg_replace( '~\s+~', '%20', $text);

I assumed that you really want to use manual string replacement and handle more types of whitespaces such as non breakable space (&nbsp;)

What is the purpose of nameof?

As others have already pointed out, the nameof operator does insert the name that the element was given in the sourcecode.

I would like to add that this is a really good idea in terms of refactoring since it makes this string refactoring safe. Previously, I used a static method which utilized reflection for the same purpose, but that has a runtime performance impact. The nameof operator has no runtime performance impact; it does its work at compile time. If you take a look at the MSIL code you will find the string embedded. See the following method and its disassembled code.

static void Main(string[] args)
{
    Console.WriteLine(nameof(args));
    Console.WriteLine("regular text");
}

// striped nops from the listing
IL_0001 ldstr args
IL_0006 call System.Void System.Console::WriteLine(System.String)
IL_000C ldstr regular text
IL_0011 call System.Void System.Console::WriteLine(System.String)
IL_0017 ret

However, that can be a drawback if you plan to obfuscate your software. After obfuscation the embedded string may no longer match the name of the element. Mechanisms that rely on this text will break. Examples for that, including but not limited to are: Reflection, NotifyPropertyChanged ...

Determining the name during runtime costs some performance, but is safe for obfuscation. If obfuscation is neither required nor planned, I would recommend using the nameof operator.

How do I check in JavaScript if a value exists at a certain array index?

Can't we just do this:

if(arrayName.length > 0){   
    //or **if(arrayName.length)**
    //this array is not empty 
}else{
   //this array is empty
}

Checking if an object is a given type in Swift

If you want to check against a specific type you can do the following:

if let stringArray = obj as? [String] {
    // obj is a string array. Do something with stringArray
}
else {
    // obj is not a string array
}

You can use "as!" and that will throw a runtime error if obj is not of type [String]

let stringArray = obj as! [String]

You can also check one element at a time:

let items : [Any] = ["Hello", "World"]
for obj in items {
   if let str = obj as? String {
      // obj is a String. Do something with str
   }
   else {
      // obj is not a String
   }
}

Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?

I know this question was asked a very long time ago, but I figured I'd offer a more recent answer.

DNS over HTTPS (DoH)

You can send DNS queries over HTTPS to DNS resolvers that support it. The standard for DOH is described in RFC 8484.

This is a similar thing to what all the other answers suggest, only that DoH is actually the DNS protocol over HTTPS. It's also a "proposed" Internet standard and it's becoming quite popular. For example, some major browsers either support it or have plans to support it (Chrome, Edge, Firefox), and Microsoft is in the process of building it into their operating system.

One of the purposes of DoH is:

allowing web applications to access DNS information via existing browser APIs in a safe way consistent with Cross Origin Resource Sharing (CORS)

There's an open source tool made especially for doing DNS lookups from web applications called dohjs. It does DNS over HTTPS (DoH) wireformat queries as described in RFC 8484. It supports both GET and POST methods.

Full disclosure: I am a contributor to dohjs.

Another JavaScript library with similar features is found here - https://github.com/sc0Vu/doh-js-client. I haven't used this one personally, but I think it would work client side as well.

DNS over HTTPS JSON APIs

If you don't want to bother with DNS wireformat, both Google and Cloudflare offer JSON APIs for DNS over HTTPS.

Example Javascript code to lookup example.com with Google's JSON DOH API:

var response = await fetch('https://dns.google/resolve?name=example.com');
var json = await response.json();
console.log(json);

Examples from the RFC for DOH GET and POST with wireformat

Here are the examples the RFC gives for both GET and POST (see https://tools.ietf.org/html/rfc8484#section-4.1.1):

GET example:

The first example request uses GET to request "www.example.com".

:method = GET
:scheme = https
:authority = dnsserver.example.net
:path = /dns-query?dns=AAABAAABAAAAAAAAA3d3dwdleGFtcGxlA2NvbQAAAQAB
accept = application/dns-message

POST example:

The same DNS query for "www.example.com", using the POST method would be:

:method = POST
:scheme = https
:authority = dnsserver.example.net
:path = /dns-query
accept = application/dns-message
content-type = application/dns-message
content-length = 33

<33 bytes represented by the following hex encoding> 00 00 01 00 00 01 00 00 00 00 00 00 03 77 77 77 07 65 78 61 6d 70 6c 65 03 63 6f 6d 00 00 01 00 01

Other places to send DOH queries

You can find a list of some public DNS resolvers that support DNS over HTTPS in a couple places:

Of the above resources, I'd say that the list on Curl's wiki and the DNSCrypt list are are probably the most complete and the most frequently updated. Curl's page also includes a list of open source tools for DoH (servers, proxies, client libs, etc).

Detect if a browser in a mobile device (iOS/Android phone/tablet) is used

Detecting mobile devices

Related answer: https://stackoverflow.com/a/13805337/1306809

There's no single approach that's truly foolproof. The best bet is to mix and match a variety of tricks as needed, to increase the chances of successfully detecting a wider range of handheld devices. See the link above for a few different options.

How to make Bootstrap 4 cards the same height in card-columns?

UPDATE: In Bootstrap 4, flexbox is now default, and each card-deck row will contain 3 cards. The cards will fill to full height.

http://www.codeply.com/go/x91w5Cl6ip

The Bootstrap 4 alpha card-columns uses CSS3 columns which don't really support equal heights (except column-fill which is only suppored in Firefox).

If you instead enable Bootstrap 4 flexbox mode, you could instead use the card-deck and a little CSS to equalize the height and wrap every 3 columns.

@media (min-width:34em) {
    .card-deck > .card
    {
        width: 29%;
        flex-wrap: wrap;
        flex: initial; 
    }
}

http://codeply.com/go/YFFFWHVoRB

Related
Bootstrap Card of same Height in Col

CSS Background Opacity

.transbg{/* Fallback for web browsers that don't support RGBa */
background-color: rgb(0, 0, 0);
/* RGBa with 0.6 opacity */
background-color: rgba(0, 0, 0, 0.6);
/* For IE 5.5 - 7*/
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);
/* For IE 8*/
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";}

How do I create a chart with multiple series using different X values for each series?

You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.

How to use boolean datatype in C?

C99 has a bool type. To use it,

#include <stdbool.h>

How do I add my new User Control to the Toolbox or a new Winform?

I found that user controls can exist in the same project.
As others have mentioned, AutoToolboxPopulate must be set to True.
Create the desired user control.
Select Build Solution.
If the new user control doesn't show up in the toolbox, close/open Visual Studio.
If the user controls still aren't showing up in the toolbox, right click on the toolbox and select Reset Toolbox. Then select Build Solution. If they still aren't there, restart Visual Studio.
There must not be any build errors when the solution is built, otherwise new toolbox items will not be added to the toolbox.

how to read xml file from url using php

$url = 'http://www.example.com'; $xml = simpleXML_load_file($url,"SimpleXMLElement",LIBXML_NOCDATA);

$url can be php file, as long as the file generate xml format data as output.

Get values from other sheet using VBA

Try the worksheet activate command before you need data from the sheet:

objWorkbook.WorkSheets(1).Activate
objWorkbook.WorkSheets(2).Activate

PostgreSQL create table if not exists

This feature has been implemented in Postgres 9.1:

CREATE TABLE IF NOT EXISTS myschema.mytable (i integer);


For older versions, here is a function to work around it:

CREATE OR REPLACE FUNCTION create_mytable()
  RETURNS void
  LANGUAGE plpgsql AS
$func$
BEGIN
   IF EXISTS (SELECT FROM pg_catalog.pg_tables 
              WHERE  schemaname = 'myschema'
              AND    tablename  = 'mytable') THEN
      RAISE NOTICE 'Table myschema.mytable already exists.';
   ELSE
      CREATE TABLE myschema.mytable (i integer);
   END IF;
END
$func$;

Call:

SELECT create_mytable();        -- call as many times as you want. 

Notes:

  • The columns schemaname and tablename in pg_tables are case-sensitive. If you double-quote identifiers in the CREATE TABLE statement, you need to use the exact same spelling. If you don't, you need to use lower-case strings. See:

  • Are PostgreSQL column names case-sensitive?

  • pg_tables only contains actual tables. The identifier may still be occupied by related objects. See:

  • How to check if a table exists in a given schema

  • If the role executing this function does not have the necessary privileges to create the table you might want to use SECURITY DEFINER for the function and make it owned by another role with the necessary privileges. This version is safe enough.

How to install PHP intl extension in Ubuntu 14.04

In Ubuntu 20.04, PHP 7.4 use the following command:

sudo apt-get install php7.4-intl

replace 7.4 with your PHP version

Change Placeholder Text using jQuery

You can use following code to update a placeholder by id:

$("#serMemtb").attr("placeholder", "Type a Location").val("").focus().blur();

Check if array is empty or null

As long as your selector is actually working, I see nothing wrong with your code that checks the length of the array. That should do what you want. There are a lot of ways to clean up your code to be simpler and more readable. Here's a cleaned up version with notes about what I cleaned up.

var album_text = [];

$("input[name='album_text[]']").each(function() {
    var value = $(this).val();
    if (value) {
        album_text.push(value);
    }
});
if (album_text.length === 0) {
    $('#error_message').html("Error");
}

else {
  //send data
}

Some notes on what you were doing and what I changed.

  1. $(this) is always a valid jQuery object so there's no reason to ever check if ($(this)). It may not have any DOM objects inside it, but you can check that with $(this).length if you need to, but that is not necessary here because the .each() loop wouldn't run if there were no items so $(this) inside your .each() loop will always be something.
  2. It's inefficient to use $(this) multiple times in the same function. Much better to get it once into a local variable and then use it from that local variable.
  3. It's recommended to initialize arrays with [] rather than new Array().
  4. if (value) when value is expected to be a string will both protect from value == null, value == undefined and value == "" so you don't have to do if (value && (value != "")). You can just do: if (value) to check for all three empty conditions.
  5. if (album_text.length === 0) will tell you if the array is empty as long as it is a valid, initialized array (which it is here).

What are you trying to do with this selector $("input[name='album_text[]']")?

Fixed page header overlaps in-page anchors

The top answer here created a 60px-high tag that was masking other links that stopped working as a result. I found this solution working without side-effects.

<a class="anchor" id="top"></a>

a.anchor {
    display: block;
    position: relative;
    top: -60px;
    visibility: hidden;
}

Python import csv to list

Pandas is pretty good at dealing with data. Here is one example how to use it:

import pandas as pd

# Read the CSV into a pandas data frame (df)
#   With a df you can do many things
#   most important: visualize data with Seaborn
df = pd.read_csv('filename.csv', delimiter=',')

# Or export it in many ways, e.g. a list of tuples
tuples = [tuple(x) for x in df.values]

# or export it as a list of dicts
dicts = df.to_dict().values()

One big advantage is that pandas deals automatically with header rows.

If you haven't heard of Seaborn, I recommend having a look at it.

See also: How do I read and write CSV files with Python?

Pandas #2

import pandas as pd

# Get data - reading the CSV file
import mpu.pd
df = mpu.pd.example_df()

# Convert
dicts = df.to_dict('records')

The content of df is:

     country   population population_time    EUR
0    Germany   82521653.0      2016-12-01   True
1     France   66991000.0      2017-01-01   True
2  Indonesia  255461700.0      2017-01-01  False
3    Ireland    4761865.0             NaT   True
4      Spain   46549045.0      2017-06-01   True
5    Vatican          NaN             NaT   True

The content of dicts is

[{'country': 'Germany', 'population': 82521653.0, 'population_time': Timestamp('2016-12-01 00:00:00'), 'EUR': True},
 {'country': 'France', 'population': 66991000.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': True},
 {'country': 'Indonesia', 'population': 255461700.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': False},
 {'country': 'Ireland', 'population': 4761865.0, 'population_time': NaT, 'EUR': True},
 {'country': 'Spain', 'population': 46549045.0, 'population_time': Timestamp('2017-06-01 00:00:00'), 'EUR': True},
 {'country': 'Vatican', 'population': nan, 'population_time': NaT, 'EUR': True}]

Pandas #3

import pandas as pd

# Get data - reading the CSV file
import mpu.pd
df = mpu.pd.example_df()

# Convert
lists = [[row[col] for col in df.columns] for row in df.to_dict('records')]

The content of lists is:

[['Germany', 82521653.0, Timestamp('2016-12-01 00:00:00'), True],
 ['France', 66991000.0, Timestamp('2017-01-01 00:00:00'), True],
 ['Indonesia', 255461700.0, Timestamp('2017-01-01 00:00:00'), False],
 ['Ireland', 4761865.0, NaT, True],
 ['Spain', 46549045.0, Timestamp('2017-06-01 00:00:00'), True],
 ['Vatican', nan, NaT, True]]

Using git commit -a with vim

See this thread for an explanation: VIM for Windows - What do I type to save and exit from a file?

As I wrote there: to learn Vimming, you could use one of the quick reference cards:

Also note How can I set up an editor to work with Git on Windows? if you're not comfortable in using Vim but want to use another editor for your commit messages.

If your commit message is not too long, you could also type

git commit -a -m "your message here"

How to convert byte array to string

Assuming that you are using UTF-8 encoding:

string convert = "This is the string to be converted";

// From string to byte array
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(convert);

// From byte array to string
string s = System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length);

css3 text-shadow in IE9

Try CSS Generator.

You can choose values and see the results online. Then you get the code in the clipboard.
This is one example of generated code:

text-shadow: 1px 1px 2px #a8aaad;
filter: dropshadow(color=#a8aaad, offx=1, offy=1);

How can I beautify JSON programmatically?

Here's something that might be interesting for developers hacking (minified or obfuscated) JavaScript more frequently.

You can build your own CLI JavaScript beautifier in under 5 mins and have it handy on the command-line. You'll need Mozilla Rhino, JavaScript file of some of the JS beautifiers available online, small hack and a script file to wrap it all up.

I wrote an article explaining the procedure: Command-line JavaScript beautifier implemented in JavaScript.

How to check if a Unix .tar.gz file is a valid file without uncompressing?

> use the -O option. [...] If the tar file is corrupt, the process will abort with an error.

Sometimes yes, but sometimes not. Let's see an example of a corrupted file:

echo Pete > my_name
tar -cf my_data.tar my_name 

# // Simulate a corruption
sed < my_data.tar 's/Pete/Fool/' > my_data_now.tar
# // "my_data_now.tar" is the corrupted file

tar -xvf my_data_now.tar -O

It shows:

my_name
Fool  

Even if you execute

echo $?

tar said that there was no error:

0

but the file was corrupted, it has now "Fool" instead of "Pete".

Uncaught ReferenceError: <function> is not defined at HTMLButtonElement.onclick

Place your script inside the body tag

<body>
  // Rest of html
  <script>
  function hideButton() {
    $(".loading").hide();
  }
function showButton() {
  $(".loading").show();
}
</script> 
< /body>

If you check this JSFIDDLE and click on javascript, you will see the load Type body is selected

Bootstrap 3 Navbar with Logo

Failing to make any of the other answers work in my case (I probably didn't pass the intelligence test) and after some experimentation, this is what I am using (which I believe is very close to the Bootstrap default):

   <div class="navbar navbar-default navbar-fixed-top" role="navigation">
      <div class="navbar-header">
         <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
         </button>
         <div class="navbar-logo">
            <a class="navbar-brand" rel="home" href="@Url.Action("Index", "Home")" title="Home">
               <img src="~/Images/logo.png" class="img-responsive">
            </a>
         </div>
         <div class="collapse navbar-collapse" id="navbar-collapse">
            <ul class="nav navbar-nav">
               <li>@Html.ActionLink("Home", "Index", "Home")</li>
               <li>@Html.ActionLink("Coaching", "Coaching", "Home")</li>
               <li>@Html.ActionLink("Resources", "Resources", "Home")</li>
               <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
               <li>@Html.ActionLink("Blog", "Blog", "Home")</li>
               <li>@Html.ActionLink("About", "About", "Home")</li>
            </ul>
         </div>
      </div>
   </div>

And in the CSS file I have added the following:

.navbar-brand {
   padding-top: 5px;
}

.navbar-collapse {
   float: left;
}

.navbar-logo {
   float: left;
}

Note that @Html.ActionLink() is Razor syntax for an <a> tag. Where it says @Html.ActionLink(...) just replace it with an appropriate <a> tag. Equally where it says @Url.Action(...) replace it with an appropriate URL (no <a> tag in that case).

Check if object is a jQuery object

Check out the instanceof operator.

var isJqueryObject = obj instanceof jQuery

How to fix Python indentation

If you're lazy (like me), you can also download a trial version of Wingware Python IDE, which has an auto-fix tool for messed up indentation. It works pretty well. http://www.wingware.com/

What is the difference between a symbolic link and a hard link?

Symbolic links give another name to a file, in a way similar to hard links. But a file can be deleted even if there are remaining symbolic links.

Html.DropDownList - Disabled/Readonly

I had to disable the dropdownlist and hide the primary ID

<div class="form-group">
        @Html.LabelFor(model => model.OBJ_ID, "Objs", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("OBJ_ID", null, htmlAttributes: new { @class = "form-control", @disabled = "disabled"})
            @Html.HiddenFor(m => m.OBJ_ID)
            @Html.ValidationMessageFor(model => model.OBJ_ID, "", new { @class = "text-danger" })
        </div>
    </div>

Detecting arrow key presses in JavaScript

Here's an example implementation:

var targetElement = $0 || document.body;

function getArrowKeyDirection (keyCode) {
  return {
    37: 'left',
    39: 'right',
    38: 'up',
    40: 'down'
  }[keyCode];
}

function isArrowKey (keyCode) {
  return !!getArrowKeyDirection(keyCode);
}

targetElement.addEventListener('keydown', function (event) {
  var direction,
      keyCode = event.keyCode;

  if (isArrowKey(keyCode)) {
    direction = getArrowKeyDirection(keyCode);

    console.log(direction);
  }
});

Read and Write CSV files including unicode with Python 2.7

I couldn't respond to Mark above, but I just made one modification which fixed the error which was caused if data in the cells was not unicode, i.e. float or int data. I replaced this line into the UnicodeWriter function: "self.writer.writerow([s.encode("utf-8") if type(s)==types.UnicodeType else s for s in row])" so that it became:

class UnicodeWriter:
    def __init__(self, f, dialect=csv.excel, encoding="utf-8-sig", **kwds):
       self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()
    def writerow(self, row):
        '''writerow(unicode) -> None
        This function takes a Unicode string and encodes it to the output.
        '''
        self.writer.writerow([s.encode("utf-8") if type(s)==types.UnicodeType else s for s in row])
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        data = self.encoder.encode(data)
        self.stream.write(data)
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)

You will also need to "import types".

How to emulate GPS location in the Android Emulator?

If you're using Android Studio (1.3):

  • Click on Menu "Tools"
  • "Android"
  • "Android device monitor"
  • click on your current Emulator
  • Tab "Emulator Control"
  • go to "Location Controls" and enter Lat and Lon

Getting the ID of the element that fired an event

You can use (this) to reference the object that fired the function.

'this' is a DOM element when you are inside of a callback function (in the context of jQuery), for example, being called by the click, each, bind, etc. methods.

Here is where you can learn more: http://remysharp.com/2007/04/12/jquerys-this-demystified/

Sorting using Comparator- Descending order (User defined classes)

I would create a comparator for the person class that can be parametrized with a certain sorting behaviour. Here I can set the sorting order but it can be modified to allow sorting for other person attributes as well.

public class PersonComparator implements Comparator<Person> {

  public enum SortOrder {ASCENDING, DESCENDING}

  private SortOrder sortOrder;

  public PersonComparator(SortOrder sortOrder) {
    this.sortOrder = sortOrder;
  }

  @Override
  public int compare(Person person1, Person person2) {
    Integer age1 = person1.getAge();
    Integer age2 = person2.getAge();
    int compare = Math.signum(age1.compareTo(age2));

    if (sortOrder == ASCENDING) {
      return compare;
    } else {
      return compare * (-1);
    }
  }
}

(hope it compiles now, I have no IDE or JDK at hand, coded 'blind')

Edit

Thanks to Thomas, edited the code. I wouldn't say that the usage of Math.signum is good, performant, effective, but I'd like to keep it as a reminder, that the compareTo method can return any integer and multiplying by (-1) will fail if the implementation returns Integer.MIN_INTEGER... And I removed the setter because it's cheap enough to construct a new PersonComparator just when it's needed.

But I keep the boxing because it shows that I rely on an existing Comparable implementation. Could have done something like Comparable<Integer> age1 = new Integer(person1.getAge()); but that looked too ugly. The idea was to show a pattern which could easily be adapted to other Person attributes, like name, birthday as Date and so on.

Swing vs JavaFx for desktop applications

On older notebooks with integrated video Swing app starts and works much faster than JavaFX app. As for development, I'd recommend switch to Scala - comparable Scala Swing app contains 2..3 times less code than Java. As for Swing vs SWT: Netbeans GUI considerably faster than Eclipse...

What is the fastest way to compare two sets in Java?

You have the following solution from https://www.mkyong.com/java/java-how-to-compare-two-sets/

public static boolean equals(Set<?> set1, Set<?> set2){

    if(set1 == null || set2 ==null){
        return false;
    }

    if(set1.size() != set2.size()){
        return false;
    }

    return set1.containsAll(set2);
}

Or if you prefer to use a single return statement:

public static boolean equals(Set<?> set1, Set<?> set2){

  return set1 != null 
    && set2 != null 
    && set1.size() == set2.size() 
    && set1.containsAll(set2);
}

How to do a redirect to another route with react-router?

How to do a redirect to another route with react-router?

For example, when a user clicks a link <Link to="/" />Click to route</Link> react-router will look for / and you can use Redirect to and send the user somewhere else like the login route.

From the docs for ReactRouterTraining:

Rendering a <Redirect> will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects (HTTP 3xx) do.

import { Route, Redirect } from 'react-router'

<Route exact path="/" render={() => (
  loggedIn ? (
    <Redirect to="/dashboard"/>
  ) : (
    <PublicHomePage/>
  )
)}/>

to: string, The URL to redirect to.

<Redirect to="/somewhere/else"/>

to: object, A location to redirect to.

<Redirect to={{
  pathname: '/login',
  search: '?utm=your+face',
  state: { referrer: currentLocation }
}}/>

How can I get a specific field of a csv file?

import csv

def read_cell(x, y):
    with open('file.csv', 'r') as f:
        reader = csv.reader(f)
        y_count = 0
        for n in reader:
            if y_count == y:
                cell = n[x]
                return cell
            y_count += 1

print (read_cell(4, 8)) 

This example prints cell 4, 8 in Python 3.

How do I increment a DOS variable in a FOR /F loop?

set TEXT_T="myfile.txt"
set /a c=1

FOR /F "tokens=1 usebackq" %%i in (%TEXT_T%) do (
    set /a c+=1
    set OUTPUT_FILE_NAME=output_%c%.txt
    echo Output file is %OUTPUT_FILE_NAME%
    echo %%i, %c%
)

How to Rotate a UIImage 90 degrees?

There is a extremely efficient UIImage category named NYXImagesKit. It uses vDSP, CoreImage and vImage to be as fast as possible. It has a UIImage+Rotating category that saved my day :)

https://github.com/Nyx0uf/NYXImagesKit

Capturing URL parameters in request.GET

I would like to share a tip that may save you some time.
If you plan to use something like this in your urls.py file:

url(r'^(?P<username>\w+)/$', views.profile_page,),

Which basically means www.example.com/<username>. Be sure to place it at the end of your URL entries, because otherwise, it is prone to cause conflicts with the URL entries that follow below, i.e. accessing one of them will give you the nice error: User matching query does not exist.

I've just experienced it myself; hope it helps!

how to format date in Component of angular 5

Another option can be using built in angular formatDate function. I am assuming that you are using reactive forms. Here todoDate is a date input field in template.

import {formatDate} from '@angular/common';

this.todoForm.controls.todoDate.setValue(formatDate(this.todo.targetDate, 'yyyy-MM-dd', 'en-US'));

jQuery - checkbox enable/disable

This is the most up-to-date solution.

<form name="frmChkForm" id="frmChkForm">
    <input type="checkbox" name="chkcc9" id="group1" />Check Me
    <input type="checkbox" name="chk9[120]" class="group1" />
    <input type="checkbox" name="chk9[140]" class="group1" />
    <input type="checkbox" name="chk9[150]" class="group1" />
</form>

$(function() {
    enable_cb();
    $("#group1").click(enable_cb);
});

function enable_cb() {
    $("input.group1").prop("disabled", !this.checked);
}

Here is the usage details for .attr() and .prop().

jQuery 1.6+

Use the new .prop() function:

$("input.group1").prop("disabled", true);
$("input.group1").prop("disabled", false);

jQuery 1.5 and below

The .prop() function is not available, so you need to use .attr().

To disable the checkbox (by setting the value of the disabled attribute) do

$("input.group1").attr('disabled','disabled');

and for enabling (by removing the attribute entirely) do

$("input.group1").removeAttr('disabled');

Any version of jQuery

If you're working with just one element, it will always be fastest to use DOMElement.disabled = true. The benefit to using the .prop() and .attr() functions is that they will operate on all matched elements.

// Assuming an event handler on a checkbox
if (this.disabled)

ref: Setting "checked" for a checkbox with jQuery?

Row Offset in SQL Server

You can use ROW_NUMBER() function to get what you want:

SELECT *
FROM (SELECT ROW_NUMBER() OVER(ORDER BY id) RowNr, id FROM tbl) t
WHERE RowNr BETWEEN 10 AND 20

SQL Server Installation - What is the Installation Media Folder?

For the SQL Server 2017 (Developer Edition) installation, I did the following:

  1. Open SQL Server Installation Center
  2. Click on Installation
  3. Click on New SQL Server stand-alone installation or add features to an existing installation
  4. Browse to C:\SQLServer2017Media\Developer_ENU and click OK

How to run function in AngularJS controller on document ready?

Why not try with what angular docs mention https://docs.angularjs.org/api/ng/function/angular.element.

angular.element(callback)

I've used this inside my $onInit(){...} function.

 var self = this;

 angular.element(function () {
        var target = document.getElementsByClassName('unitSortingModule');
        target[0].addEventListener("touchstart", self.touchHandler, false);
        ...
    });

This worked for me.

Error while sending QUERY packet

If inserting 'too much data' fails due to the max_allowed_packet setting of the database server, the following warning is raised:

SQLSTATE[08S01]: Communication link failure: 1153 Got a packet bigger than 
'max_allowed_packet' bytes

If this warning is catched as exception (due to the set error handler), the database connection is (probably) lost but the application doesn't know about this (failing inserts can have several causes). The next query in line, which can be as simple as:

SELECT 1 FROM DUAL

Will then fail with the error this SO-question started:

Error while sending QUERY packet. PID=18486

Simple test script to reproduce my explanation, try it with and without the error handler to see the difference in impact:

set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) {
    // error was suppressed with the @-operator
    if (0 === error_reporting()) {
        return false;
    }

    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});

try
{
    // $oDb is instance of PDO
    var_dump($oDb->query('SELECT 1 FROM DUAL'));

    $oStatement = $oDb->prepare('INSERT INTO `test` (`id`, `message`) VALUES (NULL, :message);');
    $oStatement->bindParam(':message', $largetext, PDO::PARAM_STR);
    var_dump($oStatement->execute());
}
catch(Exception $e)
{
    $e->getMessage();
}
var_dump($oDb->query('SELECT 2 FROM DUAL'));

How to 'grep' a continuous stream?

I think that your problem is that grep uses some output buffering. Try

tail -f file | stdbuf -o0 grep my_pattern

it will set output buffering mode of grep to unbuffered.

How to handle the click event in Listview in android?

According to my test,

  1. implements OnItemClickListener -> works.

  2. setOnItemClickListener -> works.

  3. ListView is clickable by default (API 19)

The important thing is, "click" only works to TextView (if you choose simple_list_item_1.xml as item). That means if you provide text data for the ListView, "click" works when you click on text area. Click on empty area does not trigger "click event".

How to render an ASP.NET MVC view as a string?

you are get the view in string using this way

protected string RenderPartialViewToString(string viewName, object model)
{
    if (string.IsNullOrEmpty(viewName))
        viewName = ControllerContext.RouteData.GetRequiredString("action");

    if (model != null)
        ViewData.Model = model;

    using (StringWriter sw = new StringWriter())
    {
        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);

        return sw.GetStringBuilder().ToString();
    }
}

We are call this method in two way

string strView = RenderPartialViewToString("~/Views/Shared/_Header.cshtml", null)

OR

var model = new Person()
string strView = RenderPartialViewToString("~/Views/Shared/_Header.cshtml", model)

Set left margin for a paragraph in html

<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>

That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em' as the measurement, you may want to use other units, like 'px'.

EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:

In your HTML page, containing the <p> tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:

<head>
  <style type="text/css">
    p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>

So above, all <p> elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:

<head>
  <style type="text/css">
    .container p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <div class="container">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
  </div>
  <p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>

In the example above, only the <p> element inside the div, whose class name is 'container', will have the styles applied - and not the <p> element outside the container.

In addition to the above, you can collect your styles together and remove the style element from the <head> tag, replacing it with a <link> tag, which points to an external CSS file. This external file is where you'd now put your <p> tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.

How do I fix "Expected to return a value at the end of arrow function" warning?

The problem seems to be that you are not returning something in the event that your first if-case is false.

The error you are getting states that your arrow function (comment) => { doesn't have a return statement. While it does for when your if-case is true, it does not return anything for when it's false.

return this.props.comments.map((comment) => {
  if (comment.hasComments === true) {
    return (
      <div key={comment.id}>
        <CommentItem className="MainComment" />
        {this.props.comments.map(commentReply => {
          if (commentReply.replyTo === comment.id) { 
            return (
              <CommentItem className="SubComment"/>
            )
          }
        })
        }
      </div>
    )
  } else {
     //return something here.
  }
});

edit you should take a look at Kris' answer for how to better implement what you are trying to do.

Could not open input file: composer.phar

Another solution could be.. find the location of composer.phar file in your computer. If composer is installed successfully then it can be found in the installed directory.

Copy that location & instead of composer.phar in the command line, put the entire path there.

It also worked for me!

OR condition in Regex

I think what you need might be simply:

\d( \w)?

Note that your regex would have worked too if it was written as \d \w|\d instead of \d|\d \w.

This is because in your case, once the regex matches the first option, \d, it ceases to search for a new match, so to speak.

What is the difference between "#!/usr/bin/env bash" and "#!/usr/bin/bash"?

Using #!/usr/bin/env NAME makes the shell search for the first match of NAME in the $PATH environment variable. It can be useful if you aren't aware of the absolute path or don't want to search for it.

Are HTTPS URLs encrypted?

Additionally, if you're building a ReSTful API, browser leakage and http referer issues are mostly mitigated as the client may not be a browser and you may not have people clicking links.

If this is the case I'd recommend oAuth2 login to obtain a bearer token. In which case the only sensitive data would be the initial credentials...which should probably be in a post request anyway

How to uninstall mini conda? python

The proper way to fully uninstall conda (Anaconda / Miniconda):

  1. Remove all conda-related files and directories using the Anaconda-Clean package

    conda activate your_conda_env_name
    conda install anaconda-clean
    anaconda-clean # add `--yes` to avoid being prompted to delete each one
    
  2. Remove your entire conda directory

    rm -rf ~/miniconda3
    
  3. Remove the line which adds the conda path to the PATH environment variable

    vi ~/.bashrc
    # -> Search for conda and delete the lines containing it
    # -> If you're not sure if the line belongs to conda, comment it instead of deleting it just to be safe
    source ~/.bashrc
    
  4. Remove the backup folder created by the the Anaconda-Clean package NOTE: Think twice before doing this, because after that you won't be able to restore anything from your old conda installation!

    rm -rf ~/.anaconda_backup
    

Reference: Official conda documentation

maven error: package org.junit does not exist

I fixed this error by inserting these lines of code:

<dependency>
  <groupId>junit</groupId>     <!-- NOT org.junit here -->
  <artifactId>junit-dep</artifactId>
  <version>4.8.2</version>
  <scope>test</scope>
</dependency>

into <dependencies> node.

more details refer to: http://mvnrepository.com/artifact/junit/junit-dep/4.8.2

How do I convert a numpy array to (and display) an image?

The Python Imaging Library can display images using Numpy arrays. Take a look at this page for sample code:

EDIT: As the note on the bottom of that page says, you should check the latest release notes which make this much simpler:

http://effbot.org/zone/pil-changes-116.htm

How to validate an OAuth 2.0 access token for a resource server?

An update on @Scott T.'s answer: the interface between Resource Server and Authorization Server for token validation was standardized in IETF RFC 7662 in October 2015, see: https://tools.ietf.org/html/rfc7662. A sample validation call would look like:

POST /introspect HTTP/1.1
Host: server.example.com
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Authorization: Bearer 23410913-abewfq.123483

token=2YotnFZFEjr1zCsicMWpAA

and a sample response:

HTTP/1.1 200 OK
Content-Type: application/json

{
  "active": true,
  "client_id": "l238j323ds-23ij4",
  "username": "jdoe",
  "scope": "read write dolphin",
  "sub": "Z5O3upPC88QrAjx00dis",
  "aud": "https://protected.example.net/resource",
  "iss": "https://server.example.com/",
  "exp": 1419356238,
  "iat": 1419350238,
  "extension_field": "twenty-seven"
}

Of course adoption by vendors and products will have to happen over time.

Java Loop every minute

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.schedule(yourRunnable, 1L, TimeUnit.MINUTES);
...
// when done...
executor.shutdown();

How many threads can a Java VM support?

The absolute theoretical maximum is generally a process's user address space divided by the thread stack size (though in reality, if all your memory is reserved for thread stacks, you won't have a working program...).

So under 32-bit Windows, for example, where each process has a user address space of 2GB, giving each thread a 128K stack size, you'd expect an absolute maximum of 16384 threads (=2*1024*1024 / 128). In practice, I find I can start up about 13,000 under XP.

Then, I think you're essentially into whether (a) you can manage juggling that many threads in your code and not do obviously silly things (such as making them all wait on the same object then calling notifyAll()...), and (b) whether the operating system can. In principle, the answer to (b) is "yes" if the answer to (a) is also "yes".

Incidentally, you can specify the stack size in the constructor of the Thread; you don't need to (and probably shouldn't) mess about with VM parameters for this.

Android simple alert dialog

No my friend its very simple, try using this:

AlertDialog alertDialog = new AlertDialog.Builder(AlertDialogActivity.this).create();
alertDialog.setTitle("Alert Dialog");
alertDialog.setMessage("Welcome to dear user.");
alertDialog.setIcon(R.drawable.welcome);

alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
    }
});

alertDialog.show();

This tutorial shows how you can create custom dialog using xml and then show them as an alert dialog.

What is size_t in C?

If you are the empirical type,

echo | gcc -E -xc -include 'stddef.h' - | grep size_t

Output for Ubuntu 14.04 64-bit GCC 4.8:

typedef long unsigned int size_t;

Note that stddef.h is provided by GCC and not glibc under src/gcc/ginclude/stddef.h in GCC 4.2.

Interesting C99 appearances

  • malloc takes size_t as an argument, so it determines the maximum size that may be allocated.

    And since it is also returned by sizeof, I think it limits the maximum size of any array.

    See also: What is the maximum size of an array in C?

Can't import org.apache.http.HttpResponse in Android Studio

According to the Apache site this is the Gradle dependency you need to include, if you use Android API 23 or newer:

dependencies {
    compile group: 'cz.msebera.android' , name: 'httpclient', version: '4.4.1.1'
}

Source: https://hc.apache.org/httpcomponents-client-4.5.x/android-port.html

Getting the class of the element that fired an event using JQuery

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $("a").click(function(event) {_x000D_
    var myClass = $(this).attr("class");_x000D_
    var myId = $(this).attr('id');_x000D_
    alert(myClass + " " + myId);_x000D_
  });_x000D_
})
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <a href="#" id="kana1" class="konbo">click me 1</a>_x000D_
  <a href="#" id="kana2" class="kinta">click me 2</a>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

This works for me. There is no event.target.class function in jQuery.

Concatenate in jQuery Selector

There is nothing wrong with syntax of

$('#part' + number).html(text);

jQuery accepts a String (usually a CSS Selector) or a DOM Node as parameter to create a jQuery Object.

In your case you should pass a String to $() that is

$(<a string>)

Make sure you have access to the variables number and text.

To test do:

function(){
    alert(number + ":" + text);//or use console.log(number + ":" + text)
    $('#part' + number).html(text);
}); 

If you see you dont have access, pass them as parameters to the function, you have to include the uual parameters for $.get and pass the custom parameters after them.

Node.js spawn child process and get terminal output live

Adding an answer related to child_process.exec as I too had needed live feedback and wasn't getting any until after the script finished. This also supplements my comment to the accepted answer, but as it's formatted it will a bit more understandable and easier to read.

Basically, I have a npm script that calls Gulp, invoking a task which subsequently uses child_process.exec to execute a bash or batch script depending on the OS. Either script runs a build process via Gulp and then makes some calls to some binaries that work with the Gulp output.

It's exactly like the others (spawn, etc.), but for the sake of completion, here's exactly how to do it:

// INCLUDES
import * as childProcess from 'child_process'; // ES6 Syntax


// GLOBALS
let exec = childProcess.exec; // Or use 'var' for more proper 
                              // semantics, though 'let' is 
                              // true-to-scope


// Assign exec to a variable, or chain stdout at the end of the call
// to exec - the choice, yours (i.e. exec( ... ).stdout.on( ... ); )
let childProcess = exec
(
    './binary command -- --argument argumentValue',
    ( error, stdout, stderr ) =>
    {
        if( error )
        {
            // This won't show up until the process completes:
            console.log( '[ERROR]: "' + error.name + '" - ' + error.message );
            console.log( '[STACK]: ' + error.stack );

            console.log( stdout );
            console.log( stderr );
            callback();            // Gulp stuff
            return;
        }

        // Neither will this:
        console.log( stdout );
        console.log( stderr );
        callback();                // Gulp stuff
    }
);

Now its as simple as adding an event listener. For stdout:

childProcess.stdout.on
(
    'data',
    ( data ) =>
    {
        // This will render 'live':
        console.log( '[STDOUT]: ' + data );
    }
);

And for stderr:

childProcess.stderr.on
(
    'data',
    ( data ) =>
    {
        // This will render 'live' too:
        console.log( '[STDERR]: ' + data );
    }
);

Not too bad at all - HTH

How to create timer in angular2

If you look to run a method on ngOnInit you could do something like this:

import this 2 libraries from RXJS:

import {Observable} from 'rxjs/Rx';
import {Subscription} from "rxjs";

Then declare timer and private subscription, example:

timer= Observable.timer(1000,1000); // 1 second for 2 seconds (2000,1000) etc
private subscription: Subscription;

Last but not least run method when timer stops

ngOnInit() {
  this.subscription = this.timer.subscribe(ticks=> {
    this.populatecombobox();  //example calling a method that populates a combobox
    this.subscription.unsubscribe();  //you need to unsubscribe or it will run infinite times
  });
}

That's all, Angular 5

Updating a JSON object using Javascript

$(document).ready(function(){        
    var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},  
               {'Id':'2','Username':'Steve','FatherName':'Johnson'},
               {'Id':'3','Username':'Albert','FatherName':'Einstein'}];

    $.each(jsonObj,function(i,v){       
      if (v.Id == 3) {
        v.Username = "Thomas";
        return false;
      }
    });

alert("New Username: " + jsonObj[2].Username);

});

How to unlock a file from someone else in Team Foundation Server

If you login into the source control with the admin account, you will be able to force undo checkout, or check in with any file you provide.

How to change the color of an svg element?

To change color of SVG element I have found out a way while inspecting Google search box search icon below:

_x000D_
_x000D_
.search_icon {
  color: red;
  fill: currentColor;
  display: inline-block;
  width: 100px;
  height: 100px;
}
_x000D_
<span class="search_icon">
    <svg focusable="false" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M15.5 14h-.79l-.28-.27A6.471 6.471 0 0 0 16 9.5 6.5 6.5 0 1 0 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path></svg>
</span>
_x000D_
_x000D_
_x000D_

I have used span element with "display:inline-block", height, width and setting a particular style "color: red; fill: currentColor;" to that span tag which is inherited by the child svg element.

Saving the PuTTY session logging

It works fine for me, but it's a little tricky :)

  • First open the PuTTY configuration.
  • Select the session (right part of the window, Saved Sessions)
  • Click Load (now you have loaded Host Name, Port and Connection type)
  • Then click Logging (under Session on the left)
  • Change whatever settings you want
  • Go back to Session window and click the Save button

Now you have settings for this session set (every time you load session it will be logged).

Enable SQL Server Broker taking too long

USE master;
GO
ALTER DATABASE Database_Name
    SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE;
GO
USE Database_Name;
GO

How to specify the port an ASP.NET Core application is hosted on?

Above .net core 2.2 the method Main support args with WebHost.CreateDefaultBuilder(args)

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

You can build your project and go to bin run command like this

dotnet <yours>.dll --urls=http://localhost:5001

or with multi-urls

dotnet <yours>.dll --urls="http://localhost:5001,https://localhost:5002"

Generate a unique id

Why can't we make a unique id as below.

We can use DateTime.Now.Ticks and Guid.NewGuid().ToString() to combine together and make a unique id.

As the DateTime.Now.Ticks is added, we can find out the Date and Time in seconds at which the unique id is created.

Please see the code.

var ticks = DateTime.Now.Ticks;
var guid = Guid.NewGuid().ToString();
var uniqueSessionId = ticks.ToString() +'-'+ guid; //guid created by combining ticks and guid

var datetime = new DateTime(ticks);//for checking purpose
var datetimenow = DateTime.Now;    //both these date times are different.

We can even take the part of ticks in unique id and check for the date and time later for future reference.

Handle spring security authentication exceptions with @ExceptionHandler

The best way I've found is to delegate the exception to the HandlerExceptionResolver

@Component("restAuthenticationEntryPoint")
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Autowired
    private HandlerExceptionResolver resolver;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        resolver.resolveException(request, response, null, exception);
    }
}

then you can use @ExceptionHandler to format the response the way you want.

Using multiple IF statements in a batch file

The explanation given by Merlyn above is pretty complete. However, I would like to elaborate on coding standards.

When several IF's are chained, the final command is executed when all the previous conditions are meet; this is equivalent to an AND operator. I used this behavior now and then, but I clearly indicate what I intend to do via an auxiliary Batch variable called AND:

SET AND=IF

IF EXIST somefile.txt %AND% EXIST someotherfile.txt SET var=somefile.txt,someotherfile.txt

Of course, this is NOT a true And operator and must not be used in combination with ELSE clause. This is just a programmer aid to increase the legibility of an instruction that is rarely used.

When I write Batch programs I always use several auxiliary variables that I designed with the sole purpose of write more readable code. For example:

SET AND=IF
SET THEN=(
SET ELSE=) ELSE (
SET NOELSE=
SET ENDIF=)
SET BEGIN=(
SET END=)
SET RETURN=EXIT /B

These variables aids in writting Batch programs in a much clearer way and helps to avoid subtle errors, as Merlyn suggested. For example:

IF EXIST "somefile.txt" %THEN%
  IF EXIST "someotherfile.txt" %THEN%
    SET var="somefile.txt,someotherfile.txt"
  %NOELSE%
  %ENDIF%
%NOELSE%
%ENDIF%

IF EXIST "%~1" %THEN%
  SET "result=%~1"
%ELSE%
  SET "result="
%ENDIF%

I even have variables that aids in writting WHILE-DO and REPEAT-UNTIL like constructs. This means that Batch variables may be used in some degree as preprocessor values.

How to install python developer package?

yum install python-devel will work.

If yum doesn't work then use

apt-get install python-dev

Laravel - Form Input - Multiple select for a one to many relationship

@SamMonk your technique is great. But you can use laravel form helper to do so. I have a customer and dogs relationship.

On your controller

$dogs = Dog::lists('name', 'id');

On customer create view you can use.

{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, null, ['id' => 'dogs', 'multiple' => 'multiple']) }}

Third parameter accepts a list of array a well. If you define a relationship on your model you can do this:

{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, $customer->dogs->lists('id'), ['id' => 'dogs', 'multiple' => 'multiple']) }}

Update For Laravel 5.1

The lists method now returns a Collection. Upgrading To 5.1.0

{!! Form::label('dogs', 'Dogs') !!}
{!! Form::select('dogs[]', $dogs, $customer->dogs->lists('id')->all(), ['id' => 'dogs', 'multiple' => 'multiple']) !!}

identifier "string" undefined?

Perhaps you wanted to #include<string>, not <string.h>. std::string also needs a namespace qualification, or an explicit using directive.

Send text to specific contact programmatically (whatsapp)

 private void openWhatsApp() {
       //without '+'
        try {
            Intent sendIntent = new Intent("android.intent.action.MAIN");

            //sendIntent.setComponent(new ComponentName("com.whatsapp", "com.whatsapp.Conversation"));
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.setType("text/plain");
            sendIntent.putExtra("jid",whatsappId);
            sendIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            sendIntent.setPackage("com.whatsapp");
            startActivity(sendIntent);
        } catch(Exception e) {
            Toast.makeText(this, "Error/n" + e.toString(), Toast.LENGTH_SHORT).show();
            Log.e("Error",e+"")    ;    }
    }

How to fully delete a git repository created with init?

If you want to delete all .git folders in a project use the following command:

find . -type f | grep -i "\.git" | xargs rm

This will also delete all the .git folders and .gitignore files from all subfolders

How to create Haar Cascade (.xml file) to use in OpenCV?

How to create CascadeClassifier :

  1. Open this link : https://github.com/opencv/opencv/tree/master/data/haarcascades
  2. Right click on where you find "haarcascade_frontalface_default.xml"
  3. Click on "Save link as"
  4. Save it into the same folder in which your file is.
  5. Include this line in your file face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")

UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples

As I have noticed this error occurs under two circumstances,

  1. If you have used train_test_split() to split your data, you have to make sure that you reset the index of the data (specially when taken using a pandas series object): y_train, y_test indices should be resetted. The problem is when you try to use one of the scores from sklearn.metrics such as; precision_score, this will try to match the shuffled indices of the y_test that you got from train_test_split().

so use, either np.array(y_test) for y_true in scores or y_test.reset_index(drop=True)

  1. Then again you can still have this error if your predicted 'True Positives' is 0, which is used for precision, recall and f1_scores. You can visualize this using a confusion_matrix. If the classification is multilabel and you set param: average='weighted'/micro/macro you will get an answer as long as the diagonal line in the matrix is not 0

Hope this helps.

jquery $.each() for objects

$.each() works for objects and arrays both:

var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };

$.each(data.programs, function (i) {
    $.each(data.programs[i], function (key, val) {
        alert(key + val);
    });
});

...and since you will get the current array element as second argument:

$.each(data.programs, function (i, currProgram) {
    $.each(currProgram, function (key, val) {
        alert(key + val);
    });
});

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

got into same kind of problem, wasn't able to exclude main spring boot class during testing. Solved it using following approach.

Instead of using @SpringBootApplication, use all three annotations which it contains and assign the name to @Configuration

@Configuration("myApp")
@EnableAutoConfiguration
@ComponentScan
public class MyApp { .. }

In your test class define configuration with exactly same name:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
// ugly hack how to exclude main configuration
@Configuration("myApp")
@SpringApplicationConfiguration(classes = MyTest.class)
public class MyTest { ... }

This should help. Would be nice to have some better way in place how to disable auto scanning for configuration annotations...

Background Image for Select (dropdown) does not work in Chrome

What Arne said - you can't reliably style select boxes and have them look anything like consistent across browsers.

Uniform: https://github.com/pixelmatrix/uniform is a javascript solution which gives you good graphic control over your form elements - it's still Javascript, but it's about as nice as javascript gets for solving this problem.

SQL Server IF NOT EXISTS Usage?

Have you verified that there is in fact a row where Staff_Id = @PersonID? What you've posted works fine in a test script, assuming the row exists. If you comment out the insert statement, then the error is raised.

set nocount on

create table Timesheet_Hours (Staff_Id int, BookedHours int, Posted_Flag bit)

insert into Timesheet_Hours (Staff_Id, BookedHours, Posted_Flag) values (1, 5.5, 0)

declare @PersonID int
set @PersonID = 1

IF EXISTS    
    (
    SELECT 1    
    FROM Timesheet_Hours    
    WHERE Posted_Flag = 1    
        AND Staff_Id = @PersonID    
    )    
    BEGIN
        RAISERROR('Timesheets have already been posted!', 16, 1)
        ROLLBACK TRAN
    END
ELSE
    IF NOT EXISTS
        (
        SELECT 1
        FROM Timesheet_Hours
        WHERE Staff_Id = @PersonID
        )
        BEGIN
            RAISERROR('Default list has not been loaded!', 16, 1)
            ROLLBACK TRAN
        END
    ELSE
        print 'No problems here'

drop table Timesheet_Hours

Why can I not push_back a unique_ptr into a vector?

You need to move the unique_ptr:

vec.push_back(std::move(ptr2x));

unique_ptr guarantees that a single unique_ptr container has ownership of the held pointer. This means that you can't make copies of a unique_ptr (because then two unique_ptrs would have ownership), so you can only move it.

Note, however, that your current use of unique_ptr is incorrect. You cannot use it to manage a pointer to a local variable. The lifetime of a local variable is managed automatically: local variables are destroyed when the block ends (e.g., when the function returns, in this case). You need to dynamically allocate the object:

std::unique_ptr<int> ptr(new int(1));

In C++14 we have an even better way to do so:

make_unique<int>(5);

What's the difference between process.cwd() vs __dirname?

process.cwd() returns the current working directory,

i.e. the directory from which you invoked the node command.

__dirname returns the directory name of the directory containing the JavaScript source code file

Python "expected an indented block"

The body of the loop is indented: indentation is Python’s way of grouping statements. At the interactive prompt, you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount.

src: ##

##https://docs.python.org/3/tutorial/introduction.html#using-python-as-a-calculator

"CAUTION: provisional headers are shown" in Chrome debugger

In my case, the body parameters I was sending in the post request, and logic I have writting depending on the body parameters were wrong, so the response was not able to be sent. so I was getting this error.

 example: post request body (a: alsldfjfj) which I was sending

but I had written the code for validating "b" instead of "a"

document.getelementbyId will return null if element is not defined?

console.log(document.getElementById('xx') ) evaluates to null.

document.getElementById('xx') !=null evaluates to false

You should use document.getElementById('xx') !== null as it is a stronger equality check.

asp.net: Invalid postback or callback argument

This is probably not the cause of your issue, but I noticed you were using optgroups in your dropdown so I figured this might help someone should they wind up here with this issue. For me, I needed to create a dropdownlist that would render with optgroups, and I ended up using the accepted answer here but while it would render the control correctly, it gave me this error. How I got past that is detailed in my answer here.

How to BULK INSERT a file into a *temporary* table where the filename is a variable?

You could always construct the #temp table in dynamic SQL. For example, right now I guess you have been trying:

CREATE TABLE #tmp(a INT, b INT, c INT);

DECLARE @sql NVARCHAR(1000);

SET @sql = N'BULK INSERT #tmp ...' + @variables;

EXEC master.sys.sp_executesql @sql;

SELECT * FROM #tmp;

This makes it tougher to maintain (readability) but gets by the scoping issue:

DECLARE @sql NVARCHAR(MAX);

SET @sql = N'CREATE TABLE #tmp(a INT, b INT, c INT);

BULK INSERT #tmp ...' + @variables + ';

SELECT * FROM #tmp;';

EXEC master.sys.sp_executesql @sql;

EDIT 2011-01-12

In light of how my almost 2-year old answer was suddenly deemed incomplete and unacceptable, by someone whose answer was also incomplete, how about:

CREATE TABLE #outer(a INT, b INT, c INT);

DECLARE @sql NVARCHAR(MAX);

SET @sql = N'SET NOCOUNT ON; 

CREATE TABLE #inner(a INT, b INT, c INT);

BULK INSERT #inner ...' + @variables + ';

SELECT * FROM #inner;';

INSERT #outer EXEC master.sys.sp_executesql @sql;

How to set the min and max height or width of a Frame?

A workaround - at least for the minimum size: You can use grid to manage the frames contained in root and make them follow the grid size by setting sticky='nsew'. Then you can use root.grid_rowconfigure and root.grid_columnconfigure to set values for minsize like so:

from tkinter import Frame, Tk

class MyApp():
    def __init__(self):
        self.root = Tk()

        self.my_frame_red = Frame(self.root, bg='red')
        self.my_frame_red.grid(row=0, column=0, sticky='nsew')

        self.my_frame_blue = Frame(self.root, bg='blue')
        self.my_frame_blue.grid(row=0, column=1, sticky='nsew')

        self.root.grid_rowconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(1, weight=1)

        self.root.mainloop()

if __name__ == '__main__':
    app = MyApp()

But as Brian wrote (in 2010 :D) you can still resize the window to be smaller than the frame if you don't limit its minsize.

How can I resolve the error "The security token included in the request is invalid" when running aws iam upload-server-certificate?

I was able to use AWS cli fully authenticated, so for me the issue was within terraform for sure. I tried all the steps above with no success. A reboot fixed it for me, there must be some a cache somewhere in terraform that was causing this issue.

Android, How to limit width of TextView (and add three dots at the end of text)?

you can do that by xml:

<TextView 
    android:id="@+id/textview"
    android:maxLines="1" // or any number of lines you want
    android:ellipsize="end"
    />

Transition color fade on hover?

For having a trasition effect like a highlighter just to highlight the text and fade off the bg color, we used the following:

_x000D_
_x000D_
.field-error {_x000D_
    color: #f44336;_x000D_
    padding: 2px 5px;_x000D_
    position: absolute;_x000D_
    font-size: small;_x000D_
    background-color: white;_x000D_
}_x000D_
_x000D_
.highlighter {_x000D_
    animation: fadeoutBg 3s; /***Transition delay 3s fadeout is class***/_x000D_
    -moz-animation: fadeoutBg 3s; /* Firefox */_x000D_
    -webkit-animation: fadeoutBg 3s; /* Safari and Chrome */_x000D_
    -o-animation: fadeoutBg 3s; /* Opera */_x000D_
}_x000D_
_x000D_
@keyframes fadeoutBg {_x000D_
    from { background-color: lightgreen; } /** from color **/_x000D_
    to { background-color: white; } /** to color **/_x000D_
}_x000D_
_x000D_
@-moz-keyframes fadeoutBg { /* Firefox */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes fadeoutBg { /* Safari and Chrome */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-o-keyframes fadeoutBg { /* Opera */_x000D_
    from { background-color: lightgreen; }_x000D_
    to { background-color: white; }_x000D_
}
_x000D_
<div class="field-error highlighter">File name already exists.</div>
_x000D_
_x000D_
_x000D_

Determine the line of code that causes a segmentation fault?

All of the above answers are correct and recommended; this answer is intended only as a last-resort if none of the aforementioned approaches can be used.

If all else fails, you can always recompile your program with various temporary debug-print statements (e.g. fprintf(stderr, "CHECKPOINT REACHED @ %s:%i\n", __FILE__, __LINE__);) sprinkled throughout what you believe to be the relevant parts of your code. Then run the program, and observe what the was last debug-print printed just before the crash occurred -- you know your program got that far, so the crash must have happened after that point. Add or remove debug-prints, recompile, and run the test again, until you have narrowed it down to a single line of code. At that point you can fix the bug and remove all of the temporary debug-prints.

It's quite tedious, but it has the advantage of working just about anywhere -- the only times it might not is if you don't have access to stdout or stderr for some reason, or if the bug you are trying to fix is a race-condition whose behavior changes when the timing of the program changes (since the debug-prints will slow down the program and change its timing)

How to find if a given key exists in a C++ std::map

map<string, string> m;

check key exist or not, and return number of occurs(0/1 in map):

int num = m.count("f");  
if (num>0) {    
    //found   
} else {  
    // not found  
}

check key exist or not, and return iterator:

map<string,string>::iterator mi = m.find("f");  
if(mi != m.end()) {  
    //found  
    //do something to mi.  
} else {  
    // not found  
}  

in your question, the error caused by bad operator<< overload, because p.first is map<string, string>, you can not print it out. try this:

if(p.first != p.second) {
    cout << p.first->first << " " << p.first->second << endl;
}

What process is listening on a certain port on Solaris?

This is sort of an indirect approach, but you could see if a website loads on your web browser of choice from whatever is running on port 80. Or you could telnet to port 80 and see if you get a response that gives you a clue as to what is running on that port and you can go shut it down. Since port 80 is the default port for http traffic chances are there is some sort of http server running there by default, but there's no guarantee.

python pip: force install ignoring dependencies

pip has a --no-dependencies switch. You should use that.

For more information, run pip install -h, where you'll see this line:

--no-deps, --no-dependencies
                        Ignore package dependencies

Android Service Stops When App Is Closed

Services are quite complicated sometimes.

When you start a service from an activity (or your process), the service is essentially on the same process.

quoting from the developer notes

Most confusion about the Service class actually revolves around what it is not:

A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.

A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).

So, what this means is, if the user swipes the app away from the recent tasks it will delete your process(this includes all your activities etc). Now, lets take three scenarios.

First where the service does not have a foreground notification.

In this case your process is killed along with your service.

Second where the service has a foreground notification

In this case the service is not killed and neither is the process

Third scenario If the service does not have a foreground notification, it can still keep running if the app is closed. We can do this by making the service run in a different process. (However, I've heard some people say that it may not work. left to you to try it out yourself)

you can create a service in a separate process by including the below attribute in your manifest.

android:process=":yourService"

or

android:process="yourService" process name must begin with lower case.

quoting from developer notes

If the name assigned to this attribute begins with a colon (':'), a new process, private to the application, is created when it's needed and the service runs in that process. If the process name begins with a lowercase character, the service will run in a global process of that name, provided that it has permission to do so. This allows components in different applications to share a process, reducing resource usage.

this is what I have gathered, if anyone is an expert, please do correct me if I'm wrong :)

Disable a Button

in order for this to work:

yourButton.isEnabled = false

you need to create an outlet in addition to your UI button.

Converting a String to Object

String extends Object, which means an Object. Object o = a; If you really want to get as Object, you may do like below.

String s = "Hi";

Object a =s;

ListView item background via custom selector

You can write a theme:

<pre>

    android:name=".List10" android:theme="@style/Theme"

theme.xml

<style name="Theme" parent="android:Theme">
        <item name="android:listViewStyle">@style/MyListView</item>
</style>

styles.xml

 <style name="MyListView" parent="@android:style/Widget.ListView">
<item name="android:listSelector">@drawable/my_selector</item>

my_selector is your want to custom selector I am sorry i donot know how to write my code

Select rows with same id but different value in another column

This is an old question yet I find that I also need a solution for this from time to time. The previous answers are all good and works well, I just personally prefer using CTE, for example:

DECLARE @T TABLE (ARIDNR INT, LIEFNR varchar(5)) --table variable for loading sample data
INSERT INTO @T (ARIDNR, LIEFNR) VALUES (1,'A'),(2,'A'),(3,'A'),(1,'B'),(2,'B'); --add your sample data to it
WITH duplicates AS --the CTE portion to find the duplicates
(
    SELECT ARIDNR FROM @T GROUP BY ARIDNR HAVING COUNT(*) > 1
)
SELECT t.* FROM @T t --shows results from main table
INNER JOIN duplicates d on t.ARIDNR = d.ARIDNR --where the main table can be joined to the duplicates CTE

Yields the following results:

1|A
1|B
2|B
2|A

Get GPS location via a service in Android

Take a look at Google Play Location Samples

Location Updates using a Foreground Service: Get updates about a device's location using a bound and started foreground service.

Location Updates using a PendingIntent: Get updates about a device's location using a PendingIntent. Sample shows implementation using an IntentService as well as a BroadcastReceiver.

How do I measure execution time of a command on the Windows command line?

The following script uses only "cmd.exe" and outputs the number of milliseconds from the time a pipeline is created to the time that the process preceding the script exits. i.e., Type your command, and pipe the to the script. Example: "timeout 3 | runtime.cmd" should yield something like "2990." If you need both the runtime output and the stdin output, redirect stdin before the pipe - ex: "dir /s 1>temp.txt | runtime.cmd" would dump the output of the "dir" command to "temp.txt" and would print the runtime to the console.

:: --- runtime.cmd ----
@echo off
setlocal enabledelayedexpansion

:: find target for recursive calls
if not "%1"=="" (
    shift /1
    goto :%1
    exit /b
)

:: set pipeline initialization time
set t1=%time%

:: wait for stdin
more > nul

:: set time at which stdin was ready
set t2=!time!

::parse t1
set t1=!t1::= !
set t1=!t1:.= !
set t1=!t1: 0= !

:: parse t2
set t2=!t2::= !
set t2=!t2:.= !
set t2=!t2: 0= !

:: calc difference
pushd %~dp0
for /f %%i in ('%0 calc !t1!') do for /f %%j in ('%0 calc !t2!') do (
    set /a t=%%j-%%i
    echo !t!
)
popd
exit /b
goto :eof

:calc
set /a t=(%1*(3600*1000))+(%2*(60*1000))+(%3*1000)+(%4)
echo !t!
goto :eof

endlocal

Original purpose of <input type="hidden">?

I can only imagine of sending a value from the server to the client which is (unchanged) sent back to maintain a kind of a state.

Precisely. In fact, it's still being used for this purpose today because HTTP as we know it today is still, at least fundamentally, a stateless protocol.

This use case was actually first described in HTML 3.2 (I'm surprised HTML 2.0 didn't include such a description):

type=hidden
These fields should not be rendered and provide a means for servers to store state information with a form. This will be passed back to the server when the form is submitted, using the name/value pair defined by the corresponding attributes. This is a work around for the statelessness of HTTP. Another approach is to use HTTP "Cookies".

<input type=hidden name=customerid value="c2415-345-8563">

While it's worth mentioning that HTML 3.2 became a W3C Recommendation only after JavaScript's initial release, it's safe to assume that hidden fields have pretty much always served the same purpose.

How do I concatenate strings?

Simple ways to concatenate strings in Rust

There are various methods available in Rust to concatenate strings

First method (Using concat!() ):

fn main() {
    println!("{}", concat!("a", "b"))
}

The output of the above code is :

ab


Second method (using push_str() and + operator):

fn main() {
    let mut _a = "a".to_string();
    let _b = "b".to_string();
    let _c = "c".to_string();

    _a.push_str(&_b);

    println!("{}", _a);

    println!("{}", _a + &_c);
}

The output of the above code is:

ab

abc


Third method (Using format!()):

fn main() {
    let mut _a = "a".to_string();
    let _b = "b".to_string();
    let _c = format!("{}{}", _a, _b);

    println!("{}", _c);
}

The output of the above code is :

ab

Check it out and experiment with Rust playground.

transform object to array with lodash

var arr = _.map(obj)

You can use _.map function (of both lodash and underscore) with object as well, it will internally handle that case, iterate over each value and key with your iteratee, and finally return an array. Infact, you can use it without any iteratee (just _.map(obj)) if you just want a array of values. The good part is that, if you need any transformation in between, you can do it in one go.

Example:

_x000D_
_x000D_
var obj = {_x000D_
    key1: {id: 1, name: 'A'},_x000D_
    key2: {id: 2, name: 'B'},_x000D_
    key3: {id: 3, name: 'C'}_x000D_
};_x000D_
_x000D_
var array1 = _.map(obj, v=>v);_x000D_
console.log('Array 1: ', array1);_x000D_
_x000D_
/*Actually you don't need the callback v=>v if you_x000D_
are not transforming anything in between, v=>v is default*/_x000D_
_x000D_
//SO simply you can use_x000D_
var array2 = _.map(obj);_x000D_
console.log('Array 2: ', array2);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
_x000D_
_x000D_
_x000D_

However, if you want to transform your object you can do so, even if you need to preserve the key, you can do that ( _.map(obj, (v, k) => {...}) with additional argument in map and then use it how you want.

However there are other Vanilla JS solution to this (as every lodash solution there should pure JS version of it) like:

  • Object.keys and then map them to values
  • Object.values (in ES-2017)
  • Object.entries and then map each key/value pairs (in ES-2017)
  • for...in loop and use each keys for feting values

And a lot more. But since this question is for lodash (and assuming someone already using it) then you don't need to think a lot about version, support of methods and error handling if those are not found.

There are other lodash solutions like _.values (more readable for specific perpose), or getting pairs and then map and so on. but in the case your code need flexibility that you can update it in future as you need to preserve keys or transforming values a bit, then the best solution is to use a single _.map as addresed in this answer. That will bt not that difficult as per readability also.

Add column to SQL query results

Manually add it when you build the query:

SELECT 'Site1' AS SiteName, t1.column, t1.column2
FROM t1

UNION ALL
SELECT 'Site2' AS SiteName, t2.column, t2.column2
FROM t2

UNION ALL
...

EXAMPLE:

DECLARE @t1 TABLE (column1 int, column2 nvarchar(1))
DECLARE @t2 TABLE (column1 int, column2 nvarchar(1))

INSERT INTO @t1
SELECT 1, 'a'
UNION SELECT 2, 'b'

INSERT INTO @t2
SELECT 3, 'c'
UNION SELECT 4, 'd'


SELECT 'Site1' AS SiteName, t1.column1, t1.column2
FROM @t1 t1

UNION ALL
SELECT 'Site2' AS SiteName, t2.column1, t2.column2
FROM @t2 t2

RESULT:

SiteName  column1  column2
Site1       1      a
Site1       2      b
Site2       3      c
Site2       4      d

How to list containers in Docker

To list only the containers SHA1:

docker ps -aq --no-trunc

That way, you can use the list of all containers for other commands (which accept multiple container ids as parameters).

For example, to list only the name of all containers (since docker ps list only their names with other information):

docker inspect --format='{{.Name}}' $(sudo docker ps -aq --no-trunc)

static const vs #define

Defining constants by using preprocessor directive #define is not recommended to apply not only in C++, but also in C. These constants will not have the type. Even in C was proposed to use const for constants.

Make a float only show two decimal places

You can also try using NSNumberFormatter:

NSNumberFormatter* nf = [[[NSNumberFormatter alloc] init] autorelease];
nf.positiveFormat = @"0.##";
NSString* s = [nf stringFromNumber: [NSNumber numberWithFloat: myFloat]];

You may need to also set the negative format, but I think it's smart enough to figure it out.

How can I programmatically determine if my app is running in the iphone simulator?

Already asked, but with a very different title.

What #defines are set up by Xcode when compiling for iPhone

I'll repeat my answer from there:

It's in the SDK docs under "Compiling source code conditionally"

The relevant definition is TARGET_OS_SIMULATOR, which is defined in /usr/include/TargetConditionals.h within the iOS framework. On earlier versions of the toolchain, you had to write:

#include "TargetConditionals.h"

but this is no longer necessary on the current (Xcode 6/iOS8) toolchain.

So, for example, if you want to check that you are running on device, you should do

#if TARGET_OS_SIMULATOR
    // Simulator-specific code
#else
    // Device-specific code
#endif

depending on which is appropriate for your use-case.

Android Left to Right slide animation

Also, you can do this:

FirstClass.this.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);

And you don't need to add any animation xml

How to get address location from latitude and longitude in Google Map.?

Simply pass latitude, longitude and your Google API Key to the following query string, you will get a json array, fetch your city from there.

https://maps.googleapis.com/maps/api/geocode/json?latlng=44.4647452,7.3553838&key=YOUR_API_KEY

Note: Ensure that no space exists between the latitude and longitude values when passed in the latlng parameter.

Click here to get an API key

JOptionPane Yes or No window

"if(true)" will always be true and it will never make it to the else. If you want it to work correctly you have to do this:

int reply = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
    JOptionPane.showMessageDialog(null, "HELLO");
} else {
    JOptionPane.showMessageDialog(null, "GOODBYE");
    System.exit(0);
}

JavaScript editor within Eclipse

Oracle Workshop for WebLogic (formally BEA Workshop) has excellent support for JavaScript and for visually editing HTMLs. It support many servers, not only WebLogic, including Tomcat, JBoss, Resin, Jetty, and WebSphere.

It recently became free, check out my post about it. Given that it was an expensive product not long ago, I guess it's worth checking out.

Slick.js: Get current and total slides (ie. 3/5)

The slider object contains the slide count as property.

Slick < 1.5

$('.slideshow').slick({
    slide: 'img',
    autoplay: true,
    dots: true,
    dotsClass: 'custom_paging',
    customPaging: function (slider, i) {
        //FYI just have a look at the object to find available information
        //press f12 to access the console in most browsers
        //you could also debug or look in the source
        console.log(slider);
        return  (i + 1) + '/' + slider.slideCount;
    }
});

DEMO

Update for Slick 1.5+ (tested until 1.8.1)

var $status = $('.pagingInfo');
var $slickElement = $('.slideshow');

$slickElement.on('init reInit afterChange', function(event, slick, currentSlide, nextSlide){
    //currentSlide is undefined on init -- set it to 0 in this case (currentSlide is 0 based)
    var i = (currentSlide ? currentSlide : 0) + 1;
    $status.text(i + '/' + slick.slideCount);
});

$slickElement.slick({
    slide: 'img',
    autoplay: true,
    dots: true
});

DEMO

Update for Slick 1.9+

var $status = $('.pagingInfo');
var $slickElement = $('.slideshow');

$slickElement.on('init reInit afterChange', function(event, slick, currentSlide, nextSlide){
    //currentSlide is undefined on init -- set it to 0 in this case (currentSlide is 0 based)
    var i = (currentSlide ? currentSlide : 0) + 1;
    $status.text(i + '/' + slick.slideCount);
});

$slickElement.slick({
    autoplay: true,
    dots: true
});

DEMO

Example when using slidesToShow

var $status = $('.pagingInfo');
var $slickElement = $('.slideshow');

$slickElement.on('init reInit afterChange', function (event, slick, currentSlide, nextSlide) {
  // no dots -> no slides
  if(!slick.$dots){
    return;
  }

  //currentSlide is undefined on init -- set it to 0 in this case (currentSlide is 0 based)
  var i = (currentSlide ? currentSlide : 0) + 1;
  // use dots to get some count information
  $status.text(i + '/' + (slick.$dots[0].children.length));
});

$slickElement.slick({
  infinite: false,
  slidesToShow: 4,
  autoplay: true,
  dots: true
});

DEMO

R data formats: RData, Rda, Rds etc

Rda is just a short name for RData. You can just save(), load(), attach(), etc. just like you do with RData.

Rds stores a single R object. Yet, beyond that simple explanation, there are several differences from a "standard" storage. Probably this R-manual Link to readRDS() function clarifies such distinctions sufficiently.

So, answering your questions:

  • The difference is not about the compression, but serialization (See this page)
  • Like shown in the manual page, you may wanna use it to restore a certain object with a different name, for instance.
  • You may readRDS() and save(), or load() and saveRDS() selectively.

Get value (String) of ArrayList<ArrayList<String>>(); in Java

The right way to iterate on a list inside list is:

//iterate on the general list
for(int i = 0 ; i < collection.size() ; i++) {
    ArrayList<String> currentList = collection.get(i);
    //now iterate on the current list
    for (int j = 0; j < currentList.size(); j++) {
        String s = currentList.get(1);
    }
}

Column order manipulation using col-lg-push and col-lg-pull in Twitter Bootstrap 3

Pull "pulls" the div towards the left of the browser and and Push "pushes" the div away from left of browser.

Like: enter image description here

So basically in a 3 column layout of any web page the "Main Body" appears at the "Center" and in "Mobile" view the "Main Body" appears at the "Top" of the page. This is mostly desired by everyone with 3 column layout.

<div class="container">
    <div class="row">
        <div id="content" class="col-lg-4 col-lg-push-4 col-sm-12">
        <h2>This is Content</h2>
        <p>orem Ipsum ...</p>
        </div>

        <div id="sidebar-left" class="col-lg-4  col-sm-6 col-lg-pull-4">
        <h2>This is Left Sidebar</h2>
        <p>orem Ipsum...</p>
        </div>


        <div id="sidebar-right" class="col-lg-4 col-sm-6">
        <h2>This is Right Sidebar</h2>
        <p>orem Ipsum.... </p>
        </div>
    </div>
</div>

You can view it here: http://jsfiddle.net/DrGeneral/BxaNN/1/

Hope it helps

if A vs if A is not None:

if A: will prove false if A is 0, False, empty string, empty list or None, which can lead to undesired results.

@Resource vs @Autowired

Both of them are equally good. The advantage of using Resource is in future if you want to another DI framework other than spring, your code changes will be much simpler. Using Autowired your code is tightly coupled with springs DI.

HTML Agility pack - parsing tables

In my case, there is a single table which happens to be a device list from a router. If you wish to read the table using TR/TH/TD (row, header, data) instead of a matrix as mentioned above, you can do something like the following:

    List<TableRow> deviceTable = (from table in document.DocumentNode.SelectNodes(XPathQueries.SELECT_TABLE)
                                       from row in table?.SelectNodes(HtmlBody.TR)
                                       let rows = row.SelectSingleNode(HtmlBody.TR)
                                       where row.FirstChild.OriginalName != null && row.FirstChild.OriginalName.Equals(HtmlBody.T_HEADER)
                                       select new TableRow
                                       {
                                           Header = row.SelectSingleNode(HtmlBody.T_HEADER)?.InnerText,
                                           Data = row.SelectSingleNode(HtmlBody.T_DATA)?.InnerText}).ToList();
                                       }  

TableRow is just a simple object with Header and Data as properties. The approach takes care of null-ness and this case:

_x000D_
_x000D_
<tr>_x000D_
    <td width="28%">&nbsp;</td>_x000D_
</tr>
_x000D_
_x000D_
_x000D_

which is row without a header. The HtmlBody object with the constants hanging off of it are probably readily deduced but I apologize for it even still. I came from the world where if you have " in your code, it should either be constant or localizable.

How to count total lines changed by a specific author in a Git repository?

To count number of commits by a given author (or all authors) on a given branch you can use git-shortlog; see especially its --numbered and --summary options, e.g. when run on git repository:

$ git shortlog v1.6.4 --numbered --summary
  6904  Junio C Hamano
  1320  Shawn O. Pearce
  1065  Linus Torvalds
    692  Johannes Schindelin
    443  Eric Wong

load external css file in body tag

No, it is not okay to put a link element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):

“This element defines a link. Unlike A, it may only appear in the HEAD section of a document, although it may appear any number of times.”

Reading values from DataTable

DataTable dr_art_line_2 = ds.Tables["QuantityInIssueUnit"];

for (int i = 0; i < dr_art_line_2.Rows.Count; i++)
{
    QuantityInIssueUnit_value = Convert.ToInt32(dr_art_line_2.Rows[i]["columnname"]);
    //Similarly for QuantityInIssueUnit_uom.
}

How to set up ES cluster?

Elastic Search 7 changed the configurations for cluster initialisation. What is important to note is the ES instances communicate internally using the Transport layer(TCP) and not the HTTP protocol which is normally used to perform ops on the indices. Below is sample config for 2 machines cluster.

cluster.name: cluster-new
node.name: node-1
node.master: true
node.data: true
bootstrap.memory_lock: true
network.host: 0.0.0.0
http.port: 9200
transport.host: 102.123.322.211
transport.tcp.port: 9300
discovery.seed_hosts: [“102.123.322.211:9300”,"102.123.322.212:9300”]
cluster.initial_master_nodes: 
        - "node-1"
        - "node-2”

Machine 2 config:-

cluster.name: cluster-new
node.name: node-2
node.master: true
node.data: true
bootstrap.memory_lock: true
network.host: 0.0.0.0
http.port: 9200
transport.host: 102.123.322.212
transport.tcp.port: 9300
discovery.seed_hosts: [“102.123.322.211:9300”,"102.123.322.212:9300”]
cluster.initial_master_nodes: 
        - "node-1"
        - "node-2”

cluster.name: This has be same across all the machines that are going to be part of a cluster.

node.name : Identifier for the ES instance. Defaults to machine name if not given.

node.master: specifies whether this ES instance is going to be master or not

node.data: specifies whether this ES instance is going to be data node or not(hold data)

bootsrap.memory_lock: disable swapping.You can start the cluster without setting this flag. But its recommended to set the lock.More info: https://www.elastic.co/guide/en/elasticsearch/reference/master/setup-configuration-memory.html

network.host: 0.0.0.0 if you want to expose the ES instance over network. 0.0.0.0 is different from 127.0.0.1( aka localhost or loopback address). It means all IPv4 addresses on the machine. If machine has multiple ip addresses with a server listening on 0.0.0.0, the client can reach the machine from any of the IPv4 addresses.

http.port: port on which this ES instance will listen to for HTTP requests

transport.host: The IPv4 address of the host(this will be used to communicate with other ES instances running on different machines). More info: https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-transport.html

transport.tcp.port: 9300 (the port where the machine will accept the tcp connections)

discovery.seed_hosts: This was changed in recent versions. Initialise all the IPv4 addresses with TCP port(important) of ES instances that are going to be part of this cluster. This is going to be same across all ES instances that are part of this cluster.

cluster.initial_master_nodes: node names(node.name) of the ES machines that are going to participate in master election.(Quorum based decision making :- https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-discovery-quorums.html#modules-discovery-quorums)

What is [Serializable] and when should I use it?

Here is short example of how serialization works. I was also learning about the same and I found two links useful. What Serialization is and how it can be done in .NET.

A sample program explaining serialization

If you don't understand the above program a much simple program with explanation is given here.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 23: ordinal not in range(128)

You are encoding to UTF-8, then re-encoding to UTF-8. Python can only do this if it first decodes again to Unicode, but it has to use the default ASCII codec:

>>> u'ñ'
u'\xf1'
>>> u'ñ'.encode('utf8')
'\xc3\xb1'
>>> u'ñ'.encode('utf8').encode('utf8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

Don't keep encoding; leave encoding to UTF-8 to the last possible moment instead. Concatenate Unicode values instead.

You can use str.join() (or, rather, unicode.join()) here to concatenate the three values with dashes in between:

nombre = u'-'.join(fabrica, sector, unidad)
return nombre.encode('utf-8')

but even encoding here might be too early.

Rule of thumb: decode the moment you receive the value (if not Unicode values supplied by an API already), encode only when you have to (if the destination API does not handle Unicode values directly).

How can a add a row to a data frame in R?

Or, as inspired by @MatheusAraujo:

df[nrow(df) + 1,] = list("v1","v2")

This would allow for mixed data types.

How to get a variable type in Typescript?

For :

abc:number|string;

Use the JavaScript operator typeof:

if (typeof abc === "number") {
    // do something
}

TypeScript understands typeof

This is called a typeguard.

More

For classes you would use instanceof e.g.

class Foo {}
class Bar {} 

// Later
if (fooOrBar instanceof Foo){
  // TypeScript now knows that `fooOrBar` is `Foo`
}

There are also other type guards e.g. in etc https://basarat.gitbooks.io/typescript/content/docs/types/typeGuard.html

pip installs packages successfully, but executables not found from command line

I know the question asks about macOS, but here is a solution for Linux users who arrive here via Google.

I was having the issue described in this question, having installed the pdfx package via pip.

When I ran it however, nothing...

pip list | grep pdfx
pdfx (1.3.0)

Yet:

which pdfx
pdfx not found

The problem on Linux is that pip install ... drops scripts into ~/.local/bin and this is not on the default Debian/Ubuntu $PATH.

Here's a GitHub issue going into more detail: https://github.com/pypa/pip/issues/3813

To fix, just add ~/.local/bin to your $PATH, for example by adding the following line to your .bashrc file:

export PATH="$HOME/.local/bin:$PATH"

After that, restart your shell and things should work as expected.

how to convert a string to date in mysql?

STR_TO_DATE('12/31/2011', '%m/%d/%Y')

Disable EditText blinking cursor

add android:focusableInTouchMode="true" in root layout, when edit text will be clicked at that time cursor will be shown.

ActionLink htmlAttributes

Replace the desired hyphen with an underscore; it will automatically be rendered as a hyphen:

@Html.ActionLink("Edit", "edit", "markets",
    new { id = 1 },
    new {@class="ui-btn-right", data_icon="gear"})

becomes:

<form action="markets/Edit/1" class="ui-btn-right" data-icon="gear" .../>

How to run two jQuery animations simultaneously?

yes there is!

$(function () {
    $("#first").animate({
       width: '200px'
    }, { duration: 200, queue: false });

    $("#second").animate({
       width: '600px'
    }, { duration: 200, queue: false });
});

How do you show animated GIFs on a Windows Form (c#)

It's not too hard.

  1. Drop a picturebox onto your form.
  2. Add the .gif file as the image in the picturebox
  3. Show the picturebox when you are loading.

Things to take into consideration:

  • Disabling the picturebox will prevent the gif from being animated.

Animated gifs:

If you are looking for animated gifs you can generate them:

AjaxLoad - Ajax Loading gif generator

Another way of doing it:

Another way that I have found that works quite well is the async dialog control that I found on the code project

Base64 encoding and decoding in client-side Javascript

Did someone say code golf? =)

The following is my attempt at improving my handicap while catching up with the times. Supplied for your convenience.

function decode_base64(s) {
  var b=l=0, r='',
  m='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  s.split('').forEach(function (v) {
    b=(b<<6)+m.indexOf(v); l+=6;
    if (l>=8) r+=String.fromCharCode((b>>>(l-=8))&0xff);
  });
  return r;
}

What I was actually after was an asynchronous implementation and to my surprise it turns out forEach as opposed to JQuery's $([]).each method implementation is very much synchronous.

If you also had such crazy notions in mind a 0 delay window.setTimeout will run the base64 decode asynchronously and execute the callback function with the result when done.

function decode_base64_async(s, cb) {
  setTimeout(function () { cb(decode_base64(s)); }, 0);
}

@Toothbrush suggested "index a string like an array", and get rid of the split. This routine seems really odd and not sure how compatible it will be, but it does hit another birdie so lets have it.

function decode_base64(s) {
  var b=l=0, r='',
  m='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  [].forEach.call(s, function (v) {
    b=(b<<6)+m.indexOf(v); l+=6;
    if (l>=8) r+=String.fromCharCode((b>>>(l-=8))&0xff);
  });
  return r;
}

While trying to find more information on JavaScript string as array I stumbled on this pro tip using a /./g regex to step through a string. This reduces the code size even more by replacing the string in place and eliminating the need of keeping a return variable.

function decode_base64(s) {
  var b=l=0,
  m='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  return s.replace(/./g, function (v) {
    b=(b<<6)+m.indexOf(v); l+=6;
    return l<8?'':String.fromCharCode((b>>>(l-=8))&0xff);
  });
}

If however you were looking for something a little more traditional perhaps the following is more to your taste.

function decode_base64(s) {
  var b=l=0, r='', s=s.split(''), i,
  m='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  for (i in s) {
    b=(b<<6)+m.indexOf(s[i]); l+=6;
    if (l>=8) r+=String.fromCharCode((b>>>(l-=8))&0xff);
  }
  return r;
}

I didn't have the trailing null issue so this was removed to remain under par but it should easily be resolved with a trim() or a trimRight() if you'd prefer, should this pose a problem for you.

ie.

return r.trimRight();

Note:

The result is an ascii byte string, if you need unicode the easiest is to escape the byte string which can then be decoded with decodeURIComponent to produce the unicode string.

function decode_base64_usc(s) {      
  return decodeURIComponent(escape(decode_base64(s)));
}

Since escape is being deprecated we could change our function to support unicode directly without the need for escape or String.fromCharCode we can produce a % escaped string ready for URI decoding.

function decode_base64(s) {
  var b=l=0,
  m='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  return decodeURIComponent(s.replace(/./g, function (v) {
    b=(b<<6)+m.indexOf(v); l+=6;
    return l<8?'':'%'+(0x100+((b>>>(l-=8))&0xff)).toString(16).slice(-2);
  }));
}

nJoy!

Java: Add elements to arraylist with FOR loop where element name has increasing number

Thomas's solution is good enough for this matter.

If you want to use loop to access these three Answers, you first need to put there three into an array-like data structure ---- kind of like a principle. So loop is used for operating on an array-like data structure, not just simply to simplify typing task. And you cannot use FOR loop by simply just giving increasing-number-names to the elements.

SQL: set existing column as Primary Key in MySQL

If you want to do it with phpmyadmin interface:

Select the table -> Go to structure tab -> On the row corresponding to the column you want, click on the icon with a key

How to search text using php if ($text contains "World")

This might be what you are looking for:

<?php

$text = 'This is a Simple text.';

// this echoes "is is a Simple text." because 'i' is matched first
echo strpbrk($text, 'mi');

// this echoes "Simple text." because chars are case sensitive
echo strpbrk($text, 'S');
?>

Is it?

Or maybe this:

<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'";
} else {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
}
?>

Or even this

<?php
$email  = '[email protected]';
$domain = strstr($email, '@');
echo $domain; // prints @example.com

$user = strstr($email, '@', true); // As of PHP 5.3.0
echo $user; // prints name
?>

You can read all about them in the documentation here:

http://php.net/manual/en/book.strings.php

How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS?

You'd have to test it but if you embedded an iframe within your page then used CSS to absolutely position the 1st row & column at 0,0 in the iframe page would that solve your problem?

What does "&" at the end of a linux command mean?

When not told otherwise commands take over the foreground. You only have one "foreground" process running in a single shell session. The & symbol instructs commands to run in a background process and immediately returns to the command line for additional commands.

sh my_script.sh &

A background process will not stay alive after the shell session is closed. SIGHUP terminates all running processes. By default anyway. If your command is long-running or runs indefinitely (ie: microservice) you need to pr-pend it with nohup so it remains running after you disconnect from the session:

nohup sh my_script.sh &

EDIT: There does appear to be a gray area regarding the closing of background processes when & is used. Just be aware that the shell may close your process depending on your OS and local configurations (particularly on CENTOS/RHEL): https://serverfault.com/a/117157.

DNS problem, nslookup works, ping doesn't

It's possible that the Windows internal resolver is adding '.local' to the domain name because there's no dots in it. nslookup wouldn't do that.

To verify this possiblity, install 'Wireshark' (previously aka Ethereal) on your client machine and observe any DNS request packets leaving it when you run the ping command.


OK, further investigation on my own XP machine at home reveals that for single label names (i.e. "foo", or "foo.") the system doesn't use DNS at all, and instead uses NBNS (NetBios Name Service).

Using a hint found at http://www.chicagotech.net/netforums/viewtopic.php?t=1476, I found that I was able to force DNS lookups for single label domains by putting a single entry reading "." in the "Append these DNS suffixes (in order)" in the "Advanced TCP/IP settings" dialog

Javascript: Fetch DELETE and PUT requests

Ok, here is a fetch DELETE example too:

fetch('https://example.com/delete-item/' + id, {
  method: 'DELETE',
})
.then(res => res.text()) // or res.json()
.then(res => console.log(res))

What is the simplest jQuery way to have a 'position:fixed' (always at top) div?

Beautiful! Your solution was 99%... instead of "this.scrollY", I used "$(window).scrollTop()". What's even better is that this solution only requires the jQuery1.2.6 library (no additional libraries needed).

The reason I wanted that version in particular is because that's what ships with MVC currently.

Here's the code:

$(document).ready(function() {
    $("#topBar").css("position", "absolute");
});

$(window).scroll(function() {
    $("#topBar").css("top", $(window).scrollTop() + "px");
});

How to create a Rectangle object in Java using g.fillRect method

Note:drawRect and fillRect are different.

Draws the outline of the specified rectangle:

public void drawRect(int x,
        int y,
        int width,
        int height)

Fills the specified rectangle. The rectangle is filled using the graphics context's current color:

public abstract void fillRect(int x,
        int y,
        int width,
        int height)

Getting DOM node from React child element

This may be possible by using the refs attribute.

In the example of wanting to to reach a <div> what you would want to do is use is <div ref="myExample">. Then you would be able to get that DOM node by using React.findDOMNode(this.refs.myExample).

From there getting the correct DOM node of each child may be as simple as mapping over this.refs.myExample.children(I haven't tested that yet) but you'll at least be able to grab any specific mounted child node by using the ref attribute.

Here's the official react documentation on refs for more info.

pytest cannot import module while python can

Install the packages into Your virtual environment.
Then start a new shell and source Your virtual environment again.

How do I remove carriage returns with Ruby?

def dos2unix(input)
  input.each_byte.map { |c| c.chr unless c == 13 }.join
end

remove_all_the_carriage_returns = dos2unix(some_blob)

Opening new window in HTML for target="_blank"

You can't influence neither type (tab/window) nor dimensions that way. You'll have to use JavaScript's window.open() for that.

Convert generic List/Enumerable to DataTable?

I also had to come up with an alternate solution, as none of the options listed here worked in my case. I was using an IEnumerable which returned an IEnumerable and the properties couldn't be enumerated. This did the trick:

// remove "this" if not on C# 3.0 / .NET 3.5
public static DataTable ConvertToDataTable<T>(this IEnumerable<T> data)
{
    List<IDataRecord> list = data.Cast<IDataRecord>().ToList();

    PropertyDescriptorCollection props = null;
    DataTable table = new DataTable();
    if (list != null && list.Count > 0)
    {
        props = TypeDescriptor.GetProperties(list[0]);
        for (int i = 0; i < props.Count; i++)
        {
            PropertyDescriptor prop = props[i];
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        }
    }
    if (props != null)
    {
        object[] values = new object[props.Count];
        foreach (T item in data)
        {
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = props[i].GetValue(item) ?? DBNull.Value;
            }
            table.Rows.Add(values);
        }
    }
    return table;
}

jQuery: Check if button is clicked

$('#btn1, #btn2').click(function() {
    let clickedButton = $(this).attr('id');
    console.log(clickedButton);
});

event Action<> vs event EventHandler<>

I realize that this question is over 10 years old, but it appears to me that not only has the most obvious answer not been addressed, but that maybe its not really clear from the question a good understanding of what goes on under the covers. In addition, there are other questions about late binding and what that means with regards to delegates and lambdas (more on that later).

First to address the 800 lb elephant/gorilla in the room, when to choose event vs Action<T>/Func<T>:

  • Use a lambda to execute one statement or method. Use event when you want more of a pub/sub model with multiple statements/lambdas/functions that will execute (this is a major difference right off the bat).
  • Use a lambda when you want to compile statements/functions to expression trees. Use delegates/events when you want to participate in more traditional late binding such as used in reflection and COM interop.

As an example of an event, lets wire up a simple and 'standard' set of events using a small console application as follows:

public delegate void FireEvent(int num);

public delegate void FireNiceEvent(object sender, SomeStandardArgs args);

public class SomeStandardArgs : EventArgs
{
    public SomeStandardArgs(string id)
    {
        ID = id;
    }

    public string ID { get; set; }
}

class Program
{
    public static event FireEvent OnFireEvent;

    public static event FireNiceEvent OnFireNiceEvent;


    static void Main(string[] args)
    {
        OnFireEvent += SomeSimpleEvent1;
        OnFireEvent += SomeSimpleEvent2;

        OnFireNiceEvent += SomeStandardEvent1;
        OnFireNiceEvent += SomeStandardEvent2;


        Console.WriteLine("Firing events.....");
        OnFireEvent?.Invoke(3);
        OnFireNiceEvent?.Invoke(null, new SomeStandardArgs("Fred"));

        //Console.WriteLine($"{HeightSensorTypes.Keyence_IL030}:{(int)HeightSensorTypes.Keyence_IL030}");
        Console.ReadLine();
    }

    private static void SomeSimpleEvent1(int num)
    {
        Console.WriteLine($"{nameof(SomeSimpleEvent1)}:{num}");
    }
    private static void SomeSimpleEvent2(int num)
    {
        Console.WriteLine($"{nameof(SomeSimpleEvent2)}:{num}");
    }

    private static void SomeStandardEvent1(object sender, SomeStandardArgs args)
    {

        Console.WriteLine($"{nameof(SomeStandardEvent1)}:{args.ID}");
    }
    private static void SomeStandardEvent2(object sender, SomeStandardArgs args)
    {
        Console.WriteLine($"{nameof(SomeStandardEvent2)}:{args.ID}");
    }
}

The output will look as follows:

enter image description here

If you did the same with Action<int> or Action<object, SomeStandardArgs>, you would only see SomeSimpleEvent2 and SomeStandardEvent2.

So whats going on inside of event?

If we expand out FireNiceEvent, the compiler is actually generating the following (I have omitted some details with respect to thread synchronization that isn't relevant to this discussion):

   private EventHandler<SomeStandardArgs> _OnFireNiceEvent;

    public void add_OnFireNiceEvent(EventHandler<SomeStandardArgs> handler)
    {
        Delegate.Combine(_OnFireNiceEvent, handler);
    }

    public void remove_OnFireNiceEvent(EventHandler<SomeStandardArgs> handler)
    {
        Delegate.Remove(_OnFireNiceEvent, handler);
    }

    public event EventHandler<SomeStandardArgs> OnFireNiceEvent
    {
        add
        {
            add_OnFireNiceEvent(value)
        }
        remove
        {
            remove_OnFireNiceEvent(value)

        }
    }

The compiler generates a private delegate variable which is not visible to the class namespace in which it is generated. That delegate is what is used for subscription management and late binding participation, and the public facing interface is the familiar += and -= operators we have all come to know and love : )

You can customize the code for the add/remove handlers by changing the scope of the FireNiceEvent delegate to protected. This now allows developers to add custom hooks to the hooks, such as logging or security hooks. This really makes for some very powerful features that now allows for customized accessibility to subscription based on user roles, etc. Can you do that with lambdas? (Actually you can by custom compiling expression trees, but that's beyond the scope of this response).

To address a couple of points from some of the responses here:

  • There really is no difference in the 'brittleness' between changing the args list in Action<T> and changing the properties in a class derived from EventArgs. Either will not only require a compile change, they will both change a public interface and will require versioning. No difference.

  • With respect to which is an industry standard, that depends on where this is being used and why. Action<T> and such is often used in IoC and DI, and event is often used in message routing such as GUI and MQ type frameworks. Note that I said often, not always.

  • Delegates have different lifetimes than lambdas. One also has to be aware of capture... not just with closure, but also with the notion of 'look what the cat dragged in'. This does affect memory footprint/lifetime as well as management a.k.a. leaks.

One more thing, something I referenced earlier... the notion of late binding. You will often see this when using framework like LINQ, regarding when a lambda becomes 'live'. That is very different than late binding of a delegate, which can happen more than once (i.e. the lambda is always there, but binding occurs on demand as often as is needed), as opposed to a lambda, which once it occurs, its done -- the magic is gone, and the method(s)/property(ies) will always bind. Something to keep in mind.

How to apply filters to *ngFor?

Basically, you write a pipe which you can then use in the *ngFor directive.

In your component:

filterargs = {title: 'hello'};
items = [{title: 'hello world'}, {title: 'hello kitty'}, {title: 'foo bar'}];

In your template, you can pass string, number or object to your pipe to use to filter on:

<li *ngFor="let item of items | myfilter:filterargs">

In your pipe:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'myfilter',
    pure: false
})
export class MyFilterPipe implements PipeTransform {
    transform(items: any[], filter: Object): any {
        if (!items || !filter) {
            return items;
        }
        // filter items array, items which match and return true will be
        // kept, false will be filtered out
        return items.filter(item => item.title.indexOf(filter.title) !== -1);
    }
}

Remember to register your pipe in app.module.ts; you no longer need to register the pipes in your @Component

import { MyFilterPipe } from './shared/pipes/my-filter.pipe';

@NgModule({
    imports: [
        ..
    ],
    declarations: [
        MyFilterPipe,
    ],
    providers: [
        ..
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

Here's a Plunker which demos the use of a custom filter pipe and the built-in slice pipe to limit results.

Please note (as several commentators have pointed out) that there is a reason why there are no built-in filter pipes in Angular.