Programs & Examples On #Midl

MIDL (Microsoft Interface Definition Language) is a text-based interface description language by Microsoft, based on the DCE/RPC IDL which it extends for use with the Microsoft Component Object Model. Its compiler is also called MIDL.

Group dataframe and get sum AND count?

Just in case you were wondering how to rename columns during aggregation, here's how for

pandas >= 0.25: Named Aggregation

df.groupby('Company Name')['Amount'].agg(MySum='sum', MyCount='count')

Or,

df.groupby('Company Name').agg(MySum=('Amount', 'sum'), MyCount=('Amount', 'count'))

                       MySum  MyCount
Company Name                       
Vifor Pharma UK Ltd  4207.93        5

HikariCP - connection is not available

From stack trace:

HikariPool: Timeout failure pool HikariPool-0 stats (total=20, active=20, idle=0, waiting=0) Means pool reached maximum connections limit set in configuration.

The next line: HikariPool-0 - Connection is not available, request timed out after 30000ms. Means pool waited 30000ms for free connection but your application not returned any connection meanwhile.

Mostly it is connection leak (connection is not closed after borrowing from pool), set leakDetectionThreshold to the maximum value that you expect SQL query would take to execute.

otherwise, your maximum connections 'at a time' requirement is higher than 20 !

Should black box or white box testing be the emphasis for testers?

In my experience most developers naturally migrate towards white box testing. Since we need to ensure that the underlying algorithm is "correct", we tend to focus more on the internals. But, as has been pointed out, both white and black box testing is important.

Therefore, I prefer to have testers focus more on the Black Box tests, to cover for the fact that most developers don't really do it, and frequently aren't very good at it.

That isn't to say that testers should be kept in the dark about how the system works, just that I prefer them to focus more on the problem domain and how actual users interact with the system, not whether the function SomeMethod(int x) will correctly throw an exception if x is equal to 5.

How to both read and write a file in C#

This thread seems to answer your question : simultaneous-read-write-a-file

Basically, what you need is to declare two FileStream, one for read operations, the other for write operations. Writer Filestream needs to open your file in 'Append' mode.

How to embed a SWF file in an HTML page?

<object width="100" height="100">
    <param name="movie" value="file.swf">
    <embed src="file.swf" width="100" height="100">
    </embed>
</object>

Query for array elements inside JSON type

jsonb in Postgres 9.4+

You can use the same query as below, just with jsonb_array_elements().

But rather use the jsonb "contains" operator @> in combination with a matching GIN index on the expression data->'objects':

CREATE INDEX reports_data_gin_idx ON reports
USING gin ((data->'objects') jsonb_path_ops);

SELECT * FROM reports WHERE data->'objects' @> '[{"src":"foo.png"}]';

Since the key objects holds a JSON array, we need to match the structure in the search term and wrap the array element into square brackets, too. Drop the array brackets when searching a plain record.

More explanation and options:

json in Postgres 9.3+

Unnest the JSON array with the function json_array_elements() in a lateral join in the FROM clause and test for its elements:

SELECT data::text, obj
FROM   reports r, json_array_elements(r.data#>'{objects}') obj
WHERE  obj->>'src' = 'foo.png';

db<>fiddle here
Old sqlfiddle

The CTE (WITH query) just substitutes for a table reports.
Or, equivalent for just a single level of nesting:

SELECT *
FROM   reports r, json_array_elements(r.data->'objects') obj
WHERE  obj->>'src' = 'foo.png';

->>, -> and #> operators are explained in the manual.

Both queries use an implicit JOIN LATERAL.

Closely related:

Difference between pre-increment and post-increment in a loop?

In C# there is no difference when used in a for loop.

for (int i = 0; i < 10; i++) { Console.WriteLine(i); }

outputs the same thing as

for (int i = 0; i < 10; ++i) { Console.WriteLine(i); }

As others have pointed out, when used in general i++ and ++i have a subtle yet significant difference:

int i = 0;
Console.WriteLine(i++);   // Prints 0
int j = 0;
Console.WriteLine(++j);   // Prints 1

i++ reads the value of i then increments it.

++i increments the value of i then reads it.

Java : Comparable vs Comparator

When your class implements Comparable, the compareTo method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals() comparisons return true.

A Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.

For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b") would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.

In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.

Installing Python 2.7 on Windows 8

Easiest way is to open CMD or powershell as administrator and type

set PATH=%PATH%;C:\Python27

Selected value for JSP drop down using JSTL

If you don't mind using jQuery you can use the code bellow:

    <script>
     $(document).ready(function(){
           $("#department").val("${requestScope.selectedDepartment}").attr('selected', 'selected');
     });
     </script>


    <select id="department" name="department">
      <c:forEach var="item" items="${dept}">
        <option value="${item.key}">${item.value}</option>
      </c:forEach>
    </select>

In the your Servlet add the following:

        request.setAttribute("selectedDepartment", YOUR_SELECTED_DEPARTMENT );

Get only specific attributes with from Laravel Collection

This avoid to load unised attributes, directly from db:

DB::table('roles')->pluck('title', 'name');

References: https://laravel.com/docs/5.8/queries#retrieving-results (search for pluck)

Maybe next you can apply toArray() if you need such format

Download a file from NodeJS Server using Express

'use strict';

var express = require('express');
var fs = require('fs');
var compress = require('compression');
var bodyParser = require('body-parser');

var app = express();
app.set('port', 9999);
app.use(bodyParser.json({ limit: '1mb' }));
app.use(compress());

app.use(function (req, res, next) {
    req.setTimeout(3600000)
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept,' + Object.keys(req.headers).join());

    if (req.method === 'OPTIONS') {
        res.write(':)');
        res.end();
    } else next();
});

function readApp(req,res) {
  var file = req.originalUrl == "/read-android" ? "Android.apk" : "Ios.ipa",
      filePath = "/home/sony/Documents/docs/";
  fs.exists(filePath, function(exists){
      if (exists) {     
        res.writeHead(200, {
          "Content-Type": "application/octet-stream",
          "Content-Disposition" : "attachment; filename=" + file});
        fs.createReadStream(filePath + file).pipe(res);
      } else {
        res.writeHead(400, {"Content-Type": "text/plain"});
        res.end("ERROR File does NOT Exists.ipa");
      }
    });  
}

app.get('/read-android', function(req, res) {
    var u = {"originalUrl":req.originalUrl};
    readApp(u,res) 
});

app.get('/read-ios', function(req, res) {
    var u = {"originalUrl":req.originalUrl};
    readApp(u,res) 
});

var server = app.listen(app.get('port'), function() {
    console.log('Express server listening on port ' + server.address().port);
});

Recommended date format for REST GET API

REST doesn't have a recommended date format. Really it boils down to what works best for your end user and your system. Personally, I would want to stick to a standard like you have for ISO 8601 (url encoded).

If not having ugly URI is a concern (e.g. not including the url encoded version of :, -, in you URI) and (human) addressability is not as important, you could also consider epoch time (e.g. http://example.com/start/1331162374). The URL looks a little cleaner, but you certainly lose readability.

The /2012/03/07 is another format you see a lot. You could expand upon that I suppose. If you go this route, just make sure you're either always in GMT time (and make that clear in your documentation) or you might also want to include some sort of timezone indicator.

Ultimately it boils down to what works for your API and your end user. Your API should work for you, not you for it ;-).

Detect Route Change with react-router

If you want to listen to the history object globally, you'll have to create it yourself and pass it to the Router. Then you can listen to it with its listen() method:

// Use Router from react-router, not BrowserRouter.
import { Router } from 'react-router';

// Create history object.
import createHistory from 'history/createBrowserHistory';
const history = createHistory();

// Listen to history changes.
// You can unlisten by calling the constant (`unlisten()`).
const unlisten = history.listen((location, action) => {
  console.log(action, location.pathname, location.state);
});

// Pass history to Router.
<Router history={history}>
   ...
</Router>

Even better if you create the history object as a module, so you can easily import it anywhere you may need it (e.g. import history from './history';

Tomcat - maxThreads vs maxConnections

From Tomcat documentation, For blocking I/O (BIO), the default value of maxConnections is the value of maxThreads unless Executor (thread pool) is used in which case, the value of 'maxThreads' from Executor will be used instead. For Non-blocking IO, it doesn't seem to be dependent on maxThreads.

What is the best way to redirect a page using React Router?

One of the simplest way: use Link as follows:

import { Link } from 'react-router-dom';

<Link to={`your-path`} activeClassName="current">{your-link-name}</Link>

If we want to cover the whole div section as link:

 <div>
     <Card as={Link} to={'path-name'}>
         .... 
           card content here
         ....
     </Card>
 </div>

Align div with fixed position on the right side

Just do this. It doesn't affect the horizontal position.

.test {
 position: fixed;
 left: 0;
 right: 0;
 }

Ruby on Rails 3 Can't connect to local MySQL server through socket '/tmp/mysql.sock' on OSX

The default location for the MySQL socket on Mac OS X is /var/mysql/mysql.sock.

Hibernate Union alternatives

I too have been through this pain - if the query is dynamically generated (e.g. Hibernate Criteria) then I couldn't find a practical way to do it.

The good news for me was that I was only investigating union to solve a performance problem when using an 'or' in an Oracle database.

The solution Patrick posted (combining the results programmatically using a set) while ugly (especially since I wanted to do results paging as well) was adequate for me.

How to have a default option in Angular.js select box

In my case since the default varies from case to case in the form. I add a custom attribute in the select tag.

 <select setSeletected="{{data.value}}">
      <option value="value1"> value1....
      <option value="value2"> value2....
       ......

in the directives I created a script that checks the value and when angular fills it in sets the option with that value to selected.

 .directive('setSelected', function(){
    restrict: 'A',
    link: (scope, element, attrs){
     function setSel=(){
     //test if the value is defined if not try again if so run the command
       if (typeof attrs.setSelected=='undefined'){             
         window.setTimeout( function(){setSel()},300) 
       }else{
         element.find('[value="'+attrs.setSelected+'"]').prop('selected',true);          
       }
     }
    }

  setSel()

})

just translated this from coffescript on the fly at least the jist of it is correct if not the hole thing.

It's not the simplest way but get it done when the value varies

How does data binding work in AngularJS?

I wondered this myself for a while. Without setters how does AngularJS notice changes to the $scope object? Does it poll them?

What it actually does is this: Any "normal" place you modify the model was already called from the guts of AngularJS, so it automatically calls $apply for you after your code runs. Say your controller has a method that's hooked up to ng-click on some element. Because AngularJS wires the calling of that method together for you, it has a chance to do an $apply in the appropriate place. Likewise, for expressions that appear right in the views, those are executed by AngularJS so it does the $apply.

When the documentation talks about having to call $apply manually for code outside of AngularJS, it's talking about code which, when run, doesn't stem from AngularJS itself in the call stack.

How to get first object out from List<Object> using Linq

Try:

var firstElement = lstComp.First();

You can also use FirstOrDefault() just in case lstComp does not contain any items.

http://msdn.microsoft.com/en-gb/library/bb340482(v=vs.100).aspx

Edit:

To get the Component Value:

var firstElement = lstComp.First().ComponentValue("Dep");

This would assume there is an element in lstComp. An alternative and safer way would be...

var firstOrDefault = lstComp.FirstOrDefault();
if (firstOrDefault != null) 
{
    var firstComponentValue = firstOrDefault.ComponentValue("Dep");
}

Cannot read property 'addEventListener' of null

I was getting the same error, but performing a null check did not seem to help.

The solution I found was to wrap my function inside an event listener for the whole document to check when the DOM finished loading.

document.addEventListener('DOMContentLoaded', function () {
    el.addEventListener('click', swapper, false);
});

I think this is because I am using a framework (Angular) that is changing my HTML classes and ID's dynamically.

how to use substr() function in jquery?

If you want to extract from a tag then

$('.dep_buttons').text().substr(0,25)

With the mouseover event,

$(this).text($(this).text().substr(0, 25));

The above will extract the text of a tag, then extract again assign it back.

How to solve error message: "Failed to map the path '/'."

It could be due to data in your web.config file. E.g. a backslash in a domain username.

userName='domain\user'. 

Keyboard shortcut to change font size in Eclipse?

Found a great plugin that works in Juno and Kepler. It puts shortcuts on the quick access bar for increasing or decreasing text size.

Install New Software -> http://eclipse-fonts.googlecode.com/svn/trunk/FontsUpdate/

How do the major C# DI/IoC frameworks compare?

While a comprehensive answer to this question takes up hundreds of pages of my book, here's a quick comparison chart that I'm still working on:

A table explaining difference between several DICs

what is the basic difference between stack and queue?

A Visual Model

Pancake Stack (LIFO)

The only way to add one and/or remove one is from the top.

pancake stack

Line Queue (FIFO)

When one arrives they arrive at the end of the queue and when one leaves they leave from the front of the queue.

dmv line

Fun fact: the British refer to lines of people as a Queue

How to run ~/.bash_profile in mac terminal

If the problem is that you are not seeing your changes to the file take effect, just open a new terminal window, and it will be "sourced". You will be able to use the proper PATH etc with each subsequent terminal window.

How to test which port MySQL is running on and whether it can be connected to?

grep port /etc/mysql/my.cnf ( at least in debian/ubuntu works )

or

netstat -tlpn | grep mysql

verify

bind-address 127.0.0.1

in /etc/mysql/my.cnf to see possible restrictions

Python Request Post with param data

Set data to this:

data ={"eventType":"AAS_PORTAL_START","data":{"uid":"hfe3hf45huf33545","aid":"1","vid":"1"}}

Regex, every non-alphanumeric character except white space or colon

If you want to treat accented latin characters (eg. à Ñ) as normal letters (ie. avoid matching them too), you'll also need to include the appropriate Unicode range (\u00C0-\u00FF) in your regex, so it would look like this:

/[^a-zA-Z\d\s:\u00C0-\u00FF]/g
  • ^ negates what follows
  • a-zA-Z matches upper and lower case letters
  • \d matches digits
  • \s matches white space (if you only want to match spaces, replace this with a space)
  • : matches a colon
  • \u00C0-\u00FF matches the Unicode range for accented latin characters.

nb. Unicode range matching might not work for all regex engines, but the above certainly works in Javascript (as seen in this pen on Codepen).

nb2. If you're not bothered about matching underscores, you could replace a-zA-Z\d with \w, which matches letters, digits, and underscores.

Joining pandas dataframes by column names

you need to make county_ID as index for the right frame:

frame_2.join ( frame_1.set_index( [ 'county_ID' ], verify_integrity=True ),
               on=[ 'countyid' ], how='left' )

for your information, in pandas left join breaks when the right frame has non unique values on the joining column. see this bug.

so you need to verify integrity before joining by , verify_integrity=True

getaddrinfo: nodename nor servname provided, or not known

I got the error while trying to develop while disconnected to the Internet. However, the website I was working on needs to be able to talk to some other websites, so it choked when it couldn't do so. Connecting to the internet fixed the error.

How to create empty data frame with column names specified in R?

Just create a data.frame with 0 length variables

eg

nodata <- data.frame(x= numeric(0), y= integer(0), z = character(0))
str(nodata)

## 'data.frame':    0 obs. of  3 variables:
##  $ x: num 
##  $ y: int 
##  $ z: Factor w/ 0 levels: 

or to create a data.frame with 5 columns named a,b,c,d,e

nodata <- as.data.frame(setNames(replicate(5,numeric(0), simplify = F), letters[1:5]))

How to transfer data from JSP to servlet when submitting HTML form

http://oreilly.com/catalog/javacook/chapter/ch18.html

Search for :

"Problem

You want to process the data from an HTML form in a servlet. "

How to close Browser Tab After Submitting a Form?

try onsubmit="submit(); window.close()"

is it possible to update UIButton title/text programmatically?

Sometimes it can get really complicated. The easy way is to "refresh" the button view!

//Do stuff to your button here.  For example:

[mybutton setEnabled:YES];

//Refresh it to new state.

[mybutton setNeedsDisplay];

What does numpy.random.seed(0) do?

I hope to give a really short answer:

seed make (the next series) random numbers predictable. You can think every time after you call seed, it pre-defines series numbers and numpy random keeps the iterator of it, then every time you get a random number it just gonna call get next.

e.g.:

np.random.seed(2)
np.random.randn(2) # array([-0.41675785, -0.05626683])
np.random.randn(1) # array([-1.24528809])

np.random.seed(2)
np.random.randn(1) # array([-0.41675785])
np.random.randn(2) # array([-0.05626683, -1.24528809])

You can notice when I set the same seed, no matter how many random number you request from numpy each time, it always gives the same series of numbers, in this case which is array([-0.41675785, -0.05626683, -1.24528809]).

How to insert array of data into mysql using php

if(is_array($EMailArr)){
    foreach($EMailArr as $key => $value){

    $R_ID = (int) $value['R_ID'];
    $email = mysql_real_escape_string( $value['email'] );
    $name = mysql_real_escape_string( $value['name'] );

    $sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) values ('$R_ID', '$email', '$name')";
    mysql_query($sql) or exit(mysql_error()); 
    }
}

A better example solution with PDO:

 $q = $sql->prepare("INSERT INTO `email_list` 
                     SET `R_ID` = ?, `EMAIL` = ?, `NAME` = ?");

 foreach($EMailArr as $value){
   $q ->execute( array( $value['R_ID'], $value['email'], $value['name'] ));
 }

Does this app use the Advertising Identifier (IDFA)? - AdMob 6.8.0

If you are lazy to check on each third party SDK if they use or not the IDFA you can use this command:
fgrep -R advertisingIdentifier . (don't forget the dot at the end of the command)

Go to your project/workspace folder and run the command to find which files are using the advertising identifier.

Then you just have to look in the guidelines of those SDKs to see what you need to do about the IDFA.

Align printf output in Java

You can refer to this blog for printing formatted coloured text on console

https://javaforqa.wordpress.com/java-print-coloured-table-on-console/

public class ColourConsoleDemo {
/**
*
* @param args
*
* "\033[0m BLACK" will colour the whole line
*
* "\033[37m WHITE\033[0m" will colour only WHITE.
* For colour while Opening --> "\033[37m" and closing --> "\033[0m"
*
*
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("\033[0m BLACK");
System.out.println("\033[31m RED");
System.out.println("\033[32m GREEN");
System.out.println("\033[33m YELLOW");
System.out.println("\033[34m BLUE");
System.out.println("\033[35m MAGENTA");
System.out.println("\033[36m CYAN");
System.out.println("\033[37m WHITE\033[0m");

//printing the results
String leftAlignFormat = "| %-20s | %-7d | %-7d | %-7d |%n";

System.out.format("|---------Test Cases with Steps Summary -------------|%n");
System.out.format("+----------------------+---------+---------+---------+%n");
System.out.format("| Test Cases           |Passed   |Failed   |Skipped  |%n");
System.out.format("+----------------------+---------+---------+---------+%n");

String formattedMessage = "TEST_01".trim();

leftAlignFormat = "| %-20s | %-7d | %-7d | %-7d |%n";
System.out.print("\033[31m"); // Open print red
System.out.printf(leftAlignFormat, formattedMessage, 2, 1, 0);
System.out.print("\033[0m"); // Close print red
System.out.format("+----------------------+---------+---------+---------+%n");
}

Getting the filenames of all files in a folder

Here's how to look in the documentation.

First, you're dealing with IO, so look in the java.io package.

There are two classes that look interesting: FileFilter and FileNameFilter. When I clicked on the first, it showed me that there was a a listFiles() method in the File class. And the documentation for that method says:

Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.

Scrolling up in the File JavaDoc, I see the constructors. And that's really all I need to be able to create a File instance and call listFiles() on it. Scrolling still further, I can see some information about how files are named in different operating systems.

Chrome not rendering SVG referenced via <img> tag

i came here because i had the same problem, when i inspect the element i can see the file, but on the site i can't (even when using localhost)

the answer to my problem was in saving the SVG file. If you saved it from illustrator make sure to click 'embed' and not 'link'. as link will just refer to your local files rather than include the data (If i understand it correctly). enter image description here

I read about it on the adobe website which has some other useful tips for exporting http://www.adobe.com/inspire/2013/09/exporting-svg-illustrator.html

This worked for me, hope it was useful.

How to use global variable in node.js?

global.myNumber; //Delclaration of the global variable - undefined
global.myNumber = 5; //Global variable initialized to value 5. 
var myNumberSquared = global.myNumber * global.myNumber; //Using the global variable. 

Node.js is different from client Side JavaScript when it comes to global variables. Just because you use the word var at the top of your Node.js script does not mean the variable will be accessible by all objects you require such as your 'basic-logger' .

To make something global just put the word global and a dot in front of the variable's name. So if I want company_id to be global I call it global.company_id. But be careful, global.company_id and company_id are the same thing so don't name global variable the same thing as any other variable in any other script - any other script that will be running on your server or any other place within the same code.

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

Apart from all the good answers already given, I'd like to add to @johan-leino's great answer. In my case, for some arbitrary reason, the CodeBehind attribute was omitted from the @Page directive/.aspx file. Likewise, it might be worthwhile to check the CodeFile attribute for @Control directives/.ascx files (obviously in conjunction with an Inherits attribute in both cases).

Depending on the exact scenario and reason required to 'force' a regenerate of .designer.cs, one could also try to format the document (potentially indicating a parsing error) before (quick) saving (regardless whether there were any changes or not) and check the Error List for warnings.

Android, How can I Convert String to Date?

String source = "24/10/17";

String[] sourceSplit= source.split("/");

int anno= Integer.parseInt(sourceSplit[2]);
int mese= Integer.parseInt(sourceSplit[1]);
int giorno= Integer.parseInt(sourceSplit[0]);

    GregorianCalendar calendar = new GregorianCalendar();
  calendar.set(anno,mese-1,giorno);
  Date   data1= calendar.getTime();
  SimpleDateFormat myFormat = new SimpleDateFormat("20yy-MM-dd");

    String   dayFormatted= myFormat.format(data1);

    System.out.println("data formattata,-->"+dayFormatted);

What is the worst programming language you ever worked with?

Cold Fusion

I guess it's good for designers but as a programmer I always felt like one hand was tied behind my back.

How to install Android app on LG smart TV?

LG, VIZIO, SAMSUNG and PANASONIC TVs are not android based, and you cannot run APKs off of them... You should just buy a fire stick and call it a day. The only TVs that are android-based, and you can install APKs are: SONY, PHILIPS and SHARP.
#FACTS.

Setting a windows batch file variable to the day of the week

I Improved Aacini Answer to make it Echo Full day of week Name

So here's my Code

@echo off
for /F "skip=1 tokens=2-4 delims=(-/)" %%A in ('date ^< NUL') do (
   for /F "tokens=1-3 delims=/" %%a in ("%date%") do (
      set %%A=%%a
      set %%B=%%b
      set %%C=%%c
   )
)
set /A mm=10%mm% %% 100, dd=10%dd% %% 100
if %mm% lss 3 set /A mm+=12, yy-=1
set /A a=yy/100, b=a/4, c=4-a+b, e=36525*(yy+4716)/100, f=306*(mm+1)/10,dow=(c+dd+e+f-1523)%%7 + 1
for /F "tokens=%dow%" %%a in ("Sunday Monday Tuesday Wednesday Thursday Friday Saturday ") do set dow=%%a
echo Today is %dow%>"Today is %dow%.txt"
echo Today is %dow%
Pause>Nul

REM Sun Mon Tue Wed Thu Fri Sat
REM Sunday Monday Tuesday Wednesday Thursday Friday Saturday  

SQL Server: combining multiple rows into one row

I believe for databases which support listagg function, you can do:

select id, issue, customfield, parentkey, listagg(stingvalue, ',') within group (order by id)
from jira.customfieldvalue
where customfield = 12534 and issue = 19602
group by id, issue, customfield, parentkey

How to install the Six module in Python2.7

I had the same question for macOS.

But the root cause was not installing Six. My macOS shipped Python version 2.7 was being usurped by a Python2 version I inherited by installing a package via brew.

I fixed my issue with: $ brew uninstall python@2

Some context on here: https://bugs.swift.org/browse/SR-1061

JavaScript backslash (\) in variables is causing an error

The backslash \ is reserved for use as an escape character in Javascript.

To use a backslash literally you need to use two backslashes

\\

How can I install packages using pip according to the requirements.txt file from a local directory?

I had a similar problem. I tried this:

    pip install -U -r requirements.txt

(-U = update if it had already installed)

But the problem continued. I realized that some of generic libraries for development were missed.

    sudo apt-get install libtiff5-dev libjpeg8-dev zlib1g-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev python-tk

I don't know if this would help you.

Best practices with STDIN in Ruby?

You can also use STDIN.each_line, and STDIN.each_line.to_a to get it as an array.

e.g.

STDIN.each_line do |line|
  puts line
end

What's the canonical way to check for type in Python?

The most Pythonic way to check the type of an object is... not to check it.

Since Python encourages Duck Typing, you should just try...except to use the object's methods the way you want to use them. So if your function is looking for a writable file object, don't check that it's a subclass of file, just try to use its .write() method!

Of course, sometimes these nice abstractions break down and isinstance(obj, cls) is what you need. But use sparingly.

How to sign an android apk file

The manual is clear enough. Please specify what part you get stuck with after you work through it, I'd suggest:

https://developer.android.com/studio/publish/app-signing.html

Okay, a small overview without reference or eclipse around, so leave some space for errors, but it works like this

  • Open your project in eclipse
  • Press right-mouse - > tools (android tools?) - > export signed application (apk?)
  • Go through the wizard:
  • Make a new key-store. remember that password
  • Sign your app
  • Save it etc.

Also, from the link:

Compile and sign with Eclipse ADT

If you are using Eclipse with the ADT plugin, you can use the Export Wizard to export a signed .apk (and even create a new keystore, if necessary). The Export Wizard performs all the interaction with the Keytool and Jarsigner for you, which allows you to sign the package using a GUI instead of performing the manual procedures to compile, sign, and align, as discussed above. Once the wizard has compiled and signed your package, it will also perform package alignment with zip align. Because the Export Wizard uses both Keytool and Jarsigner, you should ensure that they are accessible on your computer, as described above in the Basic Setup for Signing.

To create a signed and aligned .apk in Eclipse:

  1. Select the project in the Package Explorer and select File > Export.
  2. Open the Android folder, select Export Android Application, and click Next.

    The Export Android Application wizard now starts, which will guide you through the process of signing your application, including steps for selecting the private key with which to sign the .apk (or creating a new keystore and private key).

  3. Complete the Export Wizard and your application will be compiled, signed, aligned, and ready for distribution.

SQL Server ORDER BY date and nulls last

I know this is old but this is what worked for me

Order by Isnull(Date,'12/31/9999')

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

Your application has an AppCompat theme

<application
    android:theme="@style/AppTheme">

But, you overwrote the Activity (which extends AppCompatActivity) with a theme that isn't descendant of an AppCompat theme

<activity android:name=".MainActivity"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >

You could define your own fullscreen theme like so (notice AppCompat in the parent=)

<style name="AppFullScreenTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowActionBar">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>
</style>

Then set that on the Activity.

<activity android:name=".MainActivity"
    android:theme="@style/AppFullScreenTheme" >

Note: There might be an AppCompat theme that's already full screen, but don't know immediately

.NET Format a string with fixed spaces

Thanks for the discussion, this method also works (VB):

Public Function StringCentering(ByVal s As String, ByVal desiredLength As Integer) As String
    If s.Length >= desiredLength Then Return s
    Dim firstpad As Integer = (s.Length + desiredLength) / 2
    Return s.PadLeft(firstpad).PadRight(desiredLength)
End Function
  1. StringCentering() takes two input values and it returns a formatted string.
  2. When length of s is greater than or equal to deisredLength, the function returns the original string.
  3. When length of s is smaller than desiredLength, it will be padded both ends.
  4. Due to character spacing is integer and there is no half-space, we can have an uneven split of space. In this implementation, the greater split goes to the leading end.
  5. The function requires .NET Framework due to PadLeft() and PadRight().
  6. In the last line of the function, binding is from left to right, so firstpad is applied followed by the desiredLength pad.

Here is the C# version:

public string StringCentering(string s, int desiredLength)
{
    if (s.Length >= desiredLength) return s;
    int firstpad = (s.Length + desiredLength) / 2;
    return s.PadLeft(firstpad).PadRight(desiredLength);
}

To aid understanding, integer variable firstpad is used. s.PadLeft(firstpad) applies the (correct number of) leading white spaces. The right-most PadRight(desiredLength) has a lower binding finishes off by applying trailing white spaces.

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

What's the main difference between int.Parse() and Convert.ToInt32

Parse() methods provide the number styles which cannot be used for Convert(). For example:

int i;
bool b = int.TryParse( "123-",
           System.Globalization.NumberStyles.AllowTrailingSign,
           System.Globalization.CultureInfo.InvariantCulture,
           out i);

would parse the numbers with trailing sign so that i == -123
The trailing sign is popular in ERP systems.

How to parse JSON array in jQuery?

No, with eval is not safe, you can use JSON parser that is much safer: var myObject = JSON.parse(data); For this use the lib https://github.com/douglascrockford/JSON-js

HTML Best Practices: Should I use &rsquo; or the special keyboard shortcut?

If your text will be consumed by non-browsers then it's safer to type the character with the keyboard-combo option shift right bracket because &rsquo; will not be transformed into an apostrophe by a regular XML or JSON parser. (e.g. if you are serving this content to native Android/iOS apps).

What do 3 dots next to a parameter type mean in Java?

Syntax: (Triple dot ... ) --> Means we can add zero or more objects pass in an arguments or pass an array of type object.

public static void main(String[] args){}
public static void main(String... args){}

Definition: 1) The Object ... argument is just a reference to an array of Objects.

2) ('String []' or String ... ) It can able to handle any number of string objects. Internally it uses an array of reference type object.

i.e. Suppose we pass an Object array to the ... argument - will the resultant argument value be a two-dimensional array - because an Object[] is itself an Object:

3) If you want to call the method with a single argument and it happens to be an array, you have to explicitly wrap it in

another. method(new Object[]{array}); 
OR 
method((Object)array), which will auto-wrap.

Application: It majorly used when the number of arguments is dynamic(number of arguments know at runtime) and in overriding. General rule - In the method we can pass any types and any number of arguments. We can not add object(...) arguments before any specific arguments. i.e.

void m1(String ..., String s) this is a wrong approach give syntax error.
void m1(String s, String ...); This is a right approach. Must always give last order prefernces.   

Difference between JSON.stringify and JSON.parse

They are the inverse of each other. JSON.stringify() serializes a JS object into a JSON string, whereas JSON.parse() will deserialize a JSON string into a JS object.

Is there a simple, elegant way to define singletons?

Here's my own implementation of singletons. All you have to do is decorate the class; to get the singleton, you then have to use the Instance method. Here's an example:

@Singleton
class Foo:
   def __init__(self):
       print 'Foo created'

f = Foo() # Error, this isn't how you get the instance of a singleton

f = Foo.instance() # Good. Being explicit is in line with the Python Zen
g = Foo.instance() # Returns already created instance

print f is g # True

And here's the code:

class Singleton:
    """
    A non-thread-safe helper class to ease implementing singletons.
    This should be used as a decorator -- not a metaclass -- to the
    class that should be a singleton.

    The decorated class can define one `__init__` function that
    takes only the `self` argument. Also, the decorated class cannot be
    inherited from. Other than that, there are no restrictions that apply
    to the decorated class.

    To get the singleton instance, use the `instance` method. Trying
    to use `__call__` will result in a `TypeError` being raised.

    """

    def __init__(self, decorated):
        self._decorated = decorated

    def instance(self):
        """
        Returns the singleton instance. Upon its first call, it creates a
        new instance of the decorated class and calls its `__init__` method.
        On all subsequent calls, the already created instance is returned.

        """
        try:
            return self._instance
        except AttributeError:
            self._instance = self._decorated()
            return self._instance

    def __call__(self):
        raise TypeError('Singletons must be accessed through `instance()`.')

    def __instancecheck__(self, inst):
        return isinstance(inst, self._decorated)

Python 3 Online Interpreter / Shell

Ideone supports Python 2.6 and Python 3

IN vs ANY operator in PostgreSQL

(Neither IN nor ANY is an "operator". A "construct" or "syntax element".)

Logically, quoting the manual:

IN is equivalent to = ANY.

But there are two syntax variants of IN and two variants of ANY. Details:

IN taking a set is equivalent to = ANY taking a set, as demonstrated here:

But the second variant of each is not equivalent to the other. The second variant of the ANY construct takes an array (must be an actual array type), while the second variant of IN takes a comma-separated list of values. This leads to different restrictions in passing values and can also lead to different query plans in special cases:

ANY is more versatile

The ANY construct is far more versatile, as it can be combined with various operators, not just =. Example:

SELECT 'foo' LIKE ANY('{FOO,bar,%oo%}');

For a big number of values, providing a set scales better for each:

Related:

Inversion / opposite / exclusion

"Find rows where id is in the given array":

SELECT * FROM tbl WHERE id = ANY (ARRAY[1, 2]);

Inversion: "Find rows where id is not in the array":

SELECT * FROM tbl WHERE id <> ALL (ARRAY[1, 2]);
SELECT * FROM tbl WHERE id <> ALL ('{1, 2}');  -- equivalent array literal
SELECT * FROM tbl WHERE NOT (id = ANY ('{1, 2}'));

All three equivalent. The first with array constructor, the other two with array literal. The data type can be derived from context unambiguously. Else, an explicit cast may be required, like '{1,2}'::int[].

Rows with id IS NULL do not pass either of these expressions. To include NULL values additionally:

SELECT * FROM tbl WHERE (id = ANY ('{1, 2}')) IS NOT TRUE;

Java and SSL - java.security.NoSuchAlgorithmException

Try javax.net.ssl.keyStorePassword instead of javax.net.ssl.keyPassword: the latter isn't mentioned in the JSSE ref guide.

The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmExceptions are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.

You could also use -Djavax.net.debug=ssl, or at least -Djavax.net.debug=ssl,keymanager, to get more debugging information, if the information in the stack trace isn't sufficient.

Error when trying vagrant up

if "Vagrantfile" already exists in this directory. Remove it before running "vagrant init". error shows then

1. rm Vagrantfile
2. vagrant init hashicorp/precise64
3. vagrant up

ERROR 2006 (HY000): MySQL server has gone away

The solution is increasing the values given the wait_timeout and the connect_timeout parameters in your options file, under the [mysqld] tag.

I had to recover a 400MB mysql backup and this worked for me (the values I've used below are a bit exaggerated, but you get the point):

[mysqld]
port=3306
explicit_defaults_for_timestamp = TRUE
connect_timeout = 1000000
net_write_timeout = 1000000
wait_timeout = 1000000
max_allowed_packet = 1024M
interactive_timeout = 1000000
net_buffer_length = 200M
net_read_timeout = 1000000
set GLOBAL delayed_insert_timeout=100000

Blockquote

phpmyadmin logs out after 1440 secs

Follow below steps to increase session timeout for phpmyadmin:

Method 1:

  • Login to phpMyAdmin with your root credentials
  • Select Settings from the top in navigation bar
  • Tap on Features
  • Search for Login cookie validity field in General tab
  • Change the value for this field to something greater than 1440 like 36000 or anything higher.

Make sure whatever value you are entering in Login cookie validity is in seconds

phpmyadmin increase session timeout

Method 2:

Locate your config.inc.php file

For CentOS, Fedora servers:
/etc/phpMyAdmin/config.inc.php

For Ubuntu, Debian servers:
/etc/phpmyadmin/config.inc.php

Search LoginCookieValidity in config.inc.php and increase its value

$cfg['Servers'] [$i] ['LoginCookieValidity'] = 1440;

//change to 
$cfg['Servers'] [$i] ['LoginCookieValidity'] = 36000;

Save the changes to the config.inc.php file and restart your server.

Increase session.gc_maxlifetime in php.ini to be greater than or equal to the value that you entered in config.inc.php.

How to upgrade Angular CLI project?

Just use the build-in feature of Angular CLI

ng update

to update to the latest version.

How to declare global variables in Android?

Like there was discussed above OS could kill the APPLICATION without any notification (there is no onDestroy event) so there is no way to save these global variables.

SharedPreferences could be a solution EXCEPT you have COMPLEX STRUCTURED variables (in my case I had integer array to store the IDs that the user has already handled). The problem with the SharedPreferences is that it is hard to store and retrieve these structures each time the values needed.

In my case I had a background SERVICE so I could move this variables to there and because the service has onDestroy event, I could save those values easily.

Specifing width of a flexbox flex item: width or basis?

The bottom statement is equivalent to:

.half {
   flex-grow: 0;
   flex-shrink: 0;
   flex-basis: 50%;
}

Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.

Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.

I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)

How can you test if an object has a specific property?

I recently switch to set strict-mode -version 2.0 and my null tests failed.

I added a function:

#use in strict mode to validate property exists before using
function exists {
  param($obj,$prop)
  try {
    if ($null -ne $obj[$prop]) {return $true}
    return $false
  } catch {
    return $false
  }
  return $false
}

Now I code

if (exists $run main) { ...

rather than

if ($run.main -ne $null) { ...

and we are on our way. Seems to work on objects and hashtables

As an unintended benefit it is less typing.

How to query first 10 rows and next time query other 10 rows from table

You can use postgresql Cursors

BEGIN;
DECLARE C CURSOR FOR where * FROM msgtable where cdate='18/07/2012';

Then use

FETCH 10 FROM C;

to fetch 10 rows.

Finnish with

COMMIT;

to close the cursor.

But if you need to make a query in different processes, LIMIT and OFFSET as suggested by @Praveen Kumar is better

What is the simplest C# function to parse a JSON string into an object?

I think this is what you want:

JavaScriptSerializer JSS = new JavaScriptSerializer();
T obj = JSS.Deserialize<T>(String);

How to secure an ASP.NET Web API

in continuation to @ Cuong Le's answer , my approach to prevent replay attack would be

// Encrypt the Unix Time at Client side using the shared private key(or user's password)

// Send it as part of request header to server(WEB API)

// Decrypt the Unix Time at Server(WEB API) using the shared private key(or user's password)

// Check the time difference between the Client's Unix Time and Server's Unix Time, should not be greater than x sec

// if User ID/Hash Password are correct and the decrypted UnixTime is within x sec of server time then it is a valid request

Change header background color of modal of twitter bootstrap

All i needed was:

.modal-header{
     background-color:#0f0;
}
.modal-content {
    overflow:hidden;
}

overflow: hidden to keep the color inside the border-radius

Inherit CSS class

As said in previous responses, their is no OOP-like inheritance in CSS. But if you want to reuse a rule-set to apply it to descentants of something, changing properties, and if you can use LESS, try Mixins. To resume on OOP features, it looks like composition.

For instance, you want to apply the .paragraph class which is in a file "text.less" to all p children of paragraphsContainer, and redefine the color property from red to black

text.less file

.paragraph {
    font: arial;
    color: red
}

Do this in an alternativeText.less file

@import (reference) 'text.less';    
div#paragraphsContainer > p {
    .paragraph;
    color: black
}

your.html file

<div id='paragraphsContainer'>
   <p>paragraph 1</p>
   <p>paragraph 2</p>
   <p>paragraph 3</p>
</div>

Please read this answer about defining same css property multiple times

How do I properly clean up Excel interop objects?

I think that some of that is just the way that the framework handles Office applications, but I could be wrong. On some days, some applications clean up the processes immediately, and other days it seems to wait until the application closes. In general, I quit paying attention to the details and just make sure that there aren't any extra processes floating around at the end of the day.

Also, and maybe I'm over simplifying things, but I think you can just...

objExcel = new Excel.Application();
objBook = (Excel.Workbook)(objExcel.Workbooks.Add(Type.Missing));
DoSomeStuff(objBook);
SaveTheBook(objBook);
objBook.Close(false, Type.Missing, Type.Missing);
objExcel.Quit();

Like I said earlier, I don't tend to pay attention to the details of when the Excel process appears or disappears, but that usually works for me. I also don't like to keep Excel processes around for anything other than the minimal amount of time, but I'm probably just being paranoid on that.

Change MySQL default character set to UTF-8 in my.cnf?

Change MySQL character:

Client

default-character-set=utf8

mysqld

character_set_server=utf8

We should not write default-character-set=utf8 in mysqld, because that could result in an error like:

start: Job failed to start

At last:

 +--------------------------+----------------------------+
 | Variable_name            | Value                      |
 +--------------------------+----------------------------+
 | character_set_client     | utf8                       |
 | character_set_connection | utf8                       |
 | character_set_database   | utf8                       |
 | character_set_filesystem | binary                     |
 | character_set_results    | utf8                       |
 | character_set_server     | utf8                       |
 | character_set_system     | utf8                       |
 | character_sets_dir       | /usr/share/mysql/charsets/ |
 +--------------------------+----------------------------+

In SQL, how can you "group by" in ranges?

This will allow you to not have to specify ranges, and should be SQL server agnostic. Math FTW!

SELECT CONCAT(range,'-',range+9), COUNT(range)
FROM (
  SELECT 
    score - (score % 10) as range
  FROM scores
)

fcntl substitute on Windows

The fcntl module is just used for locking the pinning file, so assuming you don't try multiple access, this can be an acceptable workaround. Place this module in your sys.path, and it should just work as the official fcntl module.

Try using this module for development/testing purposes only in windows.

def fcntl(fd, op, arg=0):
    return 0

def ioctl(fd, op, arg=0, mutable_flag=True):
    if mutable_flag:
        return 0
    else:
        return ""

def flock(fd, op):
    return

def lockf(fd, operation, length=0, start=0, whence=0):
    return

Bootstrap Carousel : Remove auto slide

data-interval="false"

Add this to the corresponding div ...

jquery find class and get the value

var myVar = $("#start").find('.myClass').first().val();

How do I set proxy for chrome in python webdriver?

from selenium import webdriver
from selenium.webdriver.common.proxy import *

myProxy = "86.111.144.194:3128"
proxy = Proxy({
    'proxyType': ProxyType.MANUAL,
    'httpProxy': myProxy,
    'ftpProxy': myProxy,
    'sslProxy': myProxy,
    'noProxy':''})

driver = webdriver.Firefox(proxy=proxy)
driver.set_page_load_timeout(30)
driver.get('http://whatismyip.com')

How can I download a file from a URL and save it in Rails?

An even shorter version:

require 'open-uri'
download = open('http://example.com/image.png')
IO.copy_stream(download, '~/image.png')

To keep the same filename:

IO.copy_stream(download, "~/#{download.base_uri.to_s.split('/')[-1]}")

How to use `subprocess` command with pipes

Also, try to use 'pgrep' command instead of 'ps -A | grep 'process_name'

Retrofit 2.0 how to get deserialised error response.body

In Retrofit 2.0 beta2 this is the way that I'm getting error responses:

  1. Synchronous

    try {
       Call<RegistrationResponse> call = backendServiceApi.register(data.in.account, data.in.password,
               data.in.email);
       Response<RegistrationResponse> response = call.execute();
       if (response != null && !response.isSuccess() && response.errorBody() != null) {
           Converter<ResponseBody, BasicResponse> errorConverter =
                   MyApplication.getRestClient().getRetrofitInstance().responseConverter(BasicResponse.class, new Annotation[0]);
           BasicResponse error = errorConverter.convert(response.errorBody());
           //DO ERROR HANDLING HERE
           return;
       }
       RegistrationResponse registrationResponse = response.body();
       //DO SUCCESS HANDLING HERE
    } catch (IOException e) {
       //DO NETWORK ERROR HANDLING HERE
    }
    
  2. Asynchronous

    Call<BasicResponse> call = service.loadRepo();
    call.enqueue(new Callback<BasicResponse>() {
        @Override
        public void onResponse(Response<BasicResponse> response, Retrofit retrofit) {
            if (response != null && !response.isSuccess() && response.errorBody() != null) {
                Converter<ResponseBody, BasicResponse> errorConverter =
                    retrofit.responseConverter(BasicResponse.class, new Annotation[0]);
                BasicResponse error = errorConverter.convert(response.errorBody());
                //DO ERROR HANDLING HERE
                return;
            }
            RegistrationResponse registrationResponse = response.body();
            //DO SUCCESS HANDLING HERE
        }
    
        @Override
        public void onFailure(Throwable t) {
            //DO NETWORK ERROR HANDLING HERE
        }
    });
    

Update for Retrofit 2 beta3:

  1. Synchronous - not changed
  2. Asynchronous - Retrofit parameter was removed from onResponse

    Call<BasicResponse> call = service.loadRepo();
    call.enqueue(new Callback<BasicResponse>() {
        @Override
        public void onResponse(Response<BasicResponse> response) {
            if (response != null && !response.isSuccess() && response.errorBody() != null) {
                Converter<ResponseBody, BasicResponse> errorConverter =
                    MyApplication.getRestClient().getRetrofitInstance().responseConverter(BasicResponse.class, new Annotation[0]);
                BasicResponse error = errorConverter.convert(response.errorBody());
                //DO ERROR HANDLING HERE
                return;
            }
            RegistrationResponse registrationResponse = response.body();
            //DO SUCCESS HANDLING HERE
        }
    
        @Override
        public void onFailure(Throwable t) {
            //DO NETWORK ERROR HANDLING HERE
        }
    });
    

Most Pythonic way to provide global configuration variables in config.py?

How about just using the built-in types like this:

config = {
    "mysql": {
        "user": "root",
        "pass": "secret",
        "tables": {
            "users": "tb_users"
        }
        # etc
    }
}

You'd access the values as follows:

config["mysql"]["tables"]["users"]

If you are willing to sacrifice the potential to compute expressions inside your config tree, you could use YAML and end up with a more readable config file like this:

mysql:
  - user: root
  - pass: secret
  - tables:
    - users: tb_users

and use a library like PyYAML to conventiently parse and access the config file

What is the difference between attribute and property?

Often an attribute is used to describe the mechanism or real-world thing.

A property is used to describe the model.

For instance, a document (sitting on your desk) may have the attribute that it is a draft.

The class that models documents has a property to indicate whether or not it's a draft. In this case the property captures the state.

TNS Protocol adapter error while starting Oracle SQL*Plus

Try

sqlplus sys/<your password>@<your SID> as sysdba

Get hours difference between two dates in Moment Js

 var start=moment(1541243900000);
 var end=moment(1541243942882);
 var duration = moment.duration(end.diff(startTime));
 var hours = duration.asHours();

As you can see, the start and end date needed to be moment objects for this method to work.

E11000 duplicate key error index in mongodb mongoose

This is because there is already a collection with the same name with configuration..Just remove the collection from your mongodb through mongo shell and try again.

db.collectionName.remove()

now run your application it should work

Python: No acceptable C compiler found in $PATH when installing python

The gcc compiler is not in your $PATH. It means either you dont have gcc installed or it's not in your $PATH variable.

To install gcc use this: (run as root)

  • Redhat base:

    yum groupinstall "Development Tools"
    
  • Debian base:

    apt-get install build-essential
    

Internet Explorer 11- issue with security certificate error prompt

If you updated Internet Explorer and began having technical problems, you can use the Compatibility View feature to emulate a previous version of Internet Explorer.

For instructions, see the section below that corresponds with your version. To find your version number, click Help > About Internet Explorer. Internet Explorer 11

To edit the Compatibility View list:

Open the desktop, and then tap or click the Internet Explorer icon on the taskbar.
Tap or click the Tools button (Image), and then tap or click Compatibility View settings.
To remove a website:
Click the website(s) where you would like to turn off Compatibility View, clicking Remove after each one.
To add a website:
Under Add this website, enter the website(s) where you would like to turn on Compatibility View, clicking Add after each one.

How can I change eclipse's Internal Browser from IE to Firefox on Windows XP?

In Preferences -> General -> Web Browser, there is the option "Use internal web browser". Select "Use external web browser" instead and check "Firefox".

What's wrong with overridable method calls in constructors?

On invoking overridable method from constructors

Simply put, this is wrong because it unnecessarily opens up possibilities to MANY bugs. When the @Override is invoked, the state of the object may be inconsistent and/or incomplete.

A quote from Effective Java 2nd Edition, Item 17: Design and document for inheritance, or else prohibit it:

There are a few more restrictions that a class must obey to allow inheritance. Constructors must not invoke overridable methods, directly or indirectly. If you violate this rule, program failure will result. The superclass constructor runs before the subclass constructor, so the overriding method in the subclass will be invoked before the subclass constructor has run. If the overriding method depends on any initialization performed by the subclass constructor, the method will not behave as expected.

Here's an example to illustrate:

public class ConstructorCallsOverride {
    public static void main(String[] args) {

        abstract class Base {
            Base() {
                overrideMe();
            }
            abstract void overrideMe(); 
        }

        class Child extends Base {

            final int x;

            Child(int x) {
                this.x = x;
            }

            @Override
            void overrideMe() {
                System.out.println(x);
            }
        }
        new Child(42); // prints "0"
    }
}

Here, when Base constructor calls overrideMe, Child has not finished initializing the final int x, and the method gets the wrong value. This will almost certainly lead to bugs and errors.

Related questions

See also


On object construction with many parameters

Constructors with many parameters can lead to poor readability, and better alternatives exist.

Here's a quote from Effective Java 2nd Edition, Item 2: Consider a builder pattern when faced with many constructor parameters:

Traditionally, programmers have used the telescoping constructor pattern, in which you provide a constructor with only the required parameters, another with a single optional parameters, a third with two optional parameters, and so on...

The telescoping constructor pattern is essentially something like this:

public class Telescope {
    final String name;
    final int levels;
    final boolean isAdjustable;

    public Telescope(String name) {
        this(name, 5);
    }
    public Telescope(String name, int levels) {
        this(name, levels, false);
    }
    public Telescope(String name, int levels, boolean isAdjustable) {       
        this.name = name;
        this.levels = levels;
        this.isAdjustable = isAdjustable;
    }
}

And now you can do any of the following:

new Telescope("X/1999");
new Telescope("X/1999", 13);
new Telescope("X/1999", 13, true);

You can't, however, currently set only the name and isAdjustable, and leaving levels at default. You can provide more constructor overloads, but obviously the number would explode as the number of parameters grow, and you may even have multiple boolean and int arguments, which would really make a mess out of things.

As you can see, this isn't a pleasant pattern to write, and even less pleasant to use (What does "true" mean here? What's 13?).

Bloch recommends using a builder pattern, which would allow you to write something like this instead:

Telescope telly = new Telescope.Builder("X/1999").setAdjustable(true).build();

Note that now the parameters are named, and you can set them in any order you want, and you can skip the ones that you want to keep at default values. This is certainly much better than telescoping constructors, especially when there's a huge number of parameters that belong to many of the same types.

See also

Related questions

refresh leaflet map: map container is already initialized

Html:

<div id="weathermap"></div>

JavaScript:

function buildMap(lat,lon)  {
    document.getElementById('weathermap').innerHTML = "<div id='map' style='width: 100%; height: 100%;'></div>";
    var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
                    osmAttribution = 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors,' +
                        ' <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>',
    osmLayer = new L.TileLayer(osmUrl, {maxZoom: 18, attribution: osmAttribution});
    var map = new L.Map('map');
    map.setView(new L.LatLng(lat,lon), 9 );
    map.addLayer(osmLayer);
    var validatorsLayer = new OsmJs.Weather.LeafletLayer({lang: 'en'});
    map.addLayer(validatorsLayer);
}

I use this:

document.getElementById('weathermap').innerHTML = "<div id='map' style='width: 100%; height: 100%;'></div>";

to reload content of div where render map.

RAW POST using cURL in PHP

I just found the solution, kind of answering to my own question in case anyone else stumbles upon it.

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,            "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST,           1 );
curl_setopt($ch, CURLOPT_POSTFIELDS,     "body goes here" ); 
curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain')); 

$result=curl_exec ($ch);

Numpy: Creating a complex array from 2 real ones?

There's of course the rather obvious:

Data[...,0] + 1j * Data[...,1]

Powershell: count members of a AD group

How about this?

Get-ADGroupMember 'Group name' | measure-object | select count

What is an .inc and why use it?

Just to add. Another disadvantage would be, .inc files are not recognized by IDE thus, you could not take advantage of auto-complete or code prediction features.

JavaScript, get date of the next day

You can use:

var tomorrow = new Date();
tomorrow.setDate(new Date().getDate()+1);

For example, since there are 30 days in April, the following code will output May 1:

var day = new Date('Apr 30, 2000');
console.log(day); // Apr 30 2000

var nextDay = new Date(day);
nextDay.setDate(day.getDate() + 1);
console.log(nextDay); // May 01 2000    

See fiddle.

ng-if check if array is empty

To overcome the null / undefined issue, try using the ? operator to check existence:

<p ng-if="post?.capabilities?.items?.length > 0">
  • Sidenote, if anyone got to this page looking for an Ionic Framework answer, ensure you use *ngIf:

    <p *ngIf="post?.capabilities?.items?.length > 0">
    

In javascript, how do you search an array for a substring match

I've created a simple to use library (ss-search) which is designed to handle objects, but could also work in your case:

search(windowArray.map(x => ({ key: x }), ["key"], "SEARCH_TEXT").map(x => x.key)

The advantage of using this search function is that it will normalize the text before executing the search to return more accurate results.

Convert a string into an int

I had to do something like this but wanted to use a getter/setter for mine. In particular I wanted to return a long from a textfield. The other answers all worked well also, I just ended up adapting mine a little as my school project evolved.

long ms = [self.textfield.text longLongValue];
return ms;

How to return the output of stored procedure into a variable in sql server

Use this code, Working properly

CREATE PROCEDURE [dbo].[sp_delete_item]
@ItemId int = 0
@status bit OUT

AS
Begin
 DECLARE @cnt int;
 DECLARE @status int =0;
 SET NOCOUNT OFF
 SELECT @cnt =COUNT(Id) from ItemTransaction where ItemId = @ItemId
 if(@cnt = 1)
   Begin
     return @status;
   End
 else
  Begin
   SET @status =1;
    return @status;
 End
END

Execute SP

DECLARE @statuss bit;
EXECUTE  [dbo].[sp_delete_item] 6, @statuss output;
PRINT @statuss;

Removing highcharts.com credits link

Add this to your css.

.highcharts-credits {
display: none !important;
}

Android: How to overlay a bitmap and draw over a bitmap?

If the purpose is to obtain a bitmap, this is very simple:

Canvas canvas = new Canvas();
canvas.setBitmap(image);
canvas.drawBitmap(image2, new Matrix(), null);

In the end, image will contain the overlap of image and image2.

Change the color of a bullet in a html list?

Wrap the text within the list item with a span (or some other element) and apply the bullet color to the list item and the text color to the span.

What are the differences between struct and class in C++?

  1. Member of a class defined with the keyword class are private by default. Members of a class defined with the keywords struct (or union) are public by default.

  2. In absence of an access-specifier for a base class, public is assumed when the derived class is declared struct and private is assumed when the class is declared class.

  3. You can declare an enum class but not an enum struct.

  4. You can use template<class T> but not template<struct T>.

Note also that the C++ standard allows you to forward-declare a type as a struct, and then use class when declaring the type and vice-versa. Also, std::is_class<Y>::value is true for Y being a struct and a class, but is false for an enum class.

Error: package or namespace load failed for ggplot2 and for data.table

Try this:

install.packages('Rcpp')
install.packages('ggplot2')
install.packages('data.table')

Spring MVC Multipart Request with JSON

This is how I implemented Spring MVC Multipart Request with JSON Data.

Multipart Request with JSON Data (also called Mixed Multipart):

Based on RESTful service in Spring 4.0.2 Release, HTTP request with the first part as XML or JSON formatted data and the second part as a file can be achieved with @RequestPart. Below is the sample implementation.

Java Snippet:

Rest service in Controller will have mixed @RequestPart and MultipartFile to serve such Multipart + JSON request.

@RequestMapping(value = "/executesampleservice", method = RequestMethod.POST,
    consumes = {"multipart/form-data"})
@ResponseBody
public boolean executeSampleService(
        @RequestPart("properties") @Valid ConnectionProperties properties,
        @RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file) {
    return projectService.executeSampleService(properties, file);
}

Front End (JavaScript) Snippet:

  1. Create a FormData object.

  2. Append the file to the FormData object using one of the below steps.

    1. If the file has been uploaded using an input element of type "file", then append it to the FormData object. formData.append("file", document.forms[formName].file.files[0]);
    2. Directly append the file to the FormData object. formData.append("file", myFile, "myfile.txt"); OR formData.append("file", myBob, "myfile.txt");
  3. Create a blob with the stringified JSON data and append it to the FormData object. This causes the Content-type of the second part in the multipart request to be "application/json" instead of the file type.

  4. Send the request to the server.

  5. Request Details:
    Content-Type: undefined. This causes the browser to set the Content-Type to multipart/form-data and fill the boundary correctly. Manually setting Content-Type to multipart/form-data will fail to fill in the boundary parameter of the request.

Javascript Code:

formData = new FormData();

formData.append("file", document.forms[formName].file.files[0]);
formData.append('properties', new Blob([JSON.stringify({
                "name": "root",
                "password": "root"                    
            })], {
                type: "application/json"
            }));

Request Details:

method: "POST",
headers: {
         "Content-Type": undefined
  },
data: formData

Request Payload:

Accept:application/json, text/plain, */*
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryEBoJzS3HQ4PgE1QB

------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="file"; filename="myfile.txt"
Content-Type: application/txt


------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="properties"; filename="blob"
Content-Type: application/json


------WebKitFormBoundaryvijcWI2ZrZQ8xEBN--

Java Spring - How to use classpath to specify a file location?

Are we talking about standard java.io.FileReader? Won't work, but it's not hard without it.

/src/main/resources maven directory contents are placed in the root of your CLASSPATH, so you can simply retrieve it using:

InputStream is = getClass().getResourceAsStream("/storedProcedures.sql");

If the result is not null (resource not found), feel free to wrap it in a reader:

Reader reader = new InputStreamReader(is);

Using sessions & session variables in a PHP Login Script

Firstly, the PHP documentation has some excellent information on sessions.

Secondly, you will need some way to store the credentials for each user of your website (e.g. a database). It is a good idea not to store passwords as human-readable, unencrypted plain text. When storing passwords, you should use PHP's crypt() hashing function. This means that if any credentials are compromised, the passwords are not readily available.

Most log-in systems will hash/crypt the password a user enters then compare the result to the hash in the storage system (e.g. database) for the corresponding username. If the hash of the entered password matches the stored hash, the user has entered the correct password.

You can use session variables to store information about the current state of the user - i.e. are they logged in or not, and if they are you can also store their unique user ID or any other information you need readily available.

To start a PHP session, you need to call session_start(). Similarly, to destroy a session and its data, you need to call session_destroy() (for example, when the user logs out):

// Begin the session
session_start();

// Use session variables
$_SESSION['userid'] = $userid;

// E.g. find if the user is logged in
if($_SESSION['userid']) {
    // Logged in
}
else {
    // Not logged in
}

// Destroy the session
if($log_out)
    session_destroy();

I would also recommend that you take a look at this. There's some good, easy to follow information on creating a simple log-in system there.

Difference between window.location.href and top.location.href

The first one adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.

The second replaces the current history item so you can't go back to it.

See window.location:

  • assign(url): Load the document at the provided URL.

  • replace(url): Replace the current document with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.

window.location.href = url;

is favoured over:

window.location = url;

Build project into a JAR automatically in Eclipse

You want a .jardesc file. They do not kick off automatically, but it's within 2 clicks.

  1. Right click on your project
  2. Choose Export > Java > JAR file
  3. Choose included files and name output JAR, then click Next
  4. Check "Save the description of this JAR in the workspace" and choose a name for the new .jardesc file

Now, all you have to do is right click on your .jardesc file and choose Create JAR and it will export it in the same spot.

invalid use of incomplete type

Not exactly what you were asking, but you can make action a template member function:

template<typename Subclass>
class A {
    public:
        //Why doesn't it like this?
        template<class V> void action(V var) {
                (static_cast<Subclass*>(this))->do_action();
        }
};

class B : public A<B> {
    public:
        typedef int mytype;

        B() {}

        void do_action(mytype var) {
                // Do stuff
        }
};

int main(int argc, char** argv) {
    B myInstance;
    return 0;
}

Regular Expression For Duplicate Words

This is the regex I use to remove duplicate phrases in my twitch bot:

(\S+\s*)\1{2,}

(\S+\s*) looks for any string of characters that isn't whitespace, followed whitespace.

\1{2,} then looks for more than 2 instances of that phrase in the string to match. If there are 3 phrases that are identical, it matches.

How to increment a pointer address and pointer's value?

        Note:
        1) Both ++ and * have same precedence(priority), so the associativity comes into picture.
        2) in this case Associativity is from **Right-Left**

        important table to remember in case of pointers and arrays: 

        operators           precedence        associativity

    1)  () , []                1               left-right
    2)  *  , identifier        2               right-left
    3)  <data type>            3               ----------

        let me give an example, this might help;

        char **str;
        str = (char **)malloc(sizeof(char*)*2); // allocate mem for 2 char*
        str[0]=(char *)malloc(sizeof(char)*10); // allocate mem for 10 char
        str[1]=(char *)malloc(sizeof(char)*10); // allocate mem for 10 char

        strcpy(str[0],"abcd");  // assigning value
        strcpy(str[1],"efgh");  // assigning value

        while(*str)
        {
            cout<<*str<<endl;   // printing the string
            *str++;             // incrementing the address(pointer)
                                // check above about the prcedence and associativity
        }
        free(str[0]);
        free(str[1]);
        free(str);

How to write UPDATE SQL with Table alias in SQL Server 2008?

The syntax for using an alias in an update statement on SQL Server is as follows:

UPDATE Q
SET Q.TITLE = 'TEST'
FROM HOLD_TABLE Q
WHERE Q.ID = 101;

The alias should not be necessary here though.

CSS :: child set to change color on parent hover, but changes also when hovered itself

Update

The below made sense for 2013. However, now, I would use the :not() selector as described below.


CSS can be overwritten.

DEMO: http://jsfiddle.net/persianturtle/J4SUb/

Use this:

_x000D_
_x000D_
.parent {
  padding: 50px;
  border: 1px solid black;
}

.parent span {
  position: absolute;
  top: 200px;
  padding: 30px;
  border: 10px solid green;
}

.parent:hover span {
  border: 10px solid red;
}

.parent span:hover {
  border: 10px solid green;
}
_x000D_
<a class="parent">
    Parent text
    <span>Child text</span>    
</a>
_x000D_
_x000D_
_x000D_

How to set up file permissions for Laravel?

First of your answer is.

sudo chmod -R 777/775 /path/project_folder

Now You need to understand permissions and options in ubuntu.

  • chmod - You can set permissions.
  • chown - You can set the ownership of files and directories.
  • 777 - read/write/execute.
  • 775 - read/execute.

getFilesDir() vs Environment.getDataDirectory()

Environment returns user data directory. And getFilesDir returns application data directory.

C# Linq Where Date Between 2 Dates

_x000D_
_x000D_
 public List<tbltask> gettaskssdata(int? c, int? userid, string a, string StartDate, string EndDate, int? ProjectID, int? statusid)_x000D_
        {_x000D_
            List<tbltask> tbtask = new List<tbltask>();_x000D_
            DateTime sdate = (StartDate != "") ? Convert.ToDateTime(StartDate).Date : new DateTime();_x000D_
            DateTime edate = (EndDate != "") ? Convert.ToDateTime(EndDate).Date : new DateTime();_x000D_
            tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser)._x000D_
                Where(x => x.tblproject.company_id == c_x000D_
                    && (ProjectID == 0 || ProjectID == x.tblproject.ProjectId)_x000D_
                    && (statusid == 0 || statusid == x.tblstatu.StatusId)_x000D_
                    && (a == "" || (x.TaskName.Contains(a) || x.tbUser.User_name.Contains(a)))_x000D_
                    && ((StartDate == "" && EndDate == "") || ((x.StartDate >= sdate && x.EndDate <= edate)))).ToList();_x000D_
_x000D_
_x000D_
_x000D_
            return tbtask;_x000D_
_x000D_
_x000D_
        }
_x000D_
_x000D_
_x000D_

this my query for search records based on searchdata and between start to end date

Access denied for user 'root'@'localhost' (using password: YES) after new installation on Ubuntu

The new command to flush the privileges is:

FLUSH PRIVILEGES

The old command FLUSH ALL PRIVILEGES does not work any more.

You will get an error that looks like that:

MariaDB [(none)]> FLUSH ALL PRIVILEGES; ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ALL PRIVILEGES' at line 1

Hope this helps :)

How to use OKHTTP to make a post request?

OkHttp POST request with token in header

       RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("search", "a")
            .addFormDataPart("model", "1")
            .addFormDataPart("in", "1")
            .addFormDataPart("id", "1")
            .build();
    OkHttpClient client = new OkHttpClient();
    okhttp3.Request request = new okhttp3.Request.Builder()
            .url("https://somedomain.com/api")
            .post(requestBody)
            .addHeader("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIkMnkkMTAkZzZrLkwySlFCZlBmN1RTb3g3bmNpTzltcVwvemRVN2JtVC42SXN0SFZtbzZHNlFNSkZRWWRlIiwic3ViIjo0NSwiaWF0IjoxNTUwODk4NDc0LCJleHAiOjE1NTM0OTA0NzR9.tefIaPzefLftE7q0yKI8O87XXATwowEUk_XkAOOQzfw")
            .addHeader("cache-control", "no-cache")
            .addHeader("Postman-Token", "7e231ef9-5236-40d1-a28f-e5986f936877")
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, okhttp3.Response response) throws IOException {
            if (response.isSuccessful()) {
                final String myResponse = response.body().string();

                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("response", myResponse);
                        progress.hide();
                    }
                });
            }
        }
    });

How to install PyQt4 on Windows using pip?

install PyQt5 for Windows 10 and python 3.5+.

pip install PyQt5

using batch echo with special characters

The answer from Joey was not working for me. After executing

  echo ^<?xml version="1.0" encoding="utf-8" ?^> > myfile.xml

I got this error bash: syntax error near unexpected token `>'

This solution worked for me:

 echo "<?xml version=\"1.0\" encoding=\"utf-8\">" > myfile.txt

See also http://www.robvanderwoude.com/escapechars.php

Filter values only if not null using lambda in Java8

In this particular example I think @Tagir is 100% correct get it into one filter and do the two checks. I wouldn't use Optional.ofNullable the Optional stuff is really for return types not to be doing logic... but really neither here nor there.

I wanted to point out that java.util.Objects has a nice method for this in a broad case, so you can do this:

cars.stream()
    .filter(Objects::nonNull)

Which will clear out your null objects. For anyone not familiar, that's the short-hand for the following:

cars.stream()
    .filter(car -> Objects.nonNull(car))

To partially answer the question at hand to return the list of car names that starts with "M":

cars.stream()
    .filter(car -> Objects.nonNull(car))
    .map(car -> car.getName())
    .filter(carName -> Objects.nonNull(carName))
    .filter(carName -> carName.startsWith("M"))
    .collect(Collectors.toList());

Once you get used to the shorthand lambdas you could also do this:

cars.stream()
    .filter(Objects::nonNull)
    .map(Car::getName)        // Assume the class name for car is Car
    .filter(Objects::nonNull)
    .filter(carName -> carName.startsWith("M"))
    .collect(Collectors.toList());

Unfortunately once you .map(Car::getName) you'll only be returning the list of names, not the cars. So less beautiful but fully answers the question:

cars.stream()
    .filter(car -> Objects.nonNull(car))
    .filter(car -> Objects.nonNull(car.getName()))
    .filter(car -> car.getName().startsWith("M"))
    .collect(Collectors.toList());

Change date format in a Java string

SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-mm-dd");

List only stopped Docker containers

docker container list -f "status=exited"

or

docker container ls -f "status=exited"

or

 docker ps -f "status=exited"

How to loop through a HashMap in JSP?

Just the same way as you would do in normal Java code.

for (Map.Entry<String, String> entry : countries.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();
    // ...
}

However, scriptlets (raw Java code in JSP files, those <% %> things) are considered a poor practice. I recommend to install JSTL (just drop the JAR file in /WEB-INF/lib and declare the needed taglibs in top of JSP). It has a <c:forEach> tag which can iterate over among others Maps. Every iteration will give you a Map.Entry back which in turn has getKey() and getValue() methods.

Here's a basic example:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:forEach items="${map}" var="entry">
    Key = ${entry.key}, value = ${entry.value}<br>
</c:forEach>

Thus your particular issue can be solved as follows:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<select name="country">
    <c:forEach items="${countries}" var="country">
        <option value="${country.key}">${country.value}</option>
    </c:forEach>
</select>

You need a Servlet or a ServletContextListener to place the ${countries} in the desired scope. If this list is supposed to be request-based, then use the Servlet's doGet():

protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    Map<String, String> countries = MainUtils.getCountries();
    request.setAttribute("countries", countries);
    request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
}

Or if this list is supposed to be an application-wide constant, then use ServletContextListener's contextInitialized() so that it will be loaded only once and kept in memory:

public void contextInitialized(ServletContextEvent event) {
    Map<String, String> countries = MainUtils.getCountries();
    event.getServletContext().setAttribute("countries", countries);
}

In both cases the countries will be available in EL by ${countries}.

Hope this helps.

See also:

jQuery AJAX Character Encoding

If the whole application is using ISO-8859-1, you can modify your jquery.js replacing all occurences of encodeURIComponent by escape (there are 2 occurrences to replace in the current jquery script - 1.5.1)

See encodeUIComponent and escape for more information

What is the difference between <p> and <div>?

They have semantic difference - a <div> element is designed to describe a container of data whereas a <p> element is designed to describe a paragraph of content.

The semantics make all the difference. HTML is a markup language which means that it is designed to "mark up" content in a way that is meaningful to the consumer of the markup. Most developers believe that the semantics of the document are the default styles and rendering that browsers apply to these elements but that is not the case.

The elements that you choose to mark up your content should describe the content. Don't mark up your document based on how it should look - mark it up based on what it is.

If you need a generic container purely for layout purposes then use a <div>. If you need an element to describe a paragraph of content then use a <p>.

Note: It is important to understand that both <div> and <p> are block-level elements which means that most browsers will treat them in a similar fashion.

How to change date format using jQuery?

I dont think you need to use jQuery at all, just simple JavaScript...

Save the date as a string:

dte = fecha.value;//2014-01-06

Split the string to get the day, month & year values...

dteSplit = dte.split("-");
yr = dteSplit[0][2] + dteSplit[0][3]; //special yr format, take last 2 digits
month = dteSplit[1];
day = dteSplit[2];

Rejoin into final date string:

finalDate = month+"-"+day+"-"+year

How to include js and CSS in JSP with spring MVC

First you need to declare your resources in dispatcher-servlet file like this :

<mvc:resources mapping="/resources/**" location="/resources/folder/" />

Any request with url mapping /resources/** will directly look for /resources/folder/.

Now in jsp file you need to include your css file like this :

<link href="<c:url value="/resources/css/main.css" />" rel="stylesheet">

Similarly you can include js files.

Hope this solves your problem.

Is there a simple way to use button to navigate page as a link does in angularjs

Your ngClick is correct; you just need the right service. $location is what you're looking for. Check out the docs for the full details, but the solution to your specific question is this:

$location.path( '/new-page.html' );

The $location service will add the hash (#) if it's appropriate based on your current settings and ensure no page reload occurs.

You could also do something more flexible with a directive if you so chose:

.directive( 'goClick', function ( $location ) {
  return function ( scope, element, attrs ) {
    var path;

    attrs.$observe( 'goClick', function (val) {
      path = val;
    });

    element.bind( 'click', function () {
      scope.$apply( function () {
        $location.path( path );
      });
    });
  };
});

And then you could use it on anything:

<button go-click="/go/to/this">Click!</button>

There are many ways to improve this directive; it's merely to show what could be done. Here's a Plunker demonstrating it in action: http://plnkr.co/edit/870E3psx7NhsvJ4mNcd2?p=preview.

How can I get the concatenation of two lists in Python without modifying either one?

Yes: list1 + list2. This gives a new list that is the concatenation of list1 and list2.

Resource interpreted as Document but transferred with MIME type application/zip

I could not find anywhere just an explanation of the message by itself. Here is my interpretation.

As far as I understand, Chrome was expecting some material it could possibly display (a document), but it obtained something it could not display (or something it was told not to display).

This is both a question of how the document was declared at the HTML page level in href (see the download attribute in Roy's message) and how it is declared within the server's answer by the means of HTTP headers (in particular Content-Disposition). This is a question of contract, as opposed to hope and expectation.

To continue on Evan's way, I've experienced that:

Content-type: application/pdf
Content-disposition: attachment; filename=some.pdf

is just inconsistent with:

<a href='some.pdf'>

Chrome will cry Resource interpreted as document but transferred…

Actually, the attachment disposition just means this: the browser shall not interpret the link, but rather store it somewhere for other—hidden—purposes. Here above, either download is missing beside href, or Content-disposition must be removed from the headers. It depends on whether we want the browser to render the document or not.

Hope this helps.

Why would one omit the close tag?

According to the docs, it's preferable to omit the closing tag if it's at the end of the file for the following reason:

If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.

PHP Manual > Language Reference > Basic syntax > PHP tags

Loop through an array in JavaScript

In JavaScript, there are so many solutions to loop an array.

The code below are popular ones

_x000D_
_x000D_
/** Declare inputs */_x000D_
const items = ['Hello', 'World']_x000D_
_x000D_
/** Solution 1. Simple for */_x000D_
console.log('solution 1. simple for')_x000D_
_x000D_
for (let i = 0; i < items.length; i++) {_x000D_
  console.log(items[i])_x000D_
}_x000D_
_x000D_
console.log()_x000D_
console.log()_x000D_
_x000D_
/** Solution 2. Simple while */_x000D_
console.log('solution 2. simple while')_x000D_
_x000D_
let i = 0_x000D_
while (i < items.length) {_x000D_
  console.log(items[i++])_x000D_
}_x000D_
_x000D_
console.log()_x000D_
console.log()_x000D_
_x000D_
/** Solution 3. forEach*/_x000D_
console.log('solution 3. forEach')_x000D_
_x000D_
items.forEach(item => {_x000D_
  console.log(item)_x000D_
})_x000D_
_x000D_
console.log()_x000D_
console.log()_x000D_
_x000D_
/** Solution 4. for-of*/_x000D_
console.log('solution 4. for-of')_x000D_
_x000D_
for (const item of items) {_x000D_
  console.log(item)_x000D_
}_x000D_
_x000D_
console.log()_x000D_
console.log()
_x000D_
_x000D_
_x000D_

How to convert array into comma separated string in javascript

Use the join method from the Array type.

a.value = [a, b, c, d, e, f];
var stringValueYouWant = a.join();

The join method will return a string that is the concatenation of all the array elements. It will use the first parameter you pass as a separator - if you don't use one, it will use the default separator, which is the comma.

How to check if a string contains an element from a list in Python

This is a variant of the list comprehension answer given by @psun.

By switching the output value, you can actually extract the matching pattern from the list comprehension (something not possible with the any() approach by @Lauritz-v-Thaulow)

extensionsToCheck = ['.pdf', '.doc', '.xls']
url_string = 'http://.../foo.doc'

print [extension for extension in extensionsToCheck if(extension in url_string)]

['.doc']`

You can furthermore insert a regular expression if you want to collect additional information once the matched pattern is known (this could be useful when the list of allowed patterns is too long to write into a single regex pattern)

print [re.search(r'(\w+)'+extension, url_string).group(0) for extension in extensionsToCheck if(extension in url_string)]

['foo.doc']

Filter Linq EXCEPT on properties

MoreLinq has something useful for this MoreLinq.Source.MoreEnumerable.ExceptBy

https://github.com/gsscoder/morelinq/blob/master/MoreLinq/ExceptBy.cs

namespace MoreLinq
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    static partial class MoreEnumerable
    {
        /// <summary>
        /// Returns the set of elements in the first sequence which aren't
        /// in the second sequence, according to a given key selector.
        /// </summary>
        /// <remarks>
        /// This is a set operation; if multiple elements in <paramref name="first"/> have
        /// equal keys, only the first such element is returned.
        /// This operator uses deferred execution and streams the results, although
        /// a set of keys from <paramref name="second"/> is immediately selected and retained.
        /// </remarks>
        /// <typeparam name="TSource">The type of the elements in the input sequences.</typeparam>
        /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
        /// <param name="first">The sequence of potentially included elements.</param>
        /// <param name="second">The sequence of elements whose keys may prevent elements in
        /// <paramref name="first"/> from being returned.</param>
        /// <param name="keySelector">The mapping from source element to key.</param>
        /// <returns>A sequence of elements from <paramref name="first"/> whose key was not also a key for
        /// any element in <paramref name="second"/>.</returns>

        public static IEnumerable<TSource> ExceptBy<TSource, TKey>(this IEnumerable<TSource> first,
            IEnumerable<TSource> second,
            Func<TSource, TKey> keySelector)
        {
            return ExceptBy(first, second, keySelector, null);
        }

        /// <summary>
        /// Returns the set of elements in the first sequence which aren't
        /// in the second sequence, according to a given key selector.
        /// </summary>
        /// <remarks>
        /// This is a set operation; if multiple elements in <paramref name="first"/> have
        /// equal keys, only the first such element is returned.
        /// This operator uses deferred execution and streams the results, although
        /// a set of keys from <paramref name="second"/> is immediately selected and retained.
        /// </remarks>
        /// <typeparam name="TSource">The type of the elements in the input sequences.</typeparam>
        /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
        /// <param name="first">The sequence of potentially included elements.</param>
        /// <param name="second">The sequence of elements whose keys may prevent elements in
        /// <paramref name="first"/> from being returned.</param>
        /// <param name="keySelector">The mapping from source element to key.</param>
        /// <param name="keyComparer">The equality comparer to use to determine whether or not keys are equal.
        /// If null, the default equality comparer for <c>TSource</c> is used.</param>
        /// <returns>A sequence of elements from <paramref name="first"/> whose key was not also a key for
        /// any element in <paramref name="second"/>.</returns>

        public static IEnumerable<TSource> ExceptBy<TSource, TKey>(this IEnumerable<TSource> first,
            IEnumerable<TSource> second,
            Func<TSource, TKey> keySelector,
            IEqualityComparer<TKey> keyComparer)
        {
            if (first == null) throw new ArgumentNullException("first");
            if (second == null) throw new ArgumentNullException("second");
            if (keySelector == null) throw new ArgumentNullException("keySelector");
            return ExceptByImpl(first, second, keySelector, keyComparer);
        }

        private static IEnumerable<TSource> ExceptByImpl<TSource, TKey>(this IEnumerable<TSource> first,
            IEnumerable<TSource> second,
            Func<TSource, TKey> keySelector,
            IEqualityComparer<TKey> keyComparer)
        {
            var keys = new HashSet<TKey>(second.Select(keySelector), keyComparer);
            foreach (var element in first)
            {
                var key = keySelector(element);
                if (keys.Contains(key))
                {
                    continue;
                }
                yield return element;
                keys.Add(key);
            }
        }
    }
}

Why am I seeing net::ERR_CLEARTEXT_NOT_PERMITTED errors after upgrading to Cordova Android 8?

The default API level in the Cordova Android platform has been upgraded. On an Android 9 device, clear text communication is now disabled by default.

To allow clear text communication again, set the android:usesCleartextTraffic on your application tag to true:

<platform name="android">
  <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application">
      <application android:usesCleartextTraffic="true" />
  </edit-config>
</platform>

As noted in the comments, if you have not defined the android XML namespace previously, you will receive an error: unbound prefix during build. This indicates that you need to add it to your widget tag in the same config.xml, like so:

<widget id="you-app-id" version="1.2.3"
xmlns="http://www.w3.org/ns/widgets" 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cdv="http://cordova.apache.org/ns/1.0">

How to find a parent with a known class in jQuery?

You can use parents() to get all parents with the given selector.

Description: Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.

But parent() will get just the first parent of the element.

Description: Get the parent of each element in the current set of matched elements, optionally filtered by a selector.

jQuery parent() vs. parents()

And there is .parentsUntil() which I think will be the best.

Description: Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector.

How to force reloading a page when using browser back button?

Use following meta tag in your html header file, This works for me.

<meta http-equiv="Pragma" content="no-cache">

MySql Table Insert if not exist otherwise update

I had a situation where I needed to update or insert on a table according to two fields (both foreign keys) on which I couldn't set a UNIQUE constraint (so INSERT ... ON DUPLICATE KEY UPDATE won't work). Here's what I ended up using:

replace into last_recogs (id, hasher_id, hash_id, last_recog) 
  select l.* from 
    (select id, hasher_id, hash_id, [new_value] from last_recogs 
     where hasher_id in (select id from hashers where name=[hasher_name])
     and hash_id in (select id from hashes where name=[hash_name]) 
     union 
     select 0, m.id, h.id, [new_value] 
     from hashers m cross join hashes h 
     where m.name=[hasher_name] 
     and h.name=[hash_name]) l 
  limit 1;

This example is cribbed from one of my databases, with the input parameters (two names and a number) replaced with [hasher_name], [hash_name], and [new_value]. The nested SELECT...LIMIT 1 pulls the first of either the existing record or a new record (last_recogs.id is an autoincrement primary key) and uses that as the value input into the REPLACE INTO.

Span inside anchor or anchor inside span or doesn't matter?

Semantically I think makes more sense as is a container for a single element and if you need to nest them then that suggests more than element will be inside of the outer one.

Java BigDecimal: Round to the nearest whole value

I don't think you can round it like that in a single command. Try

    ArrayList<BigDecimal> list = new ArrayList<BigDecimal>();
    list.add(new BigDecimal("100.12"));
    list.add(new BigDecimal("100.44"));
    list.add(new BigDecimal("100.50"));
    list.add(new BigDecimal("100.75"));

    for (BigDecimal bd : list){
        System.out.println(bd+" -> "+bd.setScale(0,RoundingMode.HALF_UP).setScale(2));
    }

Output:
100.12 -> 100.00
100.44 -> 100.00
100.50 -> 101.00
100.75 -> 101.00

I tested for the rest of your examples and it returns the wanted values, but I don't guarantee its correctness.

Convert categorical data in pandas dataframe

Answers here seem outdated. Pandas now has a factorize() function and you can create categories as:

df.col.factorize() 

Function signature:

pandas.factorize(values, sort=False, na_sentinel=- 1, size_hint=None)

What is &amp used for

if you're doing a string of characters. make:

let linkGoogle = 'https://www.google.com/maps/dir/?api=1'; 
let origin = '&origin=' + locations[0][1] + ',' + locations[0][2];


aNav.href = linkGoogle + origin;

How to support HTTP OPTIONS verb in ASP.NET MVC/WebAPI application

    protected void Application_EndRequest()
    {
        if (Context.Response.StatusCode == 405 && Context.Request.HttpMethod == "OPTIONS" )
        {
            Response.Clear();
            Response.StatusCode = 200;
            Response.End();
        }
    }

Codeigniter: does $this->db->last_query(); execute a query?

The query execution happens on all get methods like

$this->db->get('table_name');
$this->db->get_where('table_name',$array);

While last_query contains the last query which was run

$this->db->last_query();

If you want to get query string without execution you will have to do this. Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions

public function _compile_select($select_override = FALSE)
public function _reset_select()

Now you can write query and get it in a variable

$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();

Now reset query so if you want to write another query the object will be cleared.

$this->db->_reset_select();

And the thing is done. Cheers!!! Note : While using this way you must use

$this->db->from('myTable')

instead of

$this->db->get('myTable')

which runs the query.

Take a look at this example

SQL Inner Join On Null Values

You could also use the coalesce function. I tested this in PostgreSQL, but it should also work for MySQL or MS SQL server.

INNER JOIN x ON coalesce(x.qid, -1) = coalesce(y.qid, -1)

This will replace NULL with -1 before evaluating it. Hence there must be no -1 in qid.

Signtool error: No certificates were found that met all given criteria with a Windows Store App?

Try with /debug.1,2 As in :

signtool sign /debug /f mypfxfile.pfx /p <password> (mydllexectuable).exe

It will help you find out what is going on. You should get output like this:

The following certificates were considered:
    Issued to: <issuer>
    Issued by: <certificate authority> Class 2 Primary Intermediate Server CA
    Expires:   Sun Mar 01 14:18:23 2015
    SHA1 hash: DD0000000000000000000000000000000000D93E

    Issued to: <certificate authority> Certification Authority
    Issued by: <certificate authority> Certification Authority
    Expires:   Wed Sep 17 12:46:36 2036
    SHA1 hash: 3E0000000000000000000000000000000000000F

After EKU filter, 2 certs were left.
After expiry filter, 2 certs were left.
After Private Key filter, 0 certs were left.
SignTool Error: No certificates were found that met all the given criteria.

You can see what filter is causing your certificate to not work, or if no certificates were considered.

I changed the hashes and other info, but you should get the idea. Hope this helps.


1 Please note: signtool is particular about where the /debug option is placed. It needs to go after the sign statement.
2 Also note: the /debug option only works with some versions of signtool. The WDK version has the option, whereas the Windows SDK version does not.

Java constructor/method with optional parameters?

Java doesn't support default parameters. You will need to have two constructors to do what you want.

An alternative if there are lots of possible values with defaults is to use the Builder pattern, whereby you use a helper object with setters.

e.g.

   public class Foo {
     private final String param1;
     private final String param2;

     private Foo(Builder builder) {
       this.param1 = builder.param1;
       this.param2 = builder.param2;
     }
     public static class Builder {
       private String param1 = "defaultForParam1";
       private String param2 = "defaultForParam2";

       public Builder param1(String param1) {
         this.param1 = param1;
         return this;
       }
       public Builder param2(String param1) {
         this.param2 = param2;
         return this;
       }
       public Foo build() {
         return new Foo(this);
       }
     }
   }

which allows you to say:

Foo myFoo = new Foo.Builder().param1("myvalue").build();

which will have a default value for param2.

What is a .NET developer?

Most .NET jobs I've run across also either explicitly or implicitly assume some knowledge of SQL-based RDBMSes. While it's not "part of the description", it's usually part of the job.

How do I evenly add space between a label and the input field regardless of length of text?

You can also used below code

<html>
<head>
    <style>
        .labelClass{
            float: left;
            width: 113px;
        }
    </style>
</head>
<body>
  <form action="yourclassName.jsp">
    <span class="labelClass">First name: </span><input type="text" name="fname"><br>
    <span class="labelClass">Last name: </span><input type="text" name="lname"><br>
    <input type="submit" value="Submit">
  </form>
</body>
</html>

How can I call PHP functions by JavaScript?

If you actually want to send data to a php script for example you can do this:

The php:

<?php
$a = $_REQUEST['a'];
$b = $_REQUEST['b']; //totally sanitized

echo $a + $b;
?>

Js (using jquery):

$.post("/path/to/above.php", {a: something, b: something}, function(data){                                          
  $('#somediv').html(data);
});

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

Along the same lines as previous answers, but a very short addition that Allows to use all Control properties without having cross thread invokation exception.

Helper Method

/// <summary>
/// Helper method to determin if invoke required, if so will rerun method on correct thread.
/// if not do nothing.
/// </summary>
/// <param name="c">Control that might require invoking</param>
/// <param name="a">action to preform on control thread if so.</param>
/// <returns>true if invoke required</returns>
public bool ControlInvokeRequired(Control c, Action a)
{
    if (c.InvokeRequired) c.Invoke(new MethodInvoker(delegate
    {
        a();
    }));
    else return false;

    return true;
}

Sample Usage

// usage on textbox
public void UpdateTextBox1(String text)
{
    //Check if invoke requied if so return - as i will be recalled in correct thread
    if (ControlInvokeRequired(textBox1, () => UpdateTextBox1(text))) return;
    textBox1.Text = ellapsed;
}

//Or any control
public void UpdateControl(Color c, String s)
{
    //Check if invoke requied if so return - as i will be recalled in correct thread
    if (ControlInvokeRequired(myControl, () => UpdateControl(c, s))) return;
    myControl.Text = s;
    myControl.BackColor = c;
}

How to escape apostrophe (') in MySql?

The MySQL documentation you cite actually says a little bit more than you mention. It also says,

A “'” inside a string quoted with “'” may be written as “''”.

(Also, you linked to the MySQL 5.0 version of Table 8.1. Special Character Escape Sequences, and the current version is 5.6 — but the current Table 8.1. Special Character Escape Sequences looks pretty similar.)

I think the Postgres note on the backslash_quote (string) parameter is informative:

This controls whether a quote mark can be represented by \' in a string literal. The preferred, SQL-standard way to represent a quote mark is by doubling it ('') but PostgreSQL has historically also accepted \'. However, use of \' creates security risks...

That says to me that using a doubled single-quote character is a better overall and long-term choice than using a backslash to escape the single-quote.

Now if you also want to add choice of language, choice of SQL database and its non-standard quirks, and choice of query framework to the equation, then you might end up with a different choice. You don't give much information about your constraints.

Official reasons for "Software caused connection abort: socket write error"

ssl client side will throw such exception in below situation(I had tested), :

server is asked to authenticate client certificate, but the client provide a certificate which Extended Key Usage donot support client auth.

What are the obj and bin folders (created by Visual Studio) used for?

I would encourage you to see this youtube video which demonstrates the difference between C# bin and obj folders and also explains how we get the benefit of incremental/conditional compilation.

C# compilation is a two-step process, see the below diagram for more details:

  1. Compiling: In compiling phase individual C# code files are compiled into individual compiled units. These individual compiled code files go in the OBJ directory.
  2. Linking: In the linking phase these individual compiled code files are linked to create single unit DLL and EXE. This goes in the BIN directory.

C# bin vs obj folders

If you compare both bin and obj directory you will find greater number of files in the "obj" directory as it has individual compiled code files while "bin" has a single unit.

bin vs obj

ssh "permissions are too open" error

This is what worked for me (on mac)

sudo chmod 600 path_to_your_key.pem 

then :

ssh -i path_to_your_key user@server_ip

Hope it help

correct way of comparing string jquery operator =

First of all you should use double "==" instead of "=" to compare two values. Using "=" You assigning value to variable in this case "somevar"

Update Git submodule to latest commit on origin

Your main project points to a particular commit that the submodule should be at. git submodule update tries to check out that commit in each submodule that has been initialized. The submodule is really an independent repository - just creating a new commit in the submodule and pushing that isn't enough. You also need to explicitly add the new version of the submodule in the main project.

So, in your case, you should find the right commit in the submodule - let's assume that's the tip of master:

cd mod
git checkout master
git pull origin master

Now go back to the main project, stage the submodule and commit that:

cd ..
git add mod
git commit -m "Updating the submodule 'mod' to the latest version"

Now push your new version of the main project:

git push origin master

From this point on, if anyone else updates their main project, then git submodule update for them will update the submodule, assuming it's been initialized.

Using BETWEEN in CASE SQL statement

You do not specify why you think it is wrong but I can se two dangers:

BETWEEN can be implemented differently in different databases sometimes it is including the border values and sometimes excluding, resulting in that 1 and 31 of january would end up NOTHING. You should test how you database does this.

Also, if RATE_DATE contains hours also 2010-01-31 might be translated to 2010-01-31 00:00 which also would exclude any row with an hour other that 00:00.

plot a circle with pyplot

I see plots with the use of (.circle) but based on what you might want to do you can also try this out:

import matplotlib.pyplot as plt
import numpy as np

x = list(range(1,6))
y = list(range(10, 20, 2))

print(x, y)

for i, data in enumerate(zip(x,y)):
    j, k = data
    plt.scatter(j,k, marker = "o", s = ((i+1)**4)*50, alpha = 0.3)

Simple concentric circle plot using linear progressing points

centers = np.array([[5,18], [3,14], [7,6]])
m, n = make_blobs(n_samples=20, centers=[[5,18], [3,14], [7,6]], n_features=2, 
cluster_std = 0.4)
colors = ['g', 'b', 'r', 'm']

plt.figure(num=None, figsize=(7,6), facecolor='w', edgecolor='k')
plt.scatter(m[:,0], m[:,1])

for i in range(len(centers)):

    plt.scatter(centers[i,0], centers[i,1], color = colors[i], marker = 'o', s = 13000, alpha = 0.2)
    plt.scatter(centers[i,0], centers[i,1], color = 'k', marker = 'x', s = 50)

plt.savefig('plot.png')

Circled points of a classification problem.

How to check size of a file using Bash?

[ -n file.txt ] doesn't check its size, it checks that the string file.txt is non-zero length, so it will always succeed.

If you want to say "size is non-zero", you need [ -s file.txt ].

To get a file's size, you can use wc -c to get the size (file length) in bytes:

file=file.txt
minimumsize=90000
actualsize=$(wc -c <"$file")
if [ $actualsize -ge $minimumsize ]; then
    echo size is over $minimumsize bytes
else
    echo size is under $minimumsize bytes
fi

In this case, it sounds like that's what you want.

But FYI, if you want to know how much disk space the file is using, you could use du -k to get the size (disk space used) in kilobytes:

file=file.txt
minimumsize=90
actualsize=$(du -k "$file" | cut -f 1)
if [ $actualsize -ge $minimumsize ]; then
    echo size is over $minimumsize kilobytes
else
    echo size is under $minimumsize kilobytes
fi

If you need more control over the output format, you can also look at stat. On Linux, you'd start with something like stat -c '%s' file.txt, and on BSD/Mac OS X, something like stat -f '%z' file.txt.

Angular 2 - Setting selected value on dropdown list

If your values are coming from the database, show selected values in that way.

<div class="form-group">
    <label for="status">Status</label>
    <select class="form-control" name="status" [(ngModel)]="category.status">
       <option [value]="1" [selected]="category.status ==1">Active</option>
       <option [value]="0" [selected]="category.status ==0">In Active</option>
    </select>
</div>

What is tail recursion?

In traditional recursion, the typical model is that you perform your recursive calls first, and then you take the return value of the recursive call and calculate the result. In this manner, you don't get the result of your calculation until you have returned from every recursive call.

In tail recursion, you perform your calculations first, and then you execute the recursive call, passing the results of your current step to the next recursive step. This results in the last statement being in the form of (return (recursive-function params)). Basically, the return value of any given recursive step is the same as the return value of the next recursive call.

The consequence of this is that once you are ready to perform your next recursive step, you don't need the current stack frame any more. This allows for some optimization. In fact, with an appropriately written compiler, you should never have a stack overflow snicker with a tail recursive call. Simply reuse the current stack frame for the next recursive step. I'm pretty sure Lisp does this.

How to compute the sum and average of elements in an array?

If anyone ever needs it - Here is a recursive average.

In the context of the original question, you may want to use the recursive average if you allowed the user to insert additional values and, without incurring the cost of visiting each element again, wanted to "update" the existing average.

/**
 * Computes the recursive average of an indefinite set
 * @param {Iterable<number>} set iterable sequence to average
 * @param {number} initAvg initial average value
 * @param {number} initCount initial average count
 */
function average(set, initAvg, initCount) {
  if (!set || !set[Symbol.iterator])
    throw Error("must pass an iterable sequence");

  let avg = initAvg || 0;
  let avgCnt = initCount || 0;
  for (let x of set) {
    avgCnt += 1;
    avg = avg * ((avgCnt - 1) / avgCnt) + x / avgCnt;
  }
  return avg; // or {avg: avg, count: avgCnt};
}

average([2, 4, 6]);    //returns 4
average([4, 6], 2, 1); //returns 4
average([6], 3, 2);    //returns 4
average({
  *[Symbol.iterator]() {
    yield 2; yield 4; yield 6;
  }
});                    //returns 4

How:

this works by maintaining the current average and element count. When a new value is to be included you increment count by 1, scale the existing average by (count-1) / count, and add newValue / count to the average.

Benefits:

  • you don't sum all the elements, which may result in large number that cannot be stored in a 64-bit float.
  • you can "update" an existing average if additional values become available.
  • you can perform a rolling average without knowing the sequence length.

Downsides:

  • incurs lots more divisions
  • not infinite - limited to Number.MAX_SAFE_INTEGER items unless you employ BigNumber

How to position two divs horizontally within another div

I agree with Darko Z on applying "overflow: hidden" to #sub-title. However, it should be mentioned that the overflow:hidden method of clearing floats does not work with IE6 unless you have a specified width or height. Or, if you don't want to specify a width or height, you can use "zoom: 1":

#sub-title { overflow:hidden; zoom: 1; }

Retrieving JSON Object Literal from HttpServletRequest

The easiest way is to populate your bean would be from a Reader object, this can be done in a single call:

BufferedReader reader = request.getReader();
Gson gson = new Gson();

MyBean myBean = gson.fromJson(reader, MyBean.class);

Select first occurring element after another element

Simplyfing for the begginers:

If you want to select an element immediatly after another element you use the + selector.

For example:

div + p The "+" element selects all <p> elements that are placed immediately after <div> elements


If you want to learn more about selectors use this table

Wait until page is loaded with Selenium WebDriver for Python

use this in code :

from selenium import webdriver

driver = webdriver.Firefox() # or Chrome()
driver.implicitly_wait(10) # seconds
driver.get("http://www.......")

or you can use this code if you are looking for a specific tag :

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox() #or Chrome()
driver.get("http://www.......")
try:
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "tag_id"))
    )
finally:
    driver.quit()

Including dependencies in a jar with Maven

To make it more simple, You can use the below plugin.

             <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                        <configuration>
                            <classifier>spring-boot</classifier>
                            <mainClass>
                                com.nirav.certificate.CertificateUtility
                            </mainClass>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

Regex Letters, Numbers, Dashes, and Underscores

Your expression should already match dashes, because the final - will not be interpreted as a range operator (since the range has no end). To add underscores as well, try:

([A-Za-z0-9_-]+)

How to trigger SIGUSR1 and SIGUSR2?

terminal 1

dd if=/dev/sda of=debian.img

terminal 2

killall -SIGUSR1 dd

go back to terminal 1

34292201+0 records in
34292200+0 records out
17557606400 bytes (18 GB) copied, 1034.7 s, 17.0 MB/s

Convert XML to JSON (and back) using Javascript

A while back I wrote this tool https://bitbucket.org/surenrao/xml2json for my TV Watchlist app, hope this helps too.

Synopsys: A library to not only convert xml to json, but is also easy to debug (without circular errors) and recreate json back to xml. Features :- Parse xml to json object. Print json object back to xml. Can be used to save xml in IndexedDB as X2J objects. Print json object.

Simplest way to wait some asynchronous tasks complete, in Javascript?

I do this without external libaries:

var yourArray = ['aaa','bbb','ccc'];
var counter = [];

yourArray.forEach(function(name){
    conn.collection(name).drop(function(err) {
        counter.push(true);
        console.log('dropped');
        if(counter.length === yourArray.length){
            console.log('all dropped');
        }
    });                
});

Python Unicode Encode Error

Likely, your problem is that you parsed it okay, and now you're trying to print the contents of the XML and you can't because theres some foreign Unicode characters. Try to encode your unicode string as ascii first:

unicodeData.encode('ascii', 'ignore')

the 'ignore' part will tell it to just skip those characters. From the python docs:

>>> # Python 2: u = unichr(40960) + u'abcd' + unichr(1972)
>>> u = chr(40960) + u'abcd' + chr(1972)
>>> u.encode('utf-8')
'\xea\x80\x80abcd\xde\xb4'
>>> u.encode('ascii')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode character '\ua000' in position 0: ordinal not in range(128)
>>> u.encode('ascii', 'ignore')
'abcd'
>>> u.encode('ascii', 'replace')
'?abcd?'
>>> u.encode('ascii', 'xmlcharrefreplace')
'&#40960;abcd&#1972;'

You might want to read this article: http://www.joelonsoftware.com/articles/Unicode.html, which I found very useful as a basic tutorial on what's going on. After the read, you'll stop feeling like you're just guessing what commands to use (or at least that happened to me).

How do I define the name of image built with docker-compose

Option 1: Hinting default image name

The name of the image generated by docker-compose depends on the folder name by default but you can override it by using --project-name argument:

$ docker-compose --project-name foo build bar
$ docker images foo_bar

Option 2: Specifying image name

Once docker-compose 1.6.0 is out, you may specify build: and image: to have an explicit image name (see arulraj.net's answer).

Option 3: Create image from container

A third is to create an image from the container:

$ docker-compose up -d bar
$ docker commit $(docker-compose ps -q bar) foo_bar
$ docker-compose rm -f bar

How do you embed binary data in XML?

XML is so versatile...

<DATA>
  <BINARY>
    <BIT index="0">0</BIT>
    <BIT index="1">0</BIT>
    <BIT index="2">1</BIT>
    ...
    <BIT index="n">1</BIT>
  </BINARY>
</DATA>

XML is like violence - If it doesn't solve your problem, you're not using enough of it.

EDIT:

BTW: Base64 + CDATA is probably the best solution

(EDIT2:
Whoever upmods me, please also upmod the real answer. We don't want any poor soul to come here and actually implement my method because it was the highest ranked on SO, right?)

hexadecimal string to byte array in python

Assuming you have a byte string like so

"\x12\x45\x00\xAB"

and you know the amount of bytes and their type you can also use this approach

import struct

bytes = '\x12\x45\x00\xAB'
val = struct.unpack('<BBH', bytes)

#val = (18, 69, 43776)

As I specified little endian (using the '<' char) at the start of the format string the function returned the decimal equivalent.

0x12 = 18

0x45 = 69

0xAB00 = 43776

B is equal to one byte (8 bit) unsigned

H is equal to two bytes (16 bit) unsigned

More available characters and byte sizes can be found here

The advantages are..

You can specify more than one byte and the endian of the values

Disadvantages..

You really need to know the type and length of data your dealing with

Selecting a row of pandas series/dataframe by integer index

The primary purpose of the DataFrame indexing operator, [] is to select columns.

When the indexing operator is passed a string or integer, it attempts to find a column with that particular name and return it as a Series.

So, in the question above: df[2] searches for a column name matching the integer value 2. This column does not exist and a KeyError is raised.


The DataFrame indexing operator completely changes behavior to select rows when slice notation is used

Strangely, when given a slice, the DataFrame indexing operator selects rows and can do so by integer location or by index label.

df[2:3]

This will slice beginning from the row with integer location 2 up to 3, exclusive of the last element. So, just a single row. The following selects rows beginning at integer location 6 up to but not including 20 by every third row.

df[6:20:3]

You can also use slices consisting of string labels if your DataFrame index has strings in it. For more details, see this solution on .iloc vs .loc.

I almost never use this slice notation with the indexing operator as its not explicit and hardly ever used. When slicing by rows, stick with .loc/.iloc.

Scroll to the top of the page after render in react.js

Here's yet another approach that allows you to choose which mounted components you want the window scroll position to reset to without mass duplicating the ComponentDidUpdate/ComponentDidMount.

The example below is wrapping the Blog component with ScrollIntoView(), so that if the route changes when the Blog component is mounted, then the HOC's ComponentDidUpdate will update the window scroll position.

You can just as easily wrap it over the entire app, so that on any route change, it'll trigger a window reset.

ScrollIntoView.js

import React, { Component } from 'react';
import { withRouter } from 'react-router';

export default WrappedComponent => {
  class ResetWindowScroll extends Component {
    componentDidUpdate = (prevProps) => {
      if(this.props.location !== prevProps.location) window.scrollTo(0,0);
    }

    render = () => <WrappedComponent {...this.props} />
  }
  return withRouter(ResetWindowScroll);
}

Routes.js

import React from 'react';
import { Route, IndexRoute } from 'react-router';

import App from '../components/App';
import About from '../components/pages/About';
import Blog from '../components/pages/Blog'
import Index from '../components/Landing';
import NotFound from '../components/navigation/NotFound';
import ScrollIntoView from '../components/navigation/ScrollIntoView';

 export default (
    <Route path="/" component={App}>
        <IndexRoute component={Index} />
        <Route path="/about" component={About} /> 
        <Route path="/blog" component={ScrollIntoView(Blog)} />
        <Route path="*" component={NotFound} />
    </Route>
);

The above example works great, but if you've migrated to react-router-dom, then you can simplify the above by creating a HOC that wraps the component.

Once again, you could also just as easily wrap it over your routes (just change componentDidMount method to the componentDidUpdate method example code written above, as well as wrapping ScrollIntoView with withRouter).

containers/ScrollIntoView.js

import { PureComponent, Fragment } from "react";

class ScrollIntoView extends PureComponent {
  componentDidMount = () => window.scrollTo(0, 0);

  render = () => this.props.children
}

export default ScrollIntoView;

components/Home.js

import React from "react";
import ScrollIntoView from "../containers/ScrollIntoView";

export default () => (
  <ScrollIntoView>
    <div className="container">
      <p>
        Sample Text
      </p>
    </div>
  </ScrollIntoView>
);

How to make an HTTP get request with parameters

You can also pass value directly via URL.

If you want to call method public static void calling(string name){....}

then you should call usingHttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create("http://localhost:****/Report/calling?name=Priya); webrequest.Method = "GET"; webrequest.ContentType = "application/text";

Just make sure you are using ?Object = value in URL

Position one element relative to another in CSS

I would suggest using absolute positioning within the element.

I've created this to help you visualize it a bit.

_x000D_
_x000D_
#parent {_x000D_
    width:400px;_x000D_
    height:400px;_x000D_
    background-color:white;_x000D_
    border:2px solid blue;_x000D_
    position:relative;_x000D_
}_x000D_
#div1 {position:absolute;bottom:0;right:0;background:green;width:100px;height:100px;}_x000D_
#div2 {width:100px;height:100px;position:absolute;bottom:0;left:0;background:red;}_x000D_
#div3 {width:100px;height:100px;position:absolute;top:0;right:0;background:yellow;}_x000D_
#div4 {width:100px;height:100px;position:absolute;top:0;left:0;background:gray;}
_x000D_
<div id="parent">_x000D_
<div id="div1"></div>_x000D_
<div id="div2"></div>_x000D_
<div id="div3"></div>_x000D_
<div id="div4"></div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/wUrdM/

Remove tracking branches no longer on remote

I found the answer here: How can I delete all git branches which have been merged?

git branch --merged | grep -v "\*" | xargs -n 1 git branch -d

Make sure we keep master

You can ensure that master, or any other branch for that matter, doesn't get removed by adding another grep after the first one. In that case you would go:

git branch --merged | grep -v "\*" | grep -v "YOUR_BRANCH_TO_KEEP" | xargs -n 1 git branch -d

So if we wanted to keep master, develop and staging for instance, we would go:

git branch --merged | grep -v "\*" | grep -v "master" | grep -v "develop" | grep -v "staging" | xargs -n 1 git branch -d

Make this an alias

Since it's a bit long, you might want to add an alias to your .zshrc or .bashrc. Mine is called gbpurge (for git branches purge):

alias gbpurge='git branch --merged | grep -v "\*" | grep -v "master" | grep -v "develop" | grep -v "staging" | xargs -n 1 git branch -d'

Then reload your .bashrc or .zshrc:

. ~/.bashrc

or

. ~/.zshrc

Typing the Enter/Return key using Python and Selenium

When you don't want to search any locator, you can use the Robot class. For example,

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);

How to solve PHP error 'Notice: Array to string conversion in...'

<?php
ob_start();
var_dump($_POST['C']);
$result = ob_get_clean();
?>

if you want to capture the result in a variable

How do I create a view controller file after creating a new view controller?

To add new ViewController once you have have an existing ViewController, follow below step:

  1. Click on background of Main.storyboard.

  2. Search and select ViewController from object library at the utility window.

  3. Drag and drop it in background to create a new ViewController.