Programs & Examples On #Haxe

Haxe is an open source, multiplatform programming language that allows developers to target JavaScript, NekoVM, Flash, C++, Java, C#, PHP, Python, Lua and HashLink using the same syntax.

2D cross-platform game engine for Android and iOS?

I find a nice and tidy Wave game engine few days ago. It uses C# and have Windows Phone and Windows Store converters as well which makes it a great replacement of XNA for me

Connect HTML page with SQL server using javascript

JavaScript is a client-side language and your MySQL database is going to be running on a server.

So you have to rename your file to index.php for example (.php is important) so you can use php code for that. It is not very difficult, but not directly possible with html.

(Somehow you can tell your server to let the html files behave like php files, but this is not the best solution.)

So after you renamed your file, go to the very top, before <html> or <!DOCTYPE html> and type:

<?php
    if($_SERVER['REQUEST_METHOD'] == 'POST') {
        /*Creating variables*/
        $name = $_POST["name"];
        $address = $_POST["address"];
        $age = $_POST["age"];


        $dbhost = "localhost"; /*most of the time it's localhost*/
        $username = "yourusername";
        $password = "yourpassword";
        $dbname = "mydatabase";

        $mysql = mysqli_connect($dbhost, $username, $password, $dbname); //It connects
        $query = "INSERT INTO yourtable (name,address,age) VALUES $name, $address, $age";
        mysqli_query($mysql, $query);
    }
?>
<!DOCTYPE html>
<html>
<head>.......
....
    <form method="post">
        <input name="name" type="text"/>
        <input name="address" type="text"/>
        <input name="age" type="text"/>
    </form>
....

How to fill DataTable with SQL Table

You need to modify the method GetData() and add your "experimental" code there, and return t1.

XPath selecting a node with some attribute value equals to some other node's attribute value

I think this is what you want:

/grand/parent/child[@id="#grand"]

What is the best IDE for C Development / Why use Emacs over an IDE?

How come nobody mentions Bloodshed Devc++? Havent used it in a while, but i learnt c/c++ on it. very similar to MS Visual c++.

How do I perform a GROUP BY on an aliased column in MS-SQL Server?

This is what I do.

SELECT FullName
FROM
(
  SELECT LastName + ', ' + FirstName AS FullName
  FROM customers
) as sub
GROUP BY FullName

This technique applies in a straightforward way to your "edit" scenario:

SELECT FullName
FROM
(
  SELECT
     CASE
       WHEN LastName IS NULL THEN FirstName
       WHEN LastName IS NOT NULL THEN LastName + ', ' + FirstName
     END AS FullName
  FROM customers
) as sub
GROUP BY FullName

What does the "+" (plus sign) CSS selector mean?

p+p{
//styling the code
}

p+p{
} simply mean find all the adjacent/sibling paragraphs with respect to first paragraph in DOM body.

    <div>
    <input type="text" placeholder="something">
    <p>This is first paragraph</p>
    <button>Button </button>
    <p> This is second paragraph</p>
    <p>This is third paragraph</p>
    </div>

    Styling part 
    <style type="text/css">
        p+p{
            color: red;
            font-weight: bolder;
        }
    </style>

   It will style all sibling paragraph with red color.

final output look like this

enter image description here

How to remove text before | character in notepad++

Please use regex to remove anything before |

example

dsfdf | fdfsfsf
dsdss|gfghhghg
dsdsds |dfdsfsds

Use find and replace in notepad++

find: .+(\|) replace: \1

output

| fdfsfsf
|gfghhghg
|dfdsfsds

Open fancybox from function

The answers seems a bit over complicated. I hope I didn't misunderstand the question.

If you simply want to open a fancy box from a click to an "A" tag. Just set your html to

<a id="my_fancybox" href="#contentdiv">click me</a>

The contents of your box will be inside of a div with id "contentdiv" and in your javascript you can initialize fancybox like this:

$('#my_fancybox').fancybox({
    'autoScale': true,
    'transitionIn': 'elastic',
    'transitionOut': 'elastic',
    'speedIn': 500,
    'speedOut': 300,
    'autoDimensions': true,
    'centerOnScroll': true,
});

This will show a fancybox containing "contentdiv" when your anchor tag is clicked.

Why is there still a row limit in Microsoft Excel?

In a word - speed. An index for up to a million rows fits in a 32-bit word, so it can be used efficiently on 32-bit processors. Function arguments that fit in a CPU register are extremely efficient, while ones that are larger require accessing memory on each function call, a far slower operation. Updating a spreadsheet can be an intensive operation involving many cell references, so speed is important. Besides, the Excel team expects that anyone dealing with more than a million rows will be using a database rather than a spreadsheet.

jQueryUI modal dialog does not show close button (x)

I had the same issue just add this function to the open dialog options and it worked sharm

open: function(){
            var closeBtn = $('.ui-dialog-titlebar-close');
            closeBtn.append('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span>');
        },

and on close event you need to remove that

close: function () {
            var closeBtn = $('.ui-dialog-titlebar-close');
            closeBtn.html('');}

Complete example

<div id="deleteDialog" title="Confirm Delete">
 Can you confirm you want to delete this event?
</div> 

$("#deleteDialog").dialog({
                width: 400, height: 200,
                modal: true,
                open: function () {
                    var closeBtn = $('.ui-dialog-titlebar-close');
                    closeBtn.append('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span>');
                },
                close: function () {
                    var closeBtn = $('.ui-dialog-titlebar-close');
                    closeBtn.html('');
                },
                buttons: {
                    "Confirm": function () {
                        calendar.fullCalendar('removeEvents', event._id);
                        $(this).dialog("close");
                    },
                    "Cancel": function () {
                        $(this).dialog("close");
                    }
                }
            });

            $("#dialog").dialog("open");

Freeze the top row for an html table only (Fixed Table Header Scrolling)

My concern was not to have the cells with fixed width. Which seemed to be not working in any case. I found this solution which seems to be what I need. I am posting it here for others who are searching of a way. Check out this fiddle

Working Snippet:

_x000D_
_x000D_
html, body{_x000D_
  margin:0;_x000D_
  padding:0;_x000D_
  height:100%;_x000D_
}_x000D_
section {_x000D_
  position: relative;_x000D_
  border: 1px solid #000;_x000D_
  padding-top: 37px;_x000D_
  background: #500;_x000D_
}_x000D_
section.positioned {_x000D_
  position: absolute;_x000D_
  top:100px;_x000D_
  left:100px;_x000D_
  width:800px;_x000D_
  box-shadow: 0 0 15px #333;_x000D_
}_x000D_
.container {_x000D_
  overflow-y: auto;_x000D_
  height: 160px;_x000D_
}_x000D_
table {_x000D_
  border-spacing: 0;_x000D_
  width:100%;_x000D_
}_x000D_
td + td {_x000D_
  border-left:1px solid #eee;_x000D_
}_x000D_
td, th {_x000D_
  border-bottom:1px solid #eee;_x000D_
  background: #ddd;_x000D_
  color: #000;_x000D_
  padding: 10px 25px;_x000D_
}_x000D_
th {_x000D_
  height: 0;_x000D_
  line-height: 0;_x000D_
  padding-top: 0;_x000D_
  padding-bottom: 0;_x000D_
  color: transparent;_x000D_
  border: none;_x000D_
  white-space: nowrap;_x000D_
}_x000D_
th div{_x000D_
  position: absolute;_x000D_
  background: transparent;_x000D_
  color: #fff;_x000D_
  padding: 9px 25px;_x000D_
  top: 0;_x000D_
  margin-left: -25px;_x000D_
  line-height: normal;_x000D_
  border-left: 1px solid #800;_x000D_
}_x000D_
th:first-child div{_x000D_
  border: none;_x000D_
}
_x000D_
<section class="">_x000D_
  <div class="container">_x000D_
    <table>_x000D_
      <thead>_x000D_
        <tr class="header">_x000D_
          <th>_x000D_
            Table attribute name_x000D_
            <div>Table attribute name</div>_x000D_
          </th>_x000D_
          <th>_x000D_
            Value_x000D_
            <div>Value</div>_x000D_
          </th>_x000D_
          <th>_x000D_
            Description_x000D_
            <div>Description</div>_x000D_
          </th>_x000D_
        </tr>_x000D_
      </thead>_x000D_
      <tbody>_x000D_
        <tr>_x000D_
          <td>align</td>_x000D_
          <td>left, center, right</td>_x000D_
          <td>Not supported in HTML5. Deprecated in HTML 4.01. Specifies the alignment of a table according to surrounding text</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>bgcolor</td>_x000D_
          <td>rgb(x,x,x), #xxxxxx, colorname</td>_x000D_
          <td>Not supported in HTML5. Deprecated in HTML 4.01. Specifies the background color for a table</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>border</td>_x000D_
          <td>1,""</td>_x000D_
          <td>Specifies whether the table cells should have borders or not</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>cellpadding</td>_x000D_
          <td>pixels</td>_x000D_
          <td>Not supported in HTML5. Specifies the space between the cell wall and the cell content</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>cellspacing</td>_x000D_
          <td>pixels</td>_x000D_
          <td>Not supported in HTML5. Specifies the space between cells</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>frame</td>_x000D_
          <td>void, above, below, hsides, lhs, rhs, vsides, box, border</td>_x000D_
          <td>Not supported in HTML5. Specifies which parts of the outside borders that should be visible</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>rules</td>_x000D_
          <td>none, groups, rows, cols, all</td>_x000D_
          <td>Not supported in HTML5. Specifies which parts of the inside borders that should be visible</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>summary</td>_x000D_
          <td>text</td>_x000D_
          <td>Not supported in HTML5. Specifies a summary of the content of a table</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>width</td>_x000D_
          <td>pixels, %</td>_x000D_
          <td>Not supported in HTML5. Specifies the width of a table</td>_x000D_
        </tr>_x000D_
      </tbody>_x000D_
    </table>_x000D_
  </div>_x000D_
</section>
_x000D_
_x000D_
_x000D_

Angular 4 - Observable catch error

With angular 6 and rxjs 6 Observable.throw(), Observable.off() has been deprecated instead you need to use throwError

ex :

return this.http.get('yoururl')
  .pipe(
    map(response => response.json()),
    catchError((e: any) =>{
      //do your processing here
      return throwError(e);
    }),
  );

What would be the best method to code heading/title for <ul> or <ol>, Like we have <caption> in <table>?

Always use heading tags for headings. The clue is in the name :)

If you don’t want them to be bold, change their style with CSS. For example:

HTML:

<h3 class="list-heading">heading</h3>

<ul> 
    <li>list item </li>
    <li>list item </li>
    <li>list item </li>
</ul>

CSS

.list-heading {
    font-weight: normal;
}

In HTML5, you can associate the heading and the list more clearly by using the <section> element. (<section> doesn’t work properly in IE 8 and earlier without some JavaScript though.)

<section>
    <h1>heading</h1>

    <ul>
        <li>list item </li>
        <li>list item </li>
        <li>list item </li>
    </ul>
</section>

You could do something similar in HTML 4:

<div class="list-with-heading">
    <h3>Heading</h3>

    <ul>
        <li>list item </li>
        <li>list item </li>
        <li>list item </li>
    </ul>
</div>

Then style thus:

.list-with-heading h3 {
    font-weight: normal;
}

How to while loop until the end of a file in Python without checking for empty line?

Don't loop through a file this way. Instead use a for loop.

for line in f:
    vowel += sum(ch.isvowel() for ch in line)

In fact your whole program is just:

VOWELS = {'A','E','I','O','U','a','e','i','o','u'}
# I'm assuming this is what isvowel checks, unless you're doing something
# fancy to check if 'y' is a vowel
with open('filename.txt') as f:
    vowel = sum(ch in VOWELS for line in f for ch in line.strip())

That said, if you really want to keep using a while loop for some misguided reason:

while True:
    line = f.readline().strip()
    if line == '':
        # either end of file or just a blank line.....
        # we'll assume EOF, because we don't have a choice with the while loop!
        break

Shell script to get the process ID on Linux

If you already know the process then this will be useful:

PID=`ps -eaf | grep <process> | grep -v grep | awk '{print $2}'`
if [[ "" !=  "$PID" ]]; then
echo "killing $PID"
kill -9 $PID
fi

How can I specify the required Node.js version in package.json?

There's another, simpler way to do this:

  1. npm install Node@8 (saves Node 8 as dependency in package.json)
  2. Your app will run using Node 8 for anyone - even Yarn users!

This works because node is just a package that ships node as its package binary. It just includes as node_module/.bin which means it only makes node available to package scripts. Not main shell.

See discussion on Twitter here: https://twitter.com/housecor/status/962347301456015360

Indentation shortcuts in Visual Studio

Just hit Tab to push it over or on the menu bar Edit --> Advanced --> Format Selection and that will auto indent, the keyboard shortcut is also shown in the menu.

Can I have multiple primary keys in a single table?

Having two primary keys at the same time, is not possible. But (assuming that you have not messed the case up with composite key), may be what you might need is to make one attribute unique.

CREATE t1(
c1 int NOT NULL,
c2 int NOT NULL UNIQUE,
...,
PRIMARY KEY (c1)
);

However note that in relational database a 'super key' is a subset of attributes which uniquely identify a tuple or row in a table. A 'key' is a 'super key' that has an additional property that removing any attribute from the key, makes that key no more a 'super key'(or simply a 'key' is a minimal super key). If there are more keys, all of them are candidate keys. We select one of the candidate keys as a primary key. That's why talking about multiple primary keys for a one relation or table is being a conflict.

How to get Enum Value from index in Java?

I recently had the same problem and used the solution provided by Harry Joy. That solution only works with with zero-based enumaration though. I also wouldn't consider it save as it doesn't deal with indexes that are out of range.

The solution I ended up using might not be as simple but it's completely save and won't hurt the performance of your code even with big enums:

public enum Example {

    UNKNOWN(0, "unknown"), ENUM1(1, "enum1"), ENUM2(2, "enum2"), ENUM3(3, "enum3");

    private static HashMap<Integer, Example> enumById = new HashMap<>();
    static {
        Arrays.stream(values()).forEach(e -> enumById.put(e.getId(), e));
    }

    public static Example getById(int id) {
        return enumById.getOrDefault(id, UNKNOWN);
    }

    private int id;
    private String description;

    private Example(int id, String description) {
        this.id = id;
        this.description= description;
    }

    public String getDescription() {
        return description;
    }

    public int getId() {
        return id;
    }
}

If you are sure that you will never be out of range with your index and you don't want to use UNKNOWN like I did above you can of course also do:

public static Example getById(int id) {
        return enumById.get(id);
}

Search for a string in Enum and return the Enum

var color =  Enum.Parse<Colors>("Green");

SQL Server: Get data for only the past year

For some reason none of the results above worked for me.

This selects the last 365 days.

 SELECT ... From ... WHERE date BETWEEN CURDATE() - INTERVAL 1 YEAR AND CURDATE()

adb not finding my device / phone (MacOS X)

I had a similar issue. I've discovered that MTP is not supported in OSX. I changed it to PTP, I was promoted to approve my laptop and then my device was finally listed (LG G3).

enter image description here

Appending to an empty DataFrame in Pandas?

And if you want to add a row, you can use a dictionary:

df = pd.DataFrame()
df = df.append({'name': 'Zed', 'age': 9, 'height': 2}, ignore_index=True)

which gives you:

   age  height name
0    9       2  Zed

regular expression to match exactly 5 digits

No need to care of whether before/after this digit having other type of words

To just match the pattern of 5 digits number anywhere in the string, no matter it is separated by space or not, use this regular expression (?<!\d)\d{5}(?!\d).

Sample JavaScript codes:

var regexp = new RegExp(/(?<!\d)\d{5}(?!\d)/g); 
    var matches = yourstring.match(regexp);
    if (matches && matches.length > 0) {
        for (var i = 0, len = matches.length; i < len; i++) {
            // ... ydo something with matches[i] ...
        } 
    }

Here's some quick results.

  • abc12345xyz (?)

  • 12345abcd (?)

  • abcd12345 (?)

  • 0000aaaa2 (?)

  • a1234a5 (?)

  • 12345 (?)

  • <space>12345<space>12345 (??)

Merging arrays with the same keys

Try with array_merge_recursive

$A = array('a' => 1, 'b' => 2, 'c' => 3);
$B = array('c' => 4, 'd'=> 5);
$c = array_merge_recursive($A,$B);

echo "<pre>";
print_r($c);
echo "</pre>";

will return

Array
(
    [a] => 1
    [b] => 2
    [c] => Array
        (
            [0] => 3
            [1] => 4
        )

    [d] => 5
)

Lowercase and Uppercase with jQuery

I think you want to lowercase the checked value? Try:

var jIsHasKids = $('#chkIsHasKids:checked').val().toLowerCase();

or you want to check it, then get its value as lowercase:

var jIsHasKids = $('#chkIsHasKids').attr("checked", true).val().toLowerCase();

"Fade" borders in CSS

Add this class css to your style sheet

.border_gradient {
border: 8px solid #000;
-moz-border-bottom-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
-moz-border-top-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
-moz-border-left-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
-moz-border-right-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
padding: 5px 5px 5px 15px;
width: 300px;
}

set width to the width of your image. and use this html for image

<div class="border_gradient">
        <img src="image.png" />
</div>

though it may not give the same exact border, it will some gradient looks on the border.

source: CSS3 Borders

Listing only directories in UNIX

This has been working for me:

`ls -F | grep /`

(But, I am switching to echo */ as mentioned by @nos)

ng: command not found while creating new project using angular-cli

Maximum time, this is a path issue conflict between npm and angular cli.

The solution that worked for me ->

  1. %USERPROFILE%\AppData\Roaming Paste this in File Explorer and delete npm folder.
  2. npm install -g @angular/cli@latest run this command to reinstall latest angular cli.
  3. npm link @angular/cli now this command can solve your path issue

Literally that three steps will fix your issue, otherwise you need to update environment variable by search and open Edit the system environment variables

Ariful Ahsan https://arifulahsan.com

How to convert string to boolean php

Strings always evaluate to boolean true unless they have a value that's considered "empty" by PHP (taken from the documentation for empty):

  1. "" (an empty string);
  2. "0" (0 as a string)

If you need to set a boolean based on the text value of a string, then you'll need to check for the presence or otherwise of that value.

$test_mode_mail = $string === 'true'? true: false;

EDIT: the above code is intended for clarity of understanding. In actual use the following code may be more appropriate:

$test_mode_mail = ($string === 'true');

or maybe use of the filter_var function may cover more boolean values:

filter_var($string, FILTER_VALIDATE_BOOLEAN);

filter_var covers a whole range of values, including the truthy values "true", "1", "yes" and "on". See here for more details.

Why does only the first line of this Windows batch file execute but all three lines execute in a command shell?

Maven uses batch files to do its business. With any batch script, you must call another script using the call command so it knows to return back to your script after the called script completes. Try prepending call to all commands.

Another thing you could try is using the start command which should work similarly.

Open JQuery Datepicker by clicking on an image w/ no input field

HTML:

<div class="CalendarBlock">
    <input type="hidden">
</div>

CODE:

$CalendarBlock=$('.CalendarBlock');
$CalendarBlock.click(function(){
    var $datepicker=$(this).find('input');
    datepicker.datepicker({dateFormat: 'mm/dd/yy'});
    $datepicker.focus(); });

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

I have this issue also, running on an iOS 8 device. It is detailed some more here and seems to be a case of iOS trying to use connections that have already timed out. My issue isn't the same as the Keep-Alive problem explained in that link, however it seems to be the same end result.

I have corrected my problem by running a recursive block whenever I receive an error -1005 and this makes the connection eventually get through even though sometimes the recursion can loop for 100+ times before the connection works, however it only adds a mere second onto run times and I bet that is just the time it takes the debugger to print the NSLog's for me.

Here's how I run a recursive block with AFNetworking: Add this code to your connection class file

// From Mike Ash's recursive block fixed-point-combinator strategy https://gist.github.com/1254684
dispatch_block_t recursiveBlockVehicle(void (^block)(dispatch_block_t recurse))
{
    // assuming ARC, so no explicit copy
    return ^{ block(recursiveBlockVehicle(block)); };
}
typedef void (^OneParameterBlock)(id parameter);
OneParameterBlock recursiveOneParameterBlockVehicle(void (^block)(OneParameterBlock recurse, id parameter))
{
    return ^(id parameter){ block(recursiveOneParameterBlockVehicle(block), parameter); };
}

Then use it likes this:

+ (void)runOperationWithURLPath:(NSString *)urlPath
            andStringDataToSend:(NSString *)stringData
                    withTimeOut:(NSString *)timeOut
     completionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    OneParameterBlock run = recursiveOneParameterBlockVehicle(^(OneParameterBlock recurse, id parameter) {
        // Put the request operation here that you want to keep trying
        NSNumber *offset = parameter;
        NSLog(@"--------------- Attempt number: %@ ---------------", offset);

        MyAFHTTPRequestOperation *operation =
            [[MyAFHTTPRequestOperation alloc] initWithURLPath:urlPath
            andStringDataToSend:stringData
            withTimeOut:timeOut];

        [operation setCompletionBlockWithSuccess:
            ^(AFHTTPRequestOperation *operation, id responseObject) {
                success(operation, responseObject);
            }
            failure:^(AFHTTPRequestOperation *operation2, NSError *error) {
                if (error.code == -1005) {
                    if (offset.intValue >= numberOfRetryAttempts) {
                        // Tried too many times, so fail
                        NSLog(@"Error during connection: %@",error.description);
                        failure(operation2, error);
                    } else {
                        // Failed because of an iOS bug using timed out connections, so try again
                        recurse(@(offset.intValue+1));
                    }
                } else {
                    NSLog(@"Error during connection: %@",error.description);
                    failure(operation2, error);
                }
            }];
        [[NSOperationQueue mainQueue] addOperation:operation];
    });
    run(@0);
}

You'll see that I use a AFHTTPRequestOperation subclass but add your own request code. The important part is calling recurse(@offset.intValue+1)); to make the block be called again.

Dynamically add item to jQuery Select2 control that uses AJAX

To get dynamic tagging to work with ajax, here's what I did.

Select2 version 3.5

This is easy in version 3.5 because it offers the createSearchChoice hook. It even works for multiple select, as long as multiple: true and tags: true are set.

HTML

<input type="hidden" name="locations" value="Whistler, BC" />

JS

$('input[name="locations"]').select2({
  tags: true,
  multiple: true,
  createSearchChoice: function(term, data) {
    if (!data.length)
      return { id: term, text: term };
    },
  ajax: {
    url: '/api/v1.1/locations',
    dataType: 'json'
  }
});

The idea here is to use select2's createSearchChoice hook which passes you both the term that the user entered and the ajax response (as data). If ajax returns an empty list, then tell select2 to offer the user-entered term as an option.

Demo: https://johnny.netlify.com/select2-examples/version3


Select2 version 4.X

Version 4.X doesn't have a createSearchChoice hook anymore, but here's how I did the same thing.

HTML

  <select name="locations" multiple>
    <option value="Whistler, BC" selected>Whistler, BC</option>
  </select>

JS

$('select[name="locations"]').select2({
  ajax: {
    url: '/api/v1.1/locations',
    dataType: 'json',
    data: function(params) {
      this.data('term', params.term);
      return params;
    },
    processResults: function(data) {
      if (data.length)
        return {
          results: data
        };
      else
        return {
          results: [{ id: this.$element.data('term'), text: this.$element.data('term') }]
        };
    }
  }
});

The ideas is to stash the term that the user typed into jQuery's data store inside select2's data hook. Then in select2's processResults hook, I check if the ajax response is empty. If it is, I grab the stashed term that the user typed and return it as an option to select2.

Demo: https://johnny.netlify.com/select2-examples/version4

Trying to get PyCharm to work, keep getting "No Python interpreter selected"

I got the same issue when i newly installed pycharm in my windows 10 machine.

  • download python setup

  • install this solved my problem.

for more help visit goodluck

During the install of python make sure you have "Install for all users" selected. Uninstall python and do a custom install and check "Install for all users"

How do we use runOnUiThread in Android?

This is how I use it:

runOnUiThread(new Runnable() {
                @Override
                public void run() {
                //Do something on UiThread
            }
        });

How do I post button value to PHP?

Change the type to submit and give it a name (and remove the useless onclick and flat out the 90's style uppercased tags/attributes).

<input type="submit" name="foo" value="A" />
<input type="submit" name="foo" value="B" />
...

The value will be available by $_POST['foo'] (if the parent <form> has a method="post").

When and Why to use abstract classes/methods?

At a very high level:

Abstraction of any kind comes down to separating concerns. "Client" code of an abstraction doesn't care how the contract exposed by the abstraction is fulfilled. You usually don't care if a string class uses a null-terminated or buffer-length-tracked internal storage implementation, for example. Encapsulation hides the details, but by making classes/methods/etc. abstract, you allow the implementation to change or for new implementations to be added without affecting the client code.

Redirecting Output from within Batch file

The simple naive way that is slow because it opens and positions the file pointer to End-Of-File multiple times.

@echo off
command1 >output.txt
command2 >>output.txt
...
commandN >>output.txt

A better way - easier to write, and faster because the file is opened and positioned only once.

@echo off
>output.txt (
  command1
  command2
  ...
  commandN
)

Another good and fast way that only opens and positions the file once

@echo off
call :sub >output.txt
exit /b

:sub
command1
command2
...
commandN

Edit 2020-04-17

Every now and then you may want to repeatedly write to two or more files. You might also want different messages on the screen. It is still possible to to do this efficiently by redirecting to undefined handles outside a parenthesized block or subroutine, and then use the & notation to reference the already opened files.

call :sub 9>File1.txt 8>File2.txt
exit /b

:sub
echo Screen message 1
>&9 File 1 message 1
>&8 File 2 message 1
echo Screen message 2
>&9 File 1 message 2
>&8 File 2 message 2
exit /b

I chose to use handles 9 and 8 in reverse order because that way is more likely to avoid potential permanent redirection due to a Microsoft redirection implementation design flaw when performing multiple redirections on the same command. It is highly unlikely, but even that approach could expose the bug if you try hard enough. If you stage the redirection than you are guaranteed to avoid the problem.

3>File1.txt ( 4>File2.txt call :sub)
exit /b

:sub
etc.

PHP - warning - Undefined property: stdClass - fix?

If you want to use property_exists, you'll need to get the name of the class with get_class()

In this case it would be :

 if( property_exists( get_class($response), 'records' ) ){
       $role_arr = getRole($response->records);
 }
 else
 {
       ...
 }

Can Android Studio be used to run standard Java projects?

EDIT: many moon after this question was asked, yes, now apparently you can.

No, but it's based on Intellij IDEA.

The community version of that is free for download but it doesn't support most things requiring an external database or application server. The line for Java is pretty much that JavaSE code can happily use Community.

If you want that (or are using JavaEE) then you either need the Ultimate version, which isn't free, or the EAP of the next version which is usually good for a month until they release another.

Basically it works like this

Android Studio is just Android the Android Stuff from IDEA 13 Community...

...which will be free, and is anything from IDEA 13 Ultimate...

...that doesn't require a database or app server.

http://www.jetbrains.com/idea/

IDEA 12 Community doesn't have the ability to import the gradilized project and it won't, so while you can do Android development in it now (I do), don't expect it to have the same features as Android Studio. There's a lot of good new Android stuff in it, that's going into 13.

What is meant by immutable?

As the accepted answer doesn't answer all the questions. I'm forced to give an answer after 11 years and 6 months.

Can somebody clarify what is meant by immutable?

Hope you meant immutable object (because we could think about immutable reference).

An object is immutable: iff once created, they always represent the same value (doesn't have any method that change the value).

Why is a String immutable?

Respect the above definition which could be checked by looking into the Sting.java source code.

What are the advantages/disadvantages of the immutable objects? immutable types are :

  • safer from bugs.

  • easier to understand.

  • and more ready for change.

Why should a mutable object such as StringBuilder be preferred over String and vice-verse?

Narrowing the question Why do we need the mutable StringBuilder in programming? A common use for it is to concatenate a large number of strings together, like this:

String s = "";
for (int i = 0; i < n; ++i) {
    s = s + n;
}

Using immutable strings, this makes a lot of temporary copies — the first number of the string ("0") is actually copied n times in the course of building up the final string, the second number is copied n-1 times, and so on. It actually costs O(n2) time just to do all that copying, even though we only concatenated n elements.

StringBuilder is designed to minimize this copying. It uses a simple but clever internal data structure to avoid doing any copying at all until the very end, when you ask for the final String with a toString() call:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; ++i) {
  sb.append(String.valueOf(n));
}
String s = sb.toString();

Getting good performance is one reason why we use mutable objects. Another is convenient sharing: two parts of your program can communicate more conveniently by sharing a common mutable data structure.

More could be found here : https://web.mit.edu/6.005/www/fa15/classes/09-immutability/#useful_immutable_types

tsc is not recognized as internal or external command

For me, by running Visual Studio Code as Administrator, the problem is resolved.

How to prevent a click on a '#' link from jumping to top of page?

Adding something after # sets the focus of page to the element with that ID. Simplest solution is to use #/ even if you are using jQuery. However if you are handling the event in jQuery, event.preventDefault() is the way to go.

How can I detect browser type using jQuery?

You shouldn't write your own browser-detection code - it's been done many times before. Use Modernizr to detect independent browser features instead. It's better to detect the various features than to detect entire browsers because various browsers may support different set of features and those features may even change through various versions of the same browser. If you detect the presence of a given feature, your code will likely work better in more browsers. This is especially true for the various mobile browsers.

When you run Modernizr, it'll update your HEAD element's class attribute so that it lists the various features of the browser that you're using - you can then use Javascript to query the attribute and decide what to do if a feature is present (or missing).

BeautifulSoup Grab Visible Webpage Text

Using BeautifulSoup the easiest way with less code to just get the strings, without empty lines and crap.

tag = <Parent_Tag_that_contains_the_data>
soup = BeautifulSoup(tag, 'html.parser')

for i in soup.stripped_strings:
    print repr(i)

Why can't I use Docker CMD multiple times to run multiple services?

While I respect the answer from qkrijger explaining how you can work around this issue I think there is a lot more we can learn about what's going on here ...

To actually answer your question of "why" ... I think it would for helpful for you to understand how the docker stop command works and that all processes should be shutdown cleanly to prevent problems when you try to restart them (file corruption etc).

Problem: What if docker did start SSH from it's command and started RabbitMQ from your Docker file? "The docker stop command attempts to stop a running container first by sending a SIGTERM signal to the root process (PID 1) in the container." Which process is docker tracking as PID 1 that will get the SIGTERM? Will it be SSH or Rabbit?? "According to the Unix process model, the init process -- PID 1 -- inherits all orphaned child processes and must reap them. Most Docker containers do not have an init process that does this correctly, and as a result their containers become filled with zombie processes over time."

Answer: Docker simply takes that last CMD as the one that will get launched as the root process with PID 1 and get the SIGTERM from docker stop.

Suggested solution: You should use (or create) a base image specifically made for running more than one service, such as phusion/baseimage

It should be important to note that tini exists exactly for this reason, and as of Docker 1.13 and up, tini is officially part of Docker, which tells us that running more than one process in Docker IS VALID .. so even if someone claims to be more skilled regarding Docker, and insists that you absurd for thinking of doing this, know that you are not. There are perfectly valid situations for doing so.

Good to know:

jQuery Validate - Enable validation for hidden fields

The plugin's author says you should use "square brackets without the quotes", []

http://bassistance.de/2011/10/07/release-validation-plugin-1-9-0/

Release: Validation Plugin 1.9.0: "...Another change should make the setup of forms with hidden elements easier, these are now ignored by default (option “ignore” has “:hidden” now as default). In theory, this could break an existing setup. In the unlikely case that it actually does, you can fix it by setting the ignore-option to “[]” (square brackets without the quotes)."

To change this setting for all forms:

$.validator.setDefaults({ 
    ignore: [],
    // any other default options and/or rules
});

(It is not required that .setDefaults() be within the document.ready function)

OR for one specific form:

$(document).ready(function() {

    $('#myform').validate({
        ignore: [],
        // any other options and/or rules
    });

});

EDIT:

See this answer for how to enable validation on some hidden fields but still ignore others.


EDIT 2:

Before leaving comments that "this does not work", keep in mind that the OP is simply asking about the jQuery Validate plugin and his question has nothing to do with how ASP.NET, MVC, or any other Microsoft framework can alter this plugin's normal expected behavior. If you're using a Microsoft framework, the default functioning of the jQuery Validate plugin is over-written by Microsoft's unobtrusive-validation plugin.

If you're struggling with the unobtrusive-validation plugin, then please refer to this answer instead: https://stackoverflow.com/a/11053251/594235

String vs. StringBuilder

StringBuilder is probably preferable. The reason is that it allocates more space than currently needed (you set the number of characters) to leave room for future appends. Then those future appends that fit in the current buffer don't require any memory allocation or garbage collection, which can be expensive. In general, I use StringBuilder for complex string concatentation or multiple formatting, then convert to a normal String when the data is complete, and I want an immutable object again.

onSaveInstanceState () and onRestoreInstanceState ()

The main thing is that if you don't store in onSaveInstanceState() then onRestoreInstanceState() will not be called. This is the main difference between restoreInstanceState() and onCreate(). Make sure you really store something. Most likely this is your problem.

Tesseract OCR simple example

Here's a great working example project; Tesseract OCR Sample (Visual Studio) with Leptonica Preprocessing Tesseract OCR Sample (Visual Studio) with Leptonica Preprocessing

Tesseract OCR 3.02.02 API can be confusing, so this guides you through including the Tesseract and Leptonica dll into a Visual Studio C++ Project, and provides a sample file which takes an image path to preprocess and OCR. The preprocessing script in Leptonica converts the input image into black and white book-like text.

Setup

To include this in your own projects, you will need to reference the header files and lib and copy the tessdata folders and dlls.

Copy the tesseract-include folder to the root folder of your project. Now Click on your project in Visual Studio Solution Explorer, and go to Project>Properties.

VC++ Directories>Include Directories:

..\tesseract-include\tesseract;..\tesseract-include\leptonica;$(IncludePath) C/C++>Preprocessor>Preprocessor Definitions:

_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) C/C++>Linker>Input>Additional Dependencies:

..\tesseract-include\libtesseract302.lib;..\tesseract-include\liblept168.lib;%(AdditionalDependencies) Now you can include headers in your project's file:

include

include

Now copy the two dll files in tesseract-include and the tessdata folder in Debug to the Output Directory of your project.

When you initialize tesseract, you need to specify the location of the parent folder (!important) of the tessdata folder if it is not already the current directory of your executable file. You can copy my script, which assumes tessdata is installed in the executable's folder.

tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI(); api->Init("D:\tessdataParentFolder\", ... Sample

You can compile the provided sample, which takes one command line argument of the image path to use. The preprocess() function uses Leptonica to create a black and white book-like copy of the image which makes tesseract work with 90% accuracy. The ocr() function shows the functionality of the Tesseract API to return a string output. The toClipboard() can be used to save text to clipboard on Windows. You can copy these into your own projects.

LINQ query to select top five

var list = (from t in ctn.Items
           where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
           orderby t.Delivery.SubmissionDate
           select t).Take(5);

Convert NSData to String?

Objective-C

You can use (see NSString Class Reference)

- (id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding

Example:

NSString *myString = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];

Remark: Please notice the NSData value must be valid for the encoding specified (UTF-8 in the example above), otherwise nil will be returned:

Returns nil if the initialization fails for some reason (for example if data does not represent valid data for encoding).

Prior Swift 3.0

String(data: yourData, encoding: NSUTF8StringEncoding)

Swift 3.0 Onwards

String(data: yourData, encoding: .utf8)

See String#init(data:encoding:) Reference

What data type to use in MySQL to store images?

What you need, according to your comments, is a 'BLOB' (Binary Large OBject) for both image and resume.

How can I convert a DOM element to a jQuery element?

So far best solution that I've made:

function convertHtmlToJQueryObject(html){
    var htmlDOMObject = new DOMParser().parseFromString(html, "text/html");
    return $(htmlDOMObject.documentElement);
}

Is there a way to cache GitHub credentials for pushing commits?

You can use credential helpers.

git config --global credential.helper 'cache --timeout=x'

where x is the number of seconds.

How get value from URL

You can get that value by using the $_GET array. So the id value would be stored in $_GET['id'].

So in your case you could store that value in the $id variable as follows:

$id = $_GET['id'];

How to convert CSV to JSON in Node.js

I have a very simple solution to just print json from csv on console using csvtojson module.

// require csvtojson
var csv = require("csvtojson");

const csvFilePath='customer-data.csv' //file path of csv
csv()
.fromFile(csvFilePath)``
.then((jsonObj)=>{
    console.log(jsonObj);
})

Multiple maven repositories in one gradle file

you have to do like this in your project level gradle file

allprojects {
    repositories {
        jcenter()
        maven { url "http://dl.appnext.com/" }
        maven { url "https://maven.google.com" }
    }
}

python object() takes no parameters error

You've mixed tabs and spaces. __init__ is actually defined nested inside another method, so your class doesn't have its own __init__ method, and it inherits object.__init__ instead. Open your code in Notepad instead of whatever editor you're using, and you'll see your code as Python's tab-handling rules see it.

This is why you should never mix tabs and spaces. Stick to one or the other. Spaces are recommended.

PHP remove all characters before specific string

You can use strstr to do this.

echo strstr($str, 'www/audio');

Merge two json/javascript arrays in to one array

Upon first appearance, the word "merg" leads one to think you need to use .extend, which is the proper jQuery way to "merge" JSON objects. However, $.extend(true, {}, json1, json2); will cause all values sharing the same key name to be overridden by the latest supplied in the params. As review of your question shows, this is undesired.

What you seek is a simple javascript function known as .concat. Which would work like:

var finalObj = json1.concat(json2);

While this is not a native jQuery function, you could easily add it to the jQuery library for simple future use as follows:

;(function($) {
    if (!$.concat) {
        $.extend({
            concat: function() {
                return Array.prototype.concat.apply([], arguments);
            }
        });
    }
})(jQuery);

And then recall it as desired like:

var finalObj = $.concat(json1, json2);

You can also use it for multiple array objects of this type with a like:

var finalObj = $.concat(json1, json2, json3, json4, json5, ....);

And if you really want it jQuery style and very short and sweet (aka minified)

;(function(a){a.concat||a.extend({concat:function(){return Array.prototype.concat.apply([],arguments);}})})(jQuery);

_x000D_
_x000D_
;(function($){$.concat||$.extend({concat:function(){return Array.prototype.concat.apply([],arguments);}})})(jQuery);_x000D_
_x000D_
$(function() {_x000D_
    var json1 = [{id:1, name: 'xxx'}],_x000D_
        json2 = [{id:2, name: 'xyz'}],_x000D_
        json3 = [{id:3, name: 'xyy'}],_x000D_
        json4 = [{id:4, name: 'xzy'}],_x000D_
        json5 = [{id:5, name: 'zxy'}];_x000D_
    _x000D_
    console.log(Array(10).join('-')+'(json1, json2, json3)'+Array(10).join('-'));_x000D_
    console.log($.concat(json1, json2, json3));_x000D_
    console.log(Array(10).join('-')+'(json1, json2, json3, json4, json5)'+Array(10).join('-'));_x000D_
    console.log($.concat(json1, json2, json3, json4, json5));_x000D_
    console.log(Array(10).join('-')+'(json4, json1, json2, json5)'+Array(10).join('-'));_x000D_
    console.log($.concat(json4, json1, json2, json5));_x000D_
});
_x000D_
center { padding: 3em; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<center>See Console Log</center>
_x000D_
_x000D_
_x000D_

jsFiddle

how to modify an existing check constraint?

No. If such a feature existed it would be listed in this syntax illustration. (Although it's possible there is an undocumented SQL feature, or maybe there is some package that I'm not aware of.)

How to find index of an object by key and value in an javascript array

Not a direct answer to your question, though I thing it's worth mentioning it, because your question seems like fitting in the general case of "getting things by name in a key-value storage".

If you are not tight to the way "peoples" is implemented, a more JavaScript-ish way of getting the right guy might be :

var peoples = {
  "bob":  { "dinner": "pizza" },
  "john": { "dinner": "sushi" },
  "larry" { "dinner": "hummus" }
};

// If people is implemented this way, then
// you can get values from their name, like :
var theGuy = peoples["john"];

// You can event get directly to the values
var thatGuysPrefferedDinner = peoples["john"].dinner;

Hope if this is not the answer you wanted, it might help people interested in that "key/value" question.

C# Equivalent of SQL Server DataTypes

SQL Server and .Net Data Type mapping

SQL Server and .Net Data Type mapping

How can I access and process nested objects, arrays or JSON?

// const path = 'info.value[0].item'
// const obj = { info: { value: [ { item: 'it works!' } ], randominfo: 3 }  }
// getValue(path, obj)

export const getValue = ( path , obj) => {
  const newPath = path.replace(/\]/g, "")
  const arrayPath = newPath.split(/[\[\.]+/) || newPath;

  const final = arrayPath.reduce( (obj, k) => obj ?  obj[k] : obj, obj)
  return final;
}

How to convert a python numpy array to an RGB image with Opencv 2.4?

You are looking for scipy.misc.toimage:

import scipy.misc
rgb = scipy.misc.toimage(np_array)

It seems to be also in scipy 1.0, but has a deprecation warning. Instead, you can use pillow and PIL.Image.fromarray

What is the difference between ( for... in ) and ( for... of ) statements?

Here is a useful mnemonic for remembering the difference between for...in Loop and for...of Loop.

"index in, object of"

for...in Loop => iterates over the index in the array.

for...of Loop => iterates over the object of objects.

jQuery, get ID of each element in a class using .each?

patrick dw's answer is right on.

For kicks and giggles I thought I would post a simple way to return an array of all the IDs.

var arrayOfIds = $.map($(".myClassName"), function(n, i){
  return n.id;
});
alert(arrayOfIds);

What's the difference between display:inline-flex and display:flex?

OK, I know at first might be a bit confusing, but display is talking about the parent element, so means when we say: display: flex;, it's about the element and when we say display:inline-flex;, is also making the element itself inline...

It's like make a div inline or block, run the snippet below and you can see how display flex breaks down to next line:

_x000D_
_x000D_
.inline-flex {_x000D_
  display: inline-flex;_x000D_
}_x000D_
_x000D_
.flex {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
p {_x000D_
  color: red;_x000D_
}
_x000D_
<body>_x000D_
  <p>Display Inline Flex</p>_x000D_
  <div class="inline-flex">_x000D_
    <header>header</header>_x000D_
    <nav>nav</nav>_x000D_
    <aside>aside</aside>_x000D_
    <main>main</main>_x000D_
    <footer>footer</footer>_x000D_
  </div>_x000D_
_x000D_
  <div class="inline-flex">_x000D_
    <header>header</header>_x000D_
    <nav>nav</nav>_x000D_
    <aside>aside</aside>_x000D_
    <main>main</main>_x000D_
    <footer>footer</footer>_x000D_
  </div>_x000D_
_x000D_
  <p>Display Flex</p>_x000D_
  <div class="flex">_x000D_
    <header>header</header>_x000D_
    <nav>nav</nav>_x000D_
    <aside>aside</aside>_x000D_
    <main>main</main>_x000D_
    <footer>footer</footer>_x000D_
  </div>_x000D_
_x000D_
  <div class="flex">_x000D_
    <header>header</header>_x000D_
    <nav>nav</nav>_x000D_
    <aside>aside</aside>_x000D_
    <main>main</main>_x000D_
    <footer>footer</footer>_x000D_
  </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Also quickly create the image below to show the difference at a glance:

display flex vs display inline-flex

Convert integers to strings to create output filenames at run time

Here is my subroutine approach to this problem. it transforms an integer in the range 0 : 9999 as a character. For example, the INTEGER 123 is transformed into the character 0123. hope it helps.

P.S. - sorry for the comments; they make sense in Romanian :P

 subroutine nume_fisier (i,filename_tot)

   implicit none
   integer :: i

   integer :: integer_zeci,rest_zeci,integer_sute,rest_sute,integer_mii,rest_mii
   character(1) :: filename1,filename2,filename3,filename4
   character(4) :: filename_tot

! Subrutina ce transforma un INTEGER de la 0 la 9999 in o serie de CARACTERE cu acelasi numar

! pentru a fi folosite in numerotarea si denumirea fisierelor de rezultate.

 if(i<=9) then

  filename1=char(48+0)
  filename2=char(48+0)
  filename3=char(48+0)
  filename4=char(48+i)  

 elseif(i>=10.and.i<=99) then

  integer_zeci=int(i/10)
  rest_zeci=mod(i,10)
  filename1=char(48+0)
  filename2=char(48+0)
  filename3=char(48+integer_zeci)
  filename4=char(48+rest_zeci)

 elseif(i>=100.and.i<=999) then

  integer_sute=int(i/100)
  rest_sute=mod(i,100)
  integer_zeci=int(rest_sute/10)
  rest_zeci=mod(rest_sute,10)
  filename1=char(48+0)
  filename2=char(48+integer_sute)
  filename3=char(48+integer_zeci)
  filename4=char(48+rest_zeci)

 elseif(i>=1000.and.i<=9999) then

  integer_mii=int(i/1000)
  rest_mii=mod(i,1000)
  integer_sute=int(rest_mii/100)
  rest_sute=mod(rest_mii,100)
  integer_zeci=int(rest_sute/10)
  rest_zeci=mod(rest_sute,10)
  filename1=char(48+integer_mii)
  filename2=char(48+integer_sute)
  filename3=char(48+integer_zeci) 
  filename4=char(48+rest_zeci)

 endif

 filename_tot=''//filename1//''//filename2//''//filename3//''//filename4//''
 return
 end subroutine nume_fisier

when I run mockito test occurs WrongTypeOfReturnValue Exception

TL;DR If some arguments in your test are null, be sure to mock the parameter call with isNull() instead of anyXXX().


I got this error when upgrading from Spring boot 1.5.x to 2.1.x. Spring boot ships with its own Mockito, which is now also upgraded to 2.x (see e.g. Dependencies of Spring boot 2.1.2)

Mockito has changed the behavior for the anyXXX() method, where XXX is String, Long, etc. Here is the javadoc of anyLong():

Since Mockito 2.1.0, only allow valued Long, thus null is not anymore a valid value As primitive wrappers are nullable, the suggested API to match null wrapper would be #isNull(). We felt this change would make tests harness much safer that it was with Mockito 1.x.

I'd suggest you debug to the point where your mock is about to be called and inspect, whether at least one argument is null. In that case make sure, that you prepare your mock with isNull() instead of e.g. anyLong().

So this:

when(MockedClass.method(anyString());

becomes:

when(MockedClass.method(isNull());

How to properly highlight selected item on RecyclerView?

Look on my solution. I suppose that you should set selected position in holder and pass it as Tag of View. The view should be set in the onCreateViewHolder(...) method. There is also correct place to set listener for view such as OnClickListener or LongClickListener.

Please look on the example below and read comments to code.

public class MyListAdapter extends RecyclerView.Adapter<MyListAdapter.ViewHolder> {
    //Here is current selection position
    private int mSelectedPosition = 0;
    private OnMyListItemClick mOnMainMenuClickListener = OnMyListItemClick.NULL;

    ...

    // constructor, method which allow to set list yourObjectList

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //here you prepare your view 
        // inflate it
        // set listener for it
        final ViewHolder result = new ViewHolder(view);
        final View view =  LayoutInflater.from(parent.getContext()).inflate(R.layout.your_view_layout, parent, false);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //here you set your current position from holder of clicked view
                mSelectedPosition = result.getAdapterPosition();

                //here you pass object from your list - item value which you clicked
                mOnMainMenuClickListener.onMyListItemClick(yourObjectList.get(mSelectedPosition));

                //here you inform view that something was change - view will be invalidated
                notifyDataSetChanged();
            }
        });
        return result;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        final YourObject yourObject = yourObjectList.get(position);

        holder.bind(yourObject);
        if(mSelectedPosition == position)
            holder.itemView.setBackgroundColor(Color.CYAN);
        else
            holder.itemView.setBackgroundColor(Color.RED);
    }

    // you can create your own listener which you set for adapter
    public void setOnMainMenuClickListener(OnMyListItemClick onMyListItemClick) {
        mOnMainMenuClickListener = onMyListItemClick == null ? OnMyListItemClick.NULL : onMyListItemClick;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {


        ViewHolder(View view) {
            super(view);
        }

        private void bind(YourObject object){
            //bind view with yourObject
        }
    }

    public interface OnMyListItemClick {
        OnMyListItemClick NULL = new OnMyListItemClick() {
            @Override
            public void onMyListItemClick(YourObject item) {

            }
        };

        void onMyListItemClick(YourObject item);
    }
}

What's the difference between ASCII and Unicode?

ASCII defines 128 characters, which map to the numbers 0–127. Unicode defines (less than) 221 characters, which, similarly, map to numbers 0–221 (though not all numbers are currently assigned, and some are reserved).

Unicode is a superset of ASCII, and the numbers 0–127 have the same meaning in ASCII as they have in Unicode. For example, the number 65 means "Latin capital 'A'".

Because Unicode characters don't generally fit into one 8-bit byte, there are numerous ways of storing Unicode characters in byte sequences, such as UTF-32 and UTF-8.

Multiple aggregations of the same column using pandas GroupBy.agg()

Would something like this work:

In [7]: df.groupby('dummy').returns.agg({'func1' : lambda x: x.sum(), 'func2' : lambda x: x.prod()})
Out[7]: 
              func2     func1
dummy                        
1     -4.263768e-16 -0.188565

Add newly created specific folder to .gitignore in Git

It's /public_html/stats/*.

$ ~/myrepo> ls public_html/stats/
bar baz foo
$ ~/myrepo> cat .gitignore 
public_html/stats/*
$ ~/myrepo> git status
# On branch master
#
# Initial commit
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#   .gitignore
nothing added to commit but untracked files present (use "git add" to track)
$ ~/myrepo>

In TensorFlow, what is the difference between Session.run() and Tensor.eval()?

If you have a Tensor t, calling t.eval() is equivalent to calling tf.get_default_session().run(t).

You can make a session the default as follows:

t = tf.constant(42.0)
sess = tf.Session()
with sess.as_default():   # or `with sess:` to close on exit
    assert sess is tf.get_default_session()
    assert t.eval() == sess.run(t)

The most important difference is that you can use sess.run() to fetch the values of many tensors in the same step:

t = tf.constant(42.0)
u = tf.constant(37.0)
tu = tf.mul(t, u)
ut = tf.mul(u, t)
with sess.as_default():
   tu.eval()  # runs one step
   ut.eval()  # runs one step
   sess.run([tu, ut])  # evaluates both tensors in a single step

Note that each call to eval and run will execute the whole graph from scratch. To cache the result of a computation, assign it to a tf.Variable.

How to resize image automatically on browser width resize but keep same height?

I've used Perfect Full Page Background Image to accomplish this on a previous site.

You can use background-size: cover; if you only need to support modern browsers.

SQL - Query to get server's IP address

It's in the @@SERVERNAME variable;

SELECT @@SERVERNAME;

copy db file with adb pull results in 'permission denied' error

I had the same problem. My work around is to use adb shell and su. Next, copy the file to /sdcard/Download

Then, I can use adb pull to get the file.

How can I quickly sum all numbers in a file?

It is not easier to replace all new lines by +, add a 0 and send it to the Ruby interpreter?

(sed -e "s/$/+/" file; echo 0)|irb

If you do not have irb, you can send it to bc, but you have to remove all newlines except the last one (of echo). It is better to use tr for this, unless you have a PhD in sed .

(sed -e "s/$/+/" file|tr -d "\n"; echo 0)|bc

How to use curl to get a GET request exactly same as using Chrome?

Open Chrome Developer Tools, go to Network tab, make your request (you may need to check "Preserve Log" if the page refreshes). Find the request on the left, right-click, "Copy as cURL".

HTTP status code for update and delete?

Since the question delves into if DELETE "should" return 200 vs 204 it is worth considering that some people recommend returning an entity with links so the preference is for 200.

"Instead of returning 204 (No Content), the API should be helpful and suggest places to go. In this example I think one obvious link to provide is to" 'somewhere.com/container/' (minus 'resource') "- the container from which the client just deleted a resource. Perhaps the client wishes to delete more resources, so that would be a helpful link."

http://blog.ploeh.dk/2013/04/30/rest-lesson-learned-avoid-204-responses/

If a client encounters a 204 response, it can either give up, go to the entry point of the API, or go back to the previous resource it visited. Neither option is particularly good.

Personally I would not say 204 is wrong (neither does the author; he says "annoying") because good caching at the client side has many benefits. Best is to be consistent either way.

Is Fortran easier to optimize than C for heavy calculations?

It is funny that a lot of answers here from not knowing the languages. This is especially true for C/C++ programmers who have opened and old FORTRAN 77 code and discuss the weaknesses.

I suppose that the speed issue is mostly a question between C/C++ and Fortran. In a Huge code, it always depends on the programmer. There are some features of the language that Fortran outperforms and some features which C does. So, in 2011, no one can really say which one is faster.

About the language itself, Fortran nowadays supports Full OOP features and it is fully backward compatible. I have used the Fortran 2003 thoroughly and I would say it was just delightful to use it. In some aspects, Fortran 2003 is still behind C++ but let's look at the usage. Fortran is mostly used for Numerical Computation, and nobody uses fancy C++ OOP features because of speed reasons. In high performance computing, C++ has almost no place to go(have a look at the MPI standard and you'll see that C++ has been deprecated!).

Nowadays, you can simply do mixed language programming with Fortran and C/C++. There are even interfaces for GTK+ in Fortran. There are free compilers (gfortran, g95) and many excellent commercial ones.

Make the current commit the only (initial) commit in a Git repository?

The only solution that works for me (and keeps submodules working) is

git checkout --orphan newBranch
git add -A  # Add all files and commit them
git commit
git branch -D master  # Deletes the master branch
git branch -m master  # Rename the current branch to master
git push -f origin master  # Force push master branch to github
git gc --aggressive --prune=all     # remove the old files

Deleting .git/ always causes huge issues when I have submodules. Using git rebase --root would somehow cause conflicts for me (and take long since I had a lot of history).

Multiple simultaneous downloads using Wget?

wget cant download in multiple connections, instead you can try to user other program like aria2.

npm install vs. update - what's the difference?

npm update: install and update with latest node modules which are in package.json

npm install: install node modules which are defined in package.json(without update)

JAVA_HOME and PATH are set but java -version still shows the old one

In Linux Mint 18 Cinnamon be sure to check /etc/profile.d/jdk_home.sh I renamed this file to jdk_home.sh.old and now my path does not keep getting overridden and I can call java -version and see Java 9 as expected. Even though I correctly selected Java 9 in update-aternatives --config java this jdk_home.sh file kept overriding the $PATH on boot-up.

Resize background image in div using css

With the background-size property in those browsers which support this very new feature of CSS.

Convert array values from string to int?

If you have a multi-dimensional array, none of the previously mentioned solutions will work. Here is my solution:

public function arrayValuesToInt(&$array){
  if(is_array($array)){
    foreach($array as &$arrayPiece){
      arrayValuesToInt($arrayPiece);
    }
  }else{
    $array = intval($array);
  }
}

Then, just do this:

arrayValuesToInt($multiDimentionalArray);

This will make an array like this:

[["1","2"]["3","4"]]

look like this:

[[1,2][3,4]]

This will work with any level of depth.

Alternatively, you can use array_walk_recursive() for a shorter answer:

array_walk_recursive($array, function(&$value){
    $value = intval($value);
});

Python "SyntaxError: Non-ASCII character '\xe2' in file"

When I have a similar issue when reading text files i use...

f = open('file','rt', errors='ignore')

Download/Stream file from URL - asp.net

You could try using the DirectoryEntry class with the IIS path prefix:

using(DirectoryEntry de = new DirectoryEntry("IIS://Localhost/w3svc/1/root" + DOCUMENT_PATH))
{
    filePath = de.Properties["Path"].Value;
}

if (!File.Exists(filePath))
        return;

var fileInfo = new System.IO.FileInfo(filePath);
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", String.Format("attachment;filename=\"{0}\"", filePath));
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.WriteFile(filePath);
Response.End();

How do I cancel a build that is in progress in Visual Studio?

If all else fails go to task manager and kill the msbuild task under Visual Studio 2017

Clicking submit button of an HTML form by a Javascript code

The usual way to submit a form in general is to call submit() on the form itself, as described in krtek's answer.

However, if you need to actually click a submit button for some reason (your code depends on the submit button's name/value being posted or something), you can click on the submit button itself like this:

document.getElementById('loginSubmit').click();

How do I get java logging output to appear on a single line?

Like Obediah Stane said, it's necessary to create your own format method. But I would change a few things:

  • Create a subclass directly derived from Formatter, not from SimpleFormatter. The SimpleFormatter has nothing to add anymore.

  • Be careful with creating a new Date object! You should make sure to represent the date of the LogRecord. When creating a new Date with the default constructor, it will represent the date and time the Formatter processes the LogRecord, not the date that the LogRecord was created.

The following class can be used as formatter in a Handler, which in turn can be added to the Logger. Note that it ignores all class and method information available in the LogRecord.

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

public final class LogFormatter extends Formatter {

    private static final String LINE_SEPARATOR = System.getProperty("line.separator");

    @Override
    public String format(LogRecord record) {
        StringBuilder sb = new StringBuilder();

        sb.append(new Date(record.getMillis()))
            .append(" ")
            .append(record.getLevel().getLocalizedName())
            .append(": ")
            .append(formatMessage(record))
            .append(LINE_SEPARATOR);

        if (record.getThrown() != null) {
            try {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                record.getThrown().printStackTrace(pw);
                pw.close();
                sb.append(sw.toString());
            } catch (Exception ex) {
                // ignore
            }
        }

        return sb.toString();
    }
}

Android adding simple animations while setvisibility(view.Gone)

Try adding this line to the xml parent layout

 android:animateLayoutChanges="true"

Your layout will look like this

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:animateLayoutChanges="true"
    android:longClickable="false"
    android:orientation="vertical"
    android:weightSum="16">

    .......other code here

    </LinearLayout>

"Thinking in AngularJS" if I have a jQuery background?

Listen to the podcast JavaScript Jabber: Episode #32 that features the original creators of AngularJS: Misko Hevery & Igor Minar. They talk a lot about what it's like to come to AngularJS from other JavaScript backgrounds, especially jQuery.

One of the points made in the podcast made a lot of things click for me with respects to your question:

MISKO: [...] one of the things we thought about very hardly in Angular is, how do we provide lots of escape hatches so that you can get out and basically figure out a way out of this. So to us, the answer is this thing called “Directives”. And with directives, you essentially become a regular little jQuery JavaScript, you can do whatever you want.

IGOR: So think of directive as the instruction to the compiler that tells it whenever you come across this certain element or this CSS in the template, and you keep this kind of code and that code is in charge of the element and everything below that element in the DOM tree.

A transcript of the entire episode is available at the link provided above.

So, to directly answer your question: AngularJS is -very- opinionated and is a true MV* framework. However, you can still do all of the really cool stuff you know and love with jQuery inside of directives. It's not a matter of "How do I do what I used to in jQuery?" as much as it's a matter of "How do I supplement AngularJS with all of the stuff I used to do in jQuery?"

It's really two very different states of mind.

Java: Simplest way to get last word in a string

If other whitespace characters are possible, then you'd want:

testString.split("\\s+");

Bold & Non-Bold Text In A Single UILabel?

It worked for me:

CGFloat boldTextFontSize = 17.0f;

myLabel.text = [NSString stringWithFormat:@"%@ 2012/10/14 %@",@"Updated:",@"21:59 PM"];

NSRange range1 = [myLabel.text rangeOfString:@"Updated:"];
NSRange range2 = [myLabel.text rangeOfString:@"21:59 PM"];

NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:myLabel.text];

[attributedText setAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:boldTextFontSize]}
                        range:range1];
[attributedText setAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:boldTextFontSize]}
                        range:range2];

myLabel.attributedText = attributedText;

For Swift version: See Here

Convert string to Date in java

You are wrong in the way you display the data I guess, because for me:

    String dateString = "03/26/2012 11:49:00 AM";
    SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
    Date convertedDate = new Date();
    try {
        convertedDate = dateFormat.parse(dateString);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println(convertedDate);

Prints:

Mon Mar 26 11:49:00 EEST 2012

If Else If In a Sql Server Function

ALTER FUNCTION [dbo].[fnTally] (@SchoolId nvarchar(50))
    RETURNS nvarchar(3)
AS BEGIN 

    DECLARE @Final nvarchar(3)
    SELECT @Final = CASE 
        WHEN yes_ans > no_ans  AND yes_ans > na_ans THEN 'Yes'
        WHEN no_ans  > yes_ans AND no_ans  > na_ans THEN 'No'
        WHEN na_ans  > yes_ans AND na_ans  > no_ans THEN 'N/A' END
    FROM dbo.qrc_maintally
    WHERE school_id = @SchoolId

Return @Final
End

As you can see, this simplifies the code a lot. It also makes other errors in your code more obvious: you're returning an nvarchar, but declared the function to return an int (corrected in the code above).

How to catch a unique constraint error in a PL/SQL block?

I'm sure you have your reasons, but just in case... you should also consider using a "merge" query instead:

begin
    merge into some_table st
    using (select 'some' name, 'values' value from dual) v
    on (st.name=v.name)
    when matched then update set st.value=v.value
    when not matched then insert (name, value) values (v.name, v.value);
end;

(modified the above to be in the begin/end block; obviously you can run it independantly of the procedure too).

How to save S3 object to a file using boto3

If you wish to download a version of a file, you need to use get_object.

import boto3

bucket = 'bucketName'
prefix = 'path/to/file/'
filename = 'fileName.ext'

s3c = boto3.client('s3')
s3r = boto3.resource('s3')

if __name__ == '__main__':
    for version in s3r.Bucket(bucket).object_versions.filter(Prefix=prefix + filename):
        file = version.get()
        version_id = file.get('VersionId')
        obj = s3c.get_object(
            Bucket=bucket,
            Key=prefix + filename,
            VersionId=version_id,
        )
        with open(f"{filename}.{version_id}", 'wb') as f:
            for chunk in obj['Body'].iter_chunks(chunk_size=4096):
                f.write(chunk)

Ref: https://botocore.amazonaws.com/v1/documentation/api/latest/reference/response.html

How do I find what Java version Tomcat6 is using?

If tomcat did not start up yet , you can use the command \bin\cataline version to check which JVM will the tomcat use when you start tomcat using bin\startup

In fact ,\bin\cataline version just call the main class of org.apache.catalina.util.ServerInfo , which is located inside the \lib\catalina.jar . The org.apache.catalina.util.ServerInfo gets the JVM Version and JVM Vendor by the following commands:

System.out.println("JVM Version: " +System.getProperty("java.runtime.version"));
System.out.println("JVM Vendor: " +System.getProperty("java.vm.vendor")); 

So , if the tomcat is running , you can create a JSP page that call org.apache.catalina.util.ServerInfo or just simply call the above System.getProperty() to get the JVM Version and Vendor . Deploy this JSP to the running tomcat instance and browse to it to see the result.

Alternatively, you should know which port is the running tomcat instance using . So , you can use the OS command to find which process is listening to this port. For example in the window , you can use the command netstat -aon to find out the process ID of a process that is listening to a particular port . Then go to the window task manager to check the full file path of this process ID belongs to. .The java version can then be determined from that file path.

Selecting multiple classes with jQuery

This should work:

$('.myClass, .myOtherClass').removeClass('theclass');

You must add the multiple selectors all in the first argument to $(), otherwise you are giving jQuery a context in which to search, which is not what you want.

It's the same as you would do in CSS.

Convert 24 Hour time to 12 Hour plus AM/PM indication Oracle SQL

For the 24-hour time, you need to use HH24 instead of HH.

For the 12-hour time, the AM/PM indicator is written as A.M. (if you want periods in the result) or AM (if you don't). For example:

SELECT invoice_date,
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
  FROM invoices
;

For more information on the format models you can use with TO_CHAR on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.

How to read/write arbitrary bits in C/C++

int x = 0xFF;   //your number - 11111111

How do I for example read a 3 bit integer value starting at the second bit

int y = x & ( 0x7 << 2 ) // 0x7 is 111
                         // and you shift it 2 to the left

Number of lines in a file in Java

/**
 * Count file rows.
 *
 * @param file file
 * @return file row count
 * @throws IOException
 */
public static long getLineCount(File file) throws IOException {

    try (Stream<String> lines = Files.lines(file.toPath())) {
        return lines.count();
    }
}

Tested on JDK8_u31. But indeed performance is slow compared to this method:

/**
 * Count file rows.
 *
 * @param file file
 * @return file row count
 * @throws IOException
 */
public static long getLineCount(File file) throws IOException {

    try (BufferedInputStream is = new BufferedInputStream(new FileInputStream(file), 1024)) {

        byte[] c = new byte[1024];
        boolean empty = true,
                lastEmpty = false;
        long count = 0;
        int read;
        while ((read = is.read(c)) != -1) {
            for (int i = 0; i < read; i++) {
                if (c[i] == '\n') {
                    count++;
                    lastEmpty = true;
                } else if (lastEmpty) {
                    lastEmpty = false;
                }
            }
            empty = false;
        }

        if (!empty) {
            if (count == 0) {
                count = 1;
            } else if (!lastEmpty) {
                count++;
            }
        }

        return count;
    }
}

Tested and very fast.

How do I calculate percentiles with python/numpy?

Here's how to do it without numpy, using only python to calculate the percentile.

import math

def percentile(data, percentile):
    size = len(data)
    return sorted(data)[int(math.ceil((size * percentile) / 100)) - 1]

p5 = percentile(mylist, 5)
p25 = percentile(mylist, 25)
p50 = percentile(mylist, 50)
p75 = percentile(mylist, 75)
p95 = percentile(mylist, 95)

How do I access my SSH public key?

Open your id_dsa.pub or some_name.pub file with gedit and copy-paste the contents!

Just use:

~/.ssh$ gedit some_name.pub

What's the reason I can't create generic array types in Java?

The main reason is due to the fact that arrays in Java are covariant.

There's a good overview here.

Is there a C# String.Format() equivalent in JavaScript?

Try sprintf() for javascript.

Or

// First, checks if it isn't implemented yet.
if (!String.prototype.format) {
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
        ? args[number]
        : match
      ;
    });
  };
}

"{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET")

Both answers pulled from JavaScript equivalent to printf/string.format

Fetch frame count with ffmpeg

Cmd ->

ffprobe.exe -v error -select_streams v:0 -show_entries stream=r_frame_rate,duration -of default=nw=1 "d:\movies\The.Matrix.1999.1080p.BrRip.x264.YIFY.dut.mp4"

Result ->

r_frame_rate=24000/1001
duration=8177.794625

Calculation ->

Frames=24000/1001*8177.794625=196071

Proof -> 

ffmpeg -i "d:\movies\The.Matrix.1999.1080p.BrRip.x264.YIFY.dut.mp4" -f null /dev/null
ffmpeg version N-92938-g0aaaca25e0-ffmpeg-windows-pacman Copyright (c) 2000-2019 the FFmpeg developers
  built with gcc 8.2.0 (GCC)
  configuration: --pkg-config=pkg-config --pkg-config-flags=--static --extra-version=ffmpeg-windows-pacman --enable-version3 --disable-debug --disable-w32threads --arch=x86_64 --target-os=mingw32 --cross-prefix=/opt/sandbox/cross_compilers/mingw-w64-x86_64/bin/x86_64-w64-mingw32- --enable-libcaca --enable-gray --enable-libtesseract --enable-fontconfig --enable-gmp --enable-gnutls --enable-libass --enable-libbluray --enable-libbs2b --enable-libflite --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libilbc --enable-libmodplug --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopus --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libtheora --enable-libtwolame --enable-libvo-amrwbenc --enable-libvorbis --enable-libvpx --enable-libwebp --enable-libzimg --enable-libzvbi --enable-libmysofa --enable-libaom --enable-libopenjpeg --enable-libopenh264 --enable-liblensfun --enable-nvenc --enable-nvdec --extra-libs=-lm --extra-libs=-lpthread --extra-cflags=-DLIBTWOLAME_STATIC --extra-cflags=-DMODPLUG_STATIC --extra-cflags=-DCACA_STATIC --enable-amf --enable-libmfx --enable-gpl --enable-avisynth --enable-frei0r --enable-filter=frei0r --enable-librubberband --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxvid --enable-libxavs --enable-avresample --extra-cflags='-march=core2' --extra-cflags=-O2 --enable-static --disable-shared --prefix=/opt/sandbox/cross_compilers/mingw-w64-x86_64/x86_64-w64-mingw32 --enable-nonfree --enable-decklink --enable-libfdk-aac
  libavutil      56. 25.100 / 56. 25.100
  libavcodec     58. 43.100 / 58. 43.100
  libavformat    58. 25.100 / 58. 25.100
  libavdevice    58.  6.101 / 58.  6.101
  libavfilter     7. 47.100 /  7. 47.100
  libavresample   4.  0.  0 /  4.  0.  0
  libswscale      5.  4.100 /  5.  4.100
  libswresample   3.  4.100 /  3.  4.100
  libpostproc    55.  4.100 / 55.  4.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'd:\movies\The.Matrix.1999.1080p.BrRip.x264.YIFY.dut.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf58.25.100
  Duration: 02:16:17.91, start: 0.000000, bitrate: 2497 kb/s
    Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1920x800 [SAR 1:1 DAR 12:5], 2397 kb/s, 23.98 fps, 23.98 tbr, 24k tbn, 47.95 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 93 kb/s (default)
    Metadata:
      handler_name    : GPAC ISO Audio Handler
Stream mapping:
  Stream #0:0 -> #0:0 (h264 (native) -> wrapped_avframe (native))
  Stream #0:1 -> #0:1 (aac (native) -> pcm_s16le (native))
Press [q] to stop, [?] for help
Output #0, null, to '/dev/null':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf58.25.100
    Stream #0:0(und): Video: wrapped_avframe, yuv420p, 1920x800 [SAR 1:1 DAR 12:5], q=2-31, 200 kb/s, 23.98 fps, 23.98 tbn, 23.98 tbc (default)
    Metadata:
      handler_name    : VideoHandler
      encoder         : Lavc58.43.100 wrapped_avframe
    Stream #0:1(und): Audio: pcm_s16le, 44100 Hz, stereo, s16, 1411 kb/s (default)
    Metadata:
      handler_name    : GPAC ISO Audio Handler
      encoder         : Lavc58.43.100 pcm_s16le
frame=196071 fps=331 q=-0.0 Lsize=N/A time=02:16:17.90 bitrate=N/A speed=13.8x
video:102631kB audio:1408772kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: unknown

Loop through a comma-separated shell variable

You can use the following script to dynamically traverse through your variable, no matter how many fields it has as long as it is only comma separated.

variable=abc,def,ghij
for i in $(echo $variable | sed "s/,/ /g")
do
    # call your procedure/other scripts here below
    echo "$i"
done

Instead of the echo "$i" call above, between the do and done inside the for loop, you can invoke your procedure proc "$i".


Update: The above snippet works if the value of variable does not contain spaces. If you have such a requirement, please use one of the solutions that can change IFS and then parse your variable.


Hope this helps.

Run java jar file on a server as background process

If you're using Ubuntu and have "Upstart" (http://upstart.ubuntu.com/) you can try this:

Create /var/init/yourservice.conf

with the following content

description "Your Java Service"  
author "You"  

start on runlevel [3]  
stop on shutdown  

expect fork  

script     
    cd /web 
    java -jar server.jar >/var/log/yourservice.log 2>&1  
    emit yourservice_running  
end script  

Now you can issue the service yourservice start and service yourservice stop commands. You can tail /var/log/yourservice.log to verify that it's working.

If you just want to run your jar from the console without it hogging the console window, you can just do:

java -jar /web/server.jar > /var/log/yourservice.log 2>&1

html "data-" attribute as javascript parameter

The easiest way to get data-* attributes is with element.getAttribute():

onclick="fun(this.getAttribute('data-uid'), this.getAttribute('data-name'), this.getAttribute('data-value'));"

DEMO: http://jsfiddle.net/pm6cH/


Although I would suggest just passing this to fun(), and getting the 3 attributes inside the fun function:

onclick="fun(this);"

And then:

function fun(obj) {
    var one = obj.getAttribute('data-uid'),
        two = obj.getAttribute('data-name'),
        three = obj.getAttribute('data-value');
}

DEMO: http://jsfiddle.net/pm6cH/1/


The new way to access them by property is with dataset, but that isn't supported by all browsers. You'd get them like the following:

this.dataset.uid
// and
this.dataset.name
// and
this.dataset.value

DEMO: http://jsfiddle.net/pm6cH/2/


Also note that in your HTML, there shouldn't be a comma here:

data-name="bbb",

References:

How to append text to a text file in C++?

I use this code. It makes sure that file gets created if it doesn't exist and also adds bit of error checks.

static void appendLineToFile(string filepath, string line)
{
    std::ofstream file;
    //can't enable exception now because of gcc bug that raises ios_base::failure with useless message
    //file.exceptions(file.exceptions() | std::ios::failbit);
    file.open(filepath, std::ios::out | std::ios::app);
    if (file.fail())
        throw std::ios_base::failure(std::strerror(errno));

    //make sure write fails with exception if something is wrong
    file.exceptions(file.exceptions() | std::ios::failbit | std::ifstream::badbit);

    file << line << std::endl;
}

no operator "<<" matches these operands

You're not including the standard <string> header.

You got [un]lucky that some of its pertinent definitions were accidentally made available by the other standard headers that you did include ... but operator<< was not.

Give all permissions to a user on a PostgreSQL database

GRANT USAGE ON SCHEMA schema_name TO user;

Array initialization syntax when not in a declaration

Why is this blocked by Java?

You'd have to ask the Java designers. There might be some subtle grammatical reason for the restriction. Note that some of the array creation / initialization constructs were not in Java 1.0, and (IIRC) were added in Java 1.1.

But "why" is immaterial ... the restriction is there, and you have to live with it.

I know how to work around it, but from time to time it would be simpler.

You can write this:

AClass[] array;
...
array = new AClass[]{object1, object2};

CSV with comma or semicolon?

I'd say stick to comma as it's widely recognized and understood. Be sure to quote your values and escape your quotes though.

ID,NAME,AGE
"23434","Norris, Chuck","24"
"34343","Bond, James ""master""","57"

PL/SQL, how to escape single quote in a string?

In addition to DCookie's answer above, you can also use chr(39) for a single quote.

I find this particularly useful when I have to create a number of insert/update statements based on a large amount of existing data.

Here's a very quick example:

Lets say we have a very simple table, Customers, that has 2 columns, FirstName and LastName. We need to move the data into Customers2, so we need to generate a bunch of INSERT statements.

Select 'INSERT INTO Customers2 (FirstName, LastName) ' ||
       'VALUES (' || chr(39) || FirstName || chr(39) ',' || 
       chr(39) || LastName || chr(39) || ');' From Customers;

I've found this to be very useful when moving data from one environment to another, or when rebuilding an environment quickly.

HttpContext.Current.User.Identity.Name is Empty

I struggled with this problem the past few days.

I suggest reading Scott Guthrie's blog post Recipe: Enabling Windows Authentication within an Intranet ASP.NET Web application

For me the problem was that although I had Windows Authentication enabled in IIS and I had <authentication mode="Windows" /> in the <system.web> section of web.config, I was not preventing anonymous access. This last part was the key. You need to prevent anonymous access to ensure that the browser sends the credentials.

You can either configure IIS in Control Panel so that your site (or machine) uses Windows authentication and denies anonymous access or you can add the following to your web.config in the system.web section:

<authentication mode="Windows" />

<authorization>
   <deny users="?"/>
</authorization>

What is an instance variable in Java?

An instance variable is a variable that is a member of an instance of a class (i.e., associated with something created with a new), whereas a class variable is a member of the class itself.

Every instance of a class will have its own copy of an instance variable, whereas there is only one of each static (or class) variable, associated with the class itself.

What’s the difference between a class variable and an instance variable?

This test class illustrates the difference:

public class Test {
   
    public static String classVariable = "I am associated with the class";
    public String instanceVariable = "I am associated with the instance";
    
    public void setText(String string){
        this.instanceVariable = string;
    }
    
    public static void setClassText(String string){
        classVariable = string;
    }
    
    public static void main(String[] args) {
        Test test1 = new Test();
        Test test2 = new Test();
        
        // Change test1's instance variable
        test1.setText("Changed");
        System.out.println(test1.instanceVariable); // Prints "Changed"
        // test2 is unaffected
        System.out.println(test2.instanceVariable); // Prints "I am associated with the instance"
        
        // Change class variable (associated with the class itself)
        Test.setClassText("Changed class text");
        System.out.println(Test.classVariable); // Prints "Changed class text"
        
        // Can access static fields through an instance, but there still is only one
        // (not best practice to access static variables through instance)
        System.out.println(test1.classVariable); // Prints "Changed class text"
        System.out.println(test2.classVariable); // Prints "Changed class text"
    }
}

How to divide flask app into multiple py files?

This task can be accomplished without blueprints and tricky imports using Centralized URL Map

app.py

import views
from flask import Flask

app = Flask(__name__)

app.add_url_rule('/', view_func=views.index)
app.add_url_rule('/other', view_func=views.other)

if __name__ == '__main__':
    app.run(debug=True, use_reloader=True)

views.py

from flask import render_template

def index():
    return render_template('index.html')

def other():
    return render_template('other.html')

iOS 7 status bar overlapping UI

I use this code in the ViewDidLoad method.

 if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
 {
    self.edgesForExtendedLayout = UIRectEdgeNone;
 }

This works when trying to support previous iOS versions too.

How to extract extension from filename string in Javascript?

Better to use the following; Works always!

var ext =  fileName.split('.').pop();

This will return the extension without a dot prefix. You can add "." + ext to check against the extensions you wish to support!

'System.OutOfMemoryException' was thrown when there is still plenty of memory free

If you do not need the Visual Studio Hosting Process:

Uncheck the option: Project->Properties->Debug->Enable the Visual Studio Hosting Process

And then build.

If you still face the problem:

Go to Project->Properties->Build Events->Post-Build Event Command line and paste the following:

call "$(DevEnvDir)..\..\vc\vcvarsall.bat" x86
"$(DevEnvDir)..\..\vc\bin\EditBin.exe" "$(TargetPath)"  /LARGEADDRESSAWARE

Now, build the project.

MySQL SELECT WHERE datetime matches day (and not necessarily time)

You can use %:

SELECT * FROM datetable WHERE datecol LIKE '2012-12-25%'

How to Consolidate Data from Multiple Excel Columns All into One Column

The formula

=OFFSET(Sheet1!$A$1,MOD(ROW()-1,COUNT(Sheet1!$A$1:$A$20000)),
    (ROW()-1)/COUNT(Sheet1!$A$1:$A$20000))

placed into each cell of your second workbook will retrieve the appropriate cell from the source sheet. No macros, simple copying from one sheet to another to reformat the results.

You will need to modify the ranges in the COUNT function to match the maximum number of rows in the source sheet. Adjust for column headers as required.

If you need something other than a 0 for empty cells, you may prefer to include a conditional.

A script to reformat the data may well be more efficient, but 20k rows is no longer a real limit in a modern Excel workbook.

What is PAGEIOLATCH_SH wait type in SQL Server?

PAGEIOLATCH_SH wait type usually comes up as the result of fragmented or unoptimized index.

Often reasons for excessive PAGEIOLATCH_SH wait type are:

  • I/O subsystem has a problem or is misconfigured
  • Overloaded I/O subsystem by other processes that are producing the high I/O activity
  • Bad index management
  • Logical or physical drive misconception
  • Network issues/latency
  • Memory pressure
  • Synchronous Mirroring and AlwaysOn AG

In order to try and resolve having high PAGEIOLATCH_SH wait type, you can check:

  • SQL Server, queries and indexes, as very often this could be found as a root cause of the excessive PAGEIOLATCH_SH wait types
  • For memory pressure before jumping into any I/O subsystem troubleshooting

Always keep in mind that in case of high safety Mirroring or synchronous-commit availability in AlwaysOn AG, increased/excessive PAGEIOLATCH_SH can be expected.

You can find more details about this topic in the article Handling excessive SQL Server PAGEIOLATCH_SH wait types

How to auto-indent code in the Atom editor?

I prefer using atom-beautify, CTRL+ALT+B (in linux, may be in windows also) handles better al kind of formats and it is also customizable per file format.

more details here: https://atom.io/packages/atom-beautify

Find duplicate records in MySQL

Find duplicate users by email address with this query...

SELECT users.name, users.uid, users.mail, from_unixtime(created)
FROM users
INNER JOIN (
  SELECT mail
  FROM users
  GROUP BY mail
  HAVING count(mail) > 1
) dupes ON users.mail = dupes.mail
ORDER BY users.mail;

Laravel: Validation unique on update

It works like a charm someone can try this. Here I have used soft delete checker. You could omit the last: id,deleted_at, NULL if your model doesn't have soft delete implementation.

public function rules()
{
    switch ($this->method()) {
        case 'PUT':
            $emailRules = "required|unique:users,email,{$this->id},id,deleted_at,NULL";
            break;
        default:
            $emailRules = "required|unique:users,email,NULL,id,deleted_at,NULL";
            break;
    }

    return [
        'email' => $emailRules,
        'display_name' => 'nullable',
        'description' => 'nullable',
    ];
}

Thank you.

GridView - Show headers on empty data source

Juste add ShowHeaderWhenEmpty property and set it at true

This solution works for me

How to find cube root using Python?

def cube(x):
    if 0<=x: return x**(1./3.)
    return -(-x)**(1./3.)
print (cube(8))
print (cube(-8))

Here is the full answer for both negative and positive numbers.

>>> 
2.0
-2.0
>>> 

Or here is a one-liner;

root_cube = lambda x: x**(1./3.) if 0<=x else -(-x)**(1./3.)

How much memory can a 32 bit process access on a 64 bit operating system?

Nobody seems to touch upon the fact that if you have many different 32-bit applications, the wow64 subsystem can map them anywhere in memory above 4G, so on a 64-bit windows with sufficient memory, you can run many more 32-bit applications than on a native 32-bit system.

Function to return only alpha-numeric characters from string?

Warning: Note that English is not restricted to just A-Z.

Try this to remove everything except a-z, A-Z and 0-9:

$result = preg_replace("/[^a-zA-Z0-9]+/", "", $s);

If your definition of alphanumeric includes letters in foreign languages and obsolete scripts then you will need to use the Unicode character classes.

Try this to leave only A-Z:

$result = preg_replace("/[^A-Z]+/", "", $s);

The reason for the warning is that words like résumé contains the letter é that won't be matched by this. If you want to match a specific list of letters adjust the regular expression to include those letters. If you want to match all letters, use the appropriate character classes as mentioned in the comments.

how to calculate percentage in python

Percent calculation that worked for me:

(new_num - old_num) / old_num * 100.0

@Nullable annotation usage

It makes it clear that the method accepts null values, and that if you override the method, you should also accept null values.

It also serves as a hint for code analyzers like FindBugs. For example, if such a method dereferences its argument without checking for null first, FindBugs will emit a warning.

Redirecting from cshtml page

Would be safer to do this.

@{ Response.Redirect("~/Account/LogIn?returnUrl=Products");}

So the controller for that action runs as well, to populate any model the view needs.

Source
Redirect from a view to another view

Although as @Satpal mentioned, I do recommend you do the redirecting on your controller.

My C# application is returning 0xE0434352 to Windows Task Scheduler but it is not crashing

In my case it was because I had message boxes. Once I commented that code out, it started working. I remembered that could be a problem when I looked at the event log as suggested in this thread. Thank you everyone!

Interface extends another interface but implements its methods

An interface defines behavior. For example, a Vehicle interface might define the move() method.

A Car is a Vehicle, but has additional behavior. For example, the Car interface might define the startEngine() method. Since a Car is also a Vehicle, the Car interface extends the Vehicle interface, and thus defines two methods: move() (inherited) and startEngine().

The Car interface doesn't have any method implementation. If you create a class (Volkswagen) that implements Car, it will have to provide implementations for all the methods of its interface: move() and startEngine().

An interface may not implement any other interface. It can only extend it.

How can I make a SQL temp table with primary key and auto-incrementing field?

If you're just doing some quick and dirty temporary work, you can also skip typing out an explicit CREATE TABLE statement and just make the temp table with a SELECT...INTO and include an Identity field in the select list.

select IDENTITY(int, 1, 1) as ROW_ID,
       Name
into #tmp
from (select 'Bob' as Name union all
      select 'Susan' as Name union all
      select 'Alice' as Name) some_data

select *
from #tmp

Make a dictionary in Python from input values

I have taken an empty dictionary as f and updated the values in f as name,password or balance are keys.

f=dict()
f.update(name=input(),password=input(),balance=input())
print(f)

ALTER TABLE add constraint

ALTER TABLE `User`
ADD CONSTRAINT `user_properties_foreign`
FOREIGN KEY (`properties`)
REFERENCES `Properties` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;

How do you cast a List of supertypes to a List of subtypes?

casting of generics is not possible, but if you define the list in another way it is possible to store TestB in it:

List<? extends TestA> myList = new ArrayList<TestA>();

You still have type checking to do when you are using the objects in the list.

Change color when hover a font awesome icon?

use - !important - to override default black

_x000D_
_x000D_
.fa-heart:hover{_x000D_
   color:red !important;_x000D_
}_x000D_
.fa-heart-o:hover{_x000D_
   color:red !important;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
_x000D_
<i class="fa fa-heart fa-2x"></i>_x000D_
<i class="fa fa-heart-o fa-2x"></i>
_x000D_
_x000D_
_x000D_

Remove scroll bar track from ScrollView in Android

Solved my problem by adding this to my ListView:

android:scrollbars="none"

Switch between two frames in tkinter

Note: According to JDN96, the answer below may cause a memory leak by repeatedly destroying and recreating frames. However, I have not tested to verify this myself.

One way to switch frames in tkinter is to destroy the old frame then replace it with your new frame.

I have modified Bryan Oakley's answer to destroy the old frame before replacing it. As an added bonus, this eliminates the need for a container object and allows you to use any generic Frame class.

# Multi-frame tkinter application v2.3
import tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self._frame = None
        self.switch_frame(StartPage)

    def switch_frame(self, frame_class):
        """Destroys current frame and replaces it with a new one."""
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack()

class StartPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="This is the start page").pack(side="top", fill="x", pady=10)
        tk.Button(self, text="Open page one",
                  command=lambda: master.switch_frame(PageOne)).pack()
        tk.Button(self, text="Open page two",
                  command=lambda: master.switch_frame(PageTwo)).pack()

class PageOne(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="This is page one").pack(side="top", fill="x", pady=10)
        tk.Button(self, text="Return to start page",
                  command=lambda: master.switch_frame(StartPage)).pack()

class PageTwo(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="This is page two").pack(side="top", fill="x", pady=10)
        tk.Button(self, text="Return to start page",
                  command=lambda: master.switch_frame(StartPage)).pack()

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

Start page Page one Page two

Explanation

switch_frame() works by accepting any Class object that implements Frame. The function then creates a new frame to replace the old one.

  • Deletes old _frame if it exists, then replaces it with the new frame.
  • Other frames added with .pack(), such as menubars, will be unaffected.
  • Can be used with any class that implements tkinter.Frame.
  • Window automatically resizes to fit new content

Version History

v2.3

- Pack buttons and labels as they are initialized

v2.2

- Initialize `_frame` as `None`.
- Check if `_frame` is `None` before calling `.destroy()`.

v2.1.1

- Remove type-hinting for backwards compatibility with Python 3.4.

v2.1

- Add type-hinting for `frame_class`.

v2.0

- Remove extraneous `container` frame.
    - Application now works with any generic `tkinter.frame` instance.
- Remove `controller` argument from frame classes.
    - Frame switching is now done with `master.switch_frame()`.

v1.6

- Check if frame attribute exists before destroying it.
- Use `switch_frame()` to set first frame.

v1.5

  - Revert 'Initialize new `_frame` after old `_frame` is destroyed'.
      - Initializing the frame before calling `.destroy()` results
        in a smoother visual transition.

v1.4

- Pack frames in `switch_frame()`.
- Initialize new `_frame` after old `_frame` is destroyed.
    - Remove `new_frame` variable.

v1.3

- Rename `parent` to `master` for consistency with base `Frame` class.

v1.2

- Remove `main()` function.

v1.1

- Rename `frame` to `_frame`.
    - Naming implies variable should be private.
- Create new frame before destroying old frame.

v1.0

- Initial version.

OpenCV - Saving images to a particular folder of choice

Answer given by Jeru Luke is working only on Windows systems, if we try on another operating system (Ubuntu) then it runs without error but the image is saved on target location or path.

Not working in Ubuntu and working in Windows

  import cv2
  img = cv2.imread('1.jpg', 1)
  path = '/tmp'
  cv2.imwrite(str(path) + 'waka.jpg',img)
  cv2.waitKey(0)

I run above code but the image does not save the image on target path. Then I found that the way of adding path is wrong for the general purpose we using OS module to add the path.

Example:

 import os
 final_path = os.path.join(path_1,path_2,path_3......)

working in Ubuntu and Windows

 import cv2
 import os
 img = cv2.imread('1.jpg', 1)
 path = 'D:/OpenCV/Scripts/Images'
 cv2.imwrite(os.path.join(path , 'waka.jpg'),img)
 cv2.waitKey(0)

that code works fine on both Windows and Ubuntu :)

Remove secure warnings (_CRT_SECURE_NO_WARNINGS) from projects by default in Visual Studio

my two cents for VS 2017:

I can confirm it works in stdafx.h both in these styles:

a)

#pragma once
#define _CRT_SECURE_NO_WARNINGS 1 
#define _WINSOCK_DEPRECATED_NO_WARNINGS 1 

b)

#define _CRT_SECURE_NO_WARNINGS 1 
#define _WINSOCK_DEPRECATED_NO_WARNINGS 1 
#pragma once

(I have added another define for MSDN network calls..) Of course I do prefer a).

I can confirm that: #define _CRT_SECURE_NO_WARNINGS (without a value) DOES NOT WORK.

PS the real point is to put these defines BEFORE declarations of functions, i.e. before *.h

linux find regex

Regular expressions with character classes (e.g. [[:digit:]]) are not supported in the default regular expression syntax used by find. You need to specify a different regex type such as posix-extended in order to use them.

Take a look at GNU Find's Regular Expression documentation which shows you all the regex types and what they support.

How to insert values in table with foreign key using MySQL?

http://dev.mysql.com/doc/refman/5.0/en/insert-select.html

For case1:

INSERT INTO TAB_STUDENT(name_student, id_teacher_fk)
SELECT 'Joe The Student', id_teacher
  FROM TAB_TEACHER
 WHERE name_teacher = 'Professor Jack'
 LIMIT 1

For case2 you just have to do 2 separate insert statements

How to construct a REST API that takes an array of id's for the resources

I find another way of doing the same thing by using @PathParam. Here is the code sample.

@GET
@Path("data/xml/{Ids}")
@Produces("application/xml")
public Object getData(@PathParam("zrssIds") String Ids)
{
  System.out.println("zrssIds = " + Ids);
  //Here you need to use String tokenizer to make the array from the string.
}

Call the service by using following url.

http://localhost:8080/MyServices/resources/cm/data/xml/12,13,56,76

where

http://localhost:8080/[War File Name]/[Servlet Mapping]/[Class Path]/data/xml/12,13,56,76

What is the maximum length of data I can put in a BLOB column in MySQL?

A BLOB can be 65535 bytes maximum. If you need more consider using a MEDIUMBLOB for 16777215 bytes or a LONGBLOB for 4294967295 bytes.

Hope, it will help you.

Should I use 'border: none' or 'border: 0'?

You may simply use both as per the specification kindly provided by Oli.

I always use border:0 none;.

Though there is no harm in specifying them seperately and some browsers will parse the CSS faster if you do use the legacy CSS1 property calls.

Though border:0; will normally default the border style to none, I have however noticed some browsers enforcing their default border style which can strangely overwrite border:0;.

Error:java: javacTask: source release 8 requires target release 1.8

With Intellij, using Maven, you must check that Intellij has auto-imported your project. You can check by clicking on the Maven tab on the right of your Editor.

enter image description here

If your Project is not here, then add the pom.xml file by clicking on +.

Obviously, the project must also have the relevant <build/> :

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
        </configuration>
    </plugin>

@Autowired - No qualifying bean of type found for dependency at least 1 bean

In your controller class, just add @ComponentScan("package") annotation. In my case the package name is com.shoppingcart.So i wrote the code as @ComponentScan("com.shoppingcart") and it worked for me.

Making an image act like a button

You could implement a JavaScript block which contains a function with your needs.

<div style="position: absolute; left: 10px; top: 40px;"> 
    <img src="logg.png" width="114" height="38" onclick="DoSomething();" />
</div>

Laravel 5.2 redirect back with success message

You can simply use back() function to redirect no need to use redirect()->back() make sure you are using 5.2 or greater than 5.2 version.

You can replace your code to below code.

return back()->with('message', 'WORKS!');

In the view file replace below code.

@if(session()->has('message'))
    <div class="alert alert-success">
        {{ session()->get('message') }}
    </div>
@endif

For more detail, you can read here

back() is just a helper function. It's doing the same thing as redirect()->back()

How to find and turn on USB debugging mode on Nexus 4

In case you enabled debugging mode on your phone and adb devices is not listing your device, it seems there is a problem with phone driver. You might not install the usb-driver of your phone or driver might be installed with problems (in windows check in system --> device manager).

In my case, I had the same problem with My HTC android usb device which installing drivers again, fixed my problems.

Append data to a POST NSURLRequest

 NSURL *url= [NSURL URLWithString:@"https://www.paypal.com/cgi-bin/webscr"];
 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                                        cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                    timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
 NSString *postString = @"userId=2323";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

How to strip HTML tags with jQuery?

You can use the existing split function

One easy and choppy exemple:

var str = '<p> example ive got a string</P>';
var substr = str.split('<p> ');
// substr[0] contains ""
// substr[1] contains "example ive got a string</P>"
var substr2 = substr [1].split('</p>');
// substr2[0] contains "example ive got a string"
// substr2[1] contains ""

The example is just to show you how the split works.

ArrayList vs List<> in C#

Simple Answer is,

ArrayList is Non-Generic

  • It is an Object Type, so you can store any data type into it.
  • You can store any values (value type or reference type) such string, int, employee and object in the ArrayList. (Note and)
  • Boxing and Unboxing will happen.
  • Not type safe.
  • It is older.

List is Generic

  • It is a Type of Type, so you can specify the T on run-time.
  • You can store an only value of Type T (string or int or employee or object) based on the declaration. (Note or)
  • Boxing and Unboxing will not happen.
  • Type safe.
  • It is newer.

Example:

ArrayList arrayList = new ArrayList();
List<int> list = new List<int>();

arrayList.Add(1);
arrayList.Add("String");
arrayList.Add(new object());


list.Add(1);
list.Add("String");                 // Compile-time Error
list.Add(new object());             // Compile-time Error

Please read the Microsoft official document: https://blogs.msdn.microsoft.com/kcwalina/2005/09/23/system-collections-vs-system-collection-generic-and-system-collections-objectmodel/

enter image description here

Note: You should know Generics before understanding the difference: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/

How to create loading dialogs in Android?

Today things have changed a little.

Now we avoid use ProgressDialog to show spinning progress:

enter image description here

If you want to put in your app a spinning progress you should use an Activity indicators:

http://developer.android.com/design/building-blocks/progress.html#activity

How to read a text file into a string variable and strip newlines?

python3: Google "list comphrension" if the square bracket syntax is new to you.

 with open('data.txt') as f:
     lines = [ line.strip( ) for line in list(f) ]

Combine :after with :hover

in scss

&::after{
content: url(images/RelativeProjectsArr.png);
margin-left:30px;
}

&:hover{
    background-color:$turkiz;
    color:#e5e7ef;

    &::after{
    content: url(images/RelativeProjectsArrHover.png);
    }
}

What are valid values for the id attribute in HTML?

Strictly it should match

[A-Za-z][-A-Za-z0-9_:.]*

But jquery seems to have problems with colons so it might be better to avoid them.

C# Error: Parent does not contain a constructor that takes 0 arguments

Since you don't explicitly invoke a parent constructor as part of your child class constructor, there is an implicit call to a parameterless parent constructor inserted. That constructor does not exist, and so you get that error.

To correct the situation, you need to add an explicit call:

public Child(int i) : base(i)
{
    Console.WriteLine("child");
}

Or, you can just add a parameterless parent constructor:

protected Parent() { } 

Best practice to call ConfigureAwait for all server-side code

I have some general thoughts about the implementation of Task:

  1. Task is disposable yet we are not supposed to use using.
  2. ConfigureAwait was introduced in 4.5. Task was introduced in 4.0.
  3. .NET Threads always used to flow the context (see C# via CLR book) but in the default implementation of Task.ContinueWith they do not b/c it was realised context switch is expensive and it is turned off by default.
  4. The problem is a library developer should not care whether its clients need context flow or not hence it should not decide whether flow the context or not.
  5. [Added later] The fact that there is no authoritative answer and proper reference and we keep fighting on this means someone has not done their job right.

I have got a few posts on the subject but my take - in addition to Tugberk's nice answer - is that you should turn all APIs asynchronous and ideally flow the context . Since you are doing async, you can simply use continuations instead of waiting so no deadlock will be cause since no wait is done in the library and you keep the flowing so the context is preserved (such as HttpContext).

Problem is when a library exposes a synchronous API but uses another asynchronous API - hence you need to use Wait()/Result in your code.

How to get current route in react-router 2.0.0-rc5

For any users having the same issue in 2017, I solved it the following way:

NavBar.contextTypes = {
    router: React.PropTypes.object,
    location: React.PropTypes.object
}

and use it like this:

componentDidMount () {
    console.log(this.context.location.pathname);
}

Razor If/Else conditional operator syntax

You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:

@(deletedView ? "Deleted" : "Created by")

Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.

How to commit my current changes to a different branch in Git

The other answers suggesting checking out the other branch, then committing to it, only work if the checkout is possible given the local modifications. If not, you're in the most common use case for git stash:

git stash
git checkout other-branch
git stash pop

The first stash hides away your changes (basically making a temporary commit), and the subsequent stash pop re-applies them. This lets Git use its merge capabilities.

If, when you try to pop the stash, you run into merge conflicts... the next steps depend on what those conflicts are. If all the stashed changes indeed belong on that other branch, you're simply going to have to sort through them - it's a consequence of having made your changes on the wrong branch.

On the other hand, if you've really messed up, and your work tree has a mix of changes for the two branches, and the conflicts are just in the ones you want to commit back on the original branch, you can save some work. As usual, there are a lot of ways to do this. Here's one, starting from after you pop and see the conflicts:

# Unstage everything (warning: this leaves files with conflicts in your tree)
git reset

# Add the things you *do* want to commit here
git add -p     # or maybe git add -i
git commit

# The stash still exists; pop only throws it away if it applied cleanly
git checkout original-branch
git stash pop

# Add the changes meant for this branch
git add -p
git commit

# And throw away the rest
git reset --hard

Alternatively, if you realize ahead of the time that this is going to happen, simply commit the things that belong on the current branch. You can always come back and amend that commit:

git add -p
git commit
git stash
git checkout other-branch
git stash pop

And of course, remember that this all took a bit of work, and avoid it next time, perhaps by putting your current branch name in your prompt by adding $(__git_ps1) to your PS1 environment variable in your bashrc file. (See for example the Git in Bash documentation.)

In Bootstrap 3,How to change the distance between rows in vertical?

Instead of adding any tag which is never a good solution. You can always use margin property with the required element.

You can add the margin on row class itself. So it will affect globally.

.row{
  margin-top: 30px;
  margin-bottom: 30px
}

Update: Better solution in all cases would be to introduce a new class and then use it along with .row class.

.row-m-t{
  margin-top : 20px
}

Then use it wherever you want

<div class="row row-m-t"></div>

How do I make background-size work in IE?

A bit late, but this could also be useful. There is an IE filter, for IE 5.5+, which you can apply:

filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='images/logo.gif',
sizingMethod='scale');

-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='images/logo.gif',
sizingMethod='scale')";

However, this scales the entire image to fit in the allocated area, so if you're using a sprite, this may cause issues.

Specification: AlphaImageLoader Filter @microsoft

Get today date in google appScript

function myFunction() {
  var sheetname = "DateEntry";//Sheet where you want to put the date
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetname);
    // You could use now Date(); on its own but it will not look nice.
  var date = Utilities.formatDate(new Date(), "GMT+5:30", "yyyy-MM-dd");
    //var endDate = date;
    sheet.getRange(sheet.getLastRow() + 1,1).setValue(date); //Gets the last row which had value, and goes to the next empty row to put new values.
}

TCP: can two different sockets share a port?

No. It is not possible to share the same port at a particular instant. But you can make your application such a way that it will make the port access at different instant.

Create a hexadecimal colour based on a string with JavaScript

This function does the trick. It's an adaptation of this, fairly longer implementation this repo ..

const color = (str) => {
    let rgb = [];
    // Changing non-hexadecimal characters to 0
    str = [...str].map(c => (/[0-9A-Fa-f]/g.test(c)) ? c : 0).join('');
    // Padding string with zeroes until it adds up to 3
    while (str.length % 3) str += '0';

    // Dividing string into 3 equally large arrays
    for (i = 0; i < str.length; i += str.length / 3)
        rgb.push(str.slice(i, i + str.length / 3));

    // Formatting a hex color from the first two letters of each portion
    return `#${rgb.map(string => string.slice(0, 2)).join('')}`;
}

decimal vs double! - Which one should I use and when?

I think that the main difference beside bit width is that decimal has exponent base 10 and double has 2

http://software-product-development.blogspot.com/2008/07/net-double-vs-decimal.html

What is the command for cut copy paste a file from one directory to other directory

use the xclip which is command line interface to X selections

install

apt-get install xclip

usage

echo "test xclip " > /tmp/test.xclip
xclip -i < /tmp/test.xclip
xclip -o > /tmp/test.xclip.out

cat /tmp/test.xclip.out   # "test xclip"

enjoy.

Create MSI or setup project with Visual Studio 2012

Have you tried the "Publish" method? You just right click on the project file in the solution explorer and select "Publish" from the pop-up menu. This creates an installer in a few very simple steps.

You can do more configuration of the installer from the Publish tab in the project properties window.

NB: This method only works for WPF & Windows Forms apps.

What does this GCC error "... relocation truncated to fit..." mean?

On Cygwin -mcmodel=medium is already default and doesn't help. To me adding -Wl,--image-base -Wl,0x10000000 to GCC linker did fixed the error.

Convert a hexadecimal string to an integer efficiently in C?

As if often happens, your question suffers from a serious terminological error/ambiguity. In common speech it usually doesn't matter, but in the context of this specific problem it is critically important.

You see, there's no such thing as "hex value" and "decimal value" (or "hex number" and "decimal number"). "Hex" and "decimal" are properties of representations of values. Meanwhile, values (or numbers) by themselves have no representation, so they can't be "hex" or "decimal". For example, 0xF and 15 in C syntax are two different representations of the same number.

I would guess that your question, the way it is stated, suggests that you need to convert ASCII hex representation of a value (i.e. a string) into a ASCII decimal representation of a value (another string). One way to do that is to use an integer representation as an intermediate one: first, convert ASCII hex representation to an integer of sufficient size (using functions from strto... group, like strtol), then convert the integer into the ASCII decimal representation (using sprintf).

If that's not what you need to do, then you have to clarify your question, since it is impossible to figure it out from the way your question is formulated.

iPad Safari scrolling causes HTML elements to disappear and reappear with a delay

In my case, CSS did not fix the issue. I noticed the problem while using jQuery re-render a button.

$("#myButton").html("text")

Try this

$("#myButton").html("<span>text</span>")

How to delete a remote tag?

As @CubanX suggested, I've split this answer from my original:

Here is a method which is several times faster than xargs and may scale much more with tweaking. It uses the Github API, a personal access token, and leverages the utility parallel.

git tag | sorting_processing_etc | parallel --jobs 2 curl -i -X DELETE \ 
https://api.github.com/repos/My_Account/my_repo/git/refs/tags/{} -H 
\"authorization: token GIT_OAUTH_OR_PERSONAL_KEY_HERE\"  \
-H \"cache-control: no-cache\"`

parallel has many operating modes, but generally parallelizes any command you give it while allowing you to set limits on the number of processes. You can alter the --jobs 2 parameter to allow faster operation, but I had problems with Github's rate limits, which are currently 5000/hr, but also seems to have an undocumented short-term limit as well.


After this, you'll probably want to delete your local tags too. This is much faster so we can go back to using xargs and git tag -d, which is sufficient.

git tag | sorting_processing_etc | xargs -L 1 git tag -d

How to set adaptive learning rate for GradientDescentOptimizer?

If you want to set specific learning rates for intervals of epochs like 0 < a < b < c < .... Then you can define your learning rate as a conditional tensor, conditional on the global step, and feed this as normal to the optimiser.

You could achieve this with a bunch of nested tf.cond statements, but its easier to build the tensor recursively:

def make_learning_rate_tensor(reduction_steps, learning_rates, global_step):
    assert len(reduction_steps) + 1 == len(learning_rates)
    if len(reduction_steps) == 1:
        return tf.cond(
            global_step < reduction_steps[0],
            lambda: learning_rates[0],
            lambda: learning_rates[1]
        )
    else:
        return tf.cond(
            global_step < reduction_steps[0],
            lambda: learning_rates[0],
            lambda: make_learning_rate_tensor(
                reduction_steps[1:],
                learning_rates[1:],
                global_step,)
            )

Then to use it you need to know how many training steps there are in a single epoch, so that we can use the global step to switch at the right time, and finally define the epochs and learning rates you want. So if I want the learning rates [0.1, 0.01, 0.001, 0.0001] during the epoch intervals of [0, 19], [20, 59], [60, 99], [100, \infty] respectively, I would do:

global_step = tf.train.get_or_create_global_step()
learning_rates = [0.1, 0.01, 0.001, 0.0001]
steps_per_epoch = 225
epochs_to_switch_at = [20, 60, 100]
epochs_to_switch_at = [x*steps_per_epoch for x in epochs_to_switch_at ]
learning_rate = make_learning_rate_tensor(epochs_to_switch_at , learning_rates, global_step)

Eclipse CDT: no rule to make target all

I got this same error after renaming and moving around source files. None of the proposed solutions worked for me and I tracked the error to be the meta-files under Debug directory not being updated. Deleting the entire Debug directory and re-build the project solved the problem for me.

c++ Read from .csv file

Your csv is malformed. The output is not three loopings but just one output. To ensure that this is a single loop, add a counter and increment it with every loop. It should only count to one.

This is what your code sees

0,Filipe,19,M\n1,Maria,20,F\n2,Walter,60,M

Try this

0,Filipe,19,M
1,Maria,20,F
2,Walter,60,M


while(file.good())
{

    getline(file, ID, ',');
    cout << "ID: " << ID << " " ; 

    getline(file, nome, ',') ;
    cout << "User: " << nome << " " ;

    getline(file, idade, ',') ;
    cout << "Idade: " << idade << " "  ; 

    getline(file, genero) ; \\ diff
    cout << "Sexo: " <<  genero;\\diff


}

How to update a menu item shown in the ActionBar?

For clarity, I thought that a direct example of grabbing onto a resource can be shown from the following that I think contributes to the response for this question with a quick direct example.

private MenuItem menuItem_;

@Override
public boolean onCreateOptionsMenu(Menu menuF) 
{
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_layout, menuF);
    menuItem_ = menuF.findItem(R.id.menu_item_identifier);
    return true;
}

In this case you hold onto a MenuItem reference at the beginning and then change the state of it (for icon state changes for example) at a later given point in time.

Error: "Input is not proper UTF-8, indicate encoding !" using PHP's simplexml_load_string

Your 0xED 0x6E 0x2C 0x20 bytes correspond to "ín, " in ISO-8859-1, so it looks like your content is in ISO-8859-1, not UTF-8. Tell your data provider about it and ask them to fix it, because if it doesn't work for you it probably doesn't work for other people either.

Now there are a few ways to work it around, which you should only use if you cannot load the XML normally. One of them would be to use utf8_encode(). The downside is that if that XML contains both valid UTF-8 and some ISO-8859-1 then the result will contain mojibake. Or you can try to convert the string from UTF-8 to UTF-8 using iconv() or mbstring, and hope they'll fix it for you. (they won't, but you can at least ignore the invalid characters so you can load your XML)

Or you can take the long, long road and validate/fix the sequences by yourself. That will take you a while depending on how familiar you are with UTF-8. Perhaps there are libraries out there that would do that, although I don't know any.

Either way, notify your data provider that they're sending invalid data so that they can fix it.


Here's a partial fix. It will definitely not fix everything, but will fix some of it. Hopefully enough for you to get by until your provider fix their stuff.

function fix_latin1_mangled_with_utf8_maybe_hopefully_most_of_the_time($str)
{
    return preg_replace_callback('#[\\xA1-\\xFF](?![\\x80-\\xBF]{2,})#', 'utf8_encode_callback', $str);
}

function utf8_encode_callback($m)
{
    return utf8_encode($m[0]);
}

Spring @Value is not resolving to value from property file

Please note that if you have multiple application.properties files throughout your codebase, then try adding your value to the parent project's property file.

You can check your project's pom.xml file to identify what the parent project of your current project is.

Alternatively, try using environment.getProperty() instead of @Value.

How to change the pop-up position of the jQuery DatePicker control

A very simple jquery function.

$(".datepicker").focus(function(event){
                var dim = $(this).offset();
                $("#ui-datepicker-div").offset({
                    top     :   dim.top - 180,
                    left    :   dim.left + 150
                });
            });

phpexcel to download

posible you already solved your problem, any way i hope this help you.

all files downloaded starts with empty line, in my case where four empty lines, and it make a problem. No matter if you work with readfile(); or save('php://output');, This can be fixed with adding ob_start(); at the beginning of the script and ob_end_clean(); just before the readfile(); or save('php://output');.

How to atomically delete keys matching a pattern using Redis

Spring RedisTemplate itself provides the functionality. RedissonClient in the latest version has deprecated the "deleteByPattern" functionality.

Set<String> keys = redisTemplate.keys("geotag|*");
redisTemplate.delete(keys);

Where should my npm modules be installed on Mac OS X?

Second Thomas David Kehoe, with the following caveat --

If you are using node version manager (nvm), your global node modules will be stored under whatever version of node you are using at the time you saved the module.

So ~/.nvm/versions/node/{version}/lib/node_modules/.

Check if the file exists using VBA

I'm not certain what's wrong with your code specifically, but I use this function I found online (URL in the comments) for checking if a file exists:

Private Function File_Exists(ByVal sPathName As String, Optional Directory As Boolean) As Boolean
    'Code from internet: http://vbadud.blogspot.com/2007/04/vba-function-to-check-file-existence.html
    'Returns True if the passed sPathName exist
    'Otherwise returns False
    On Error Resume Next
    If sPathName <> "" Then

        If IsMissing(Directory) Or Directory = False Then

            File_Exists = (Dir$(sPathName) <> "")
        Else

            File_Exists = (Dir$(sPathName, vbDirectory) <> "")
        End If

    End If
End Function

Getting a list of all subdirectories in the current directory

Here are a couple of simple functions based on @Blair Conrad's example -

import os

def get_subdirs(dir):
    "Get a list of immediate subdirectories"
    return next(os.walk(dir))[1]

def get_subfiles(dir):
    "Get a list of immediate subfiles"
    return next(os.walk(dir))[2]

How can I get the CheckBoxList selected values, what I have doesn't seem to work C#.NET/VisualWebPart

Try something like this:

foreach (ListItem listItem in YrChkBox.Items)
{
    if (listItem.Selected)
    { 
       //do some work 
    }
    else 
    { 
      //do something else 
    }
}