Programs & Examples On #Newlib

Error: Could not find or load main class in intelliJ IDE

In my case in the module's build.gradle the mainClassName assignment must state the fully qualified class name, ie. as specified as the package name in the main class' source code file.

How to use aria-expanded="true" to change a css property

_x000D_
_x000D_
li a[aria-expanded="true"] span{_x000D_
    color: red;_x000D_
}
_x000D_
<li class="active">_x000D_
    <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true">_x000D_
        <span class="network-name">Google+</span>_x000D_
    </a>_x000D_
</li>_x000D_
<li class="active">_x000D_
    <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="false">_x000D_
        <span class="network-name">Google+</span>_x000D_
    </a>_x000D_
</li>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
li a[aria-expanded="true"]{_x000D_
    background: yellow;_x000D_
}
_x000D_
<li class="active">_x000D_
    <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true">_x000D_
        <span class="network-name">Google+</span>_x000D_
    </a>_x000D_
</li>_x000D_
<li class="active">_x000D_
    <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="false">_x000D_
        <span class="network-name">Google+</span>_x000D_
    </a>_x000D_
</li>
_x000D_
_x000D_
_x000D_

Ruby on Rails: How do I add placeholder text to a f.text_field?

In your view template, set a default value:

f.text_field :password, :value => "password"

In your Javascript (assuming jquery here):

$(document).ready(function() {
  //add a handler to remove the text
});

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

I know this is tagged html/css only, but you can't do that with css only. Easiest way will be using some jQuery.

var fixmeTop = $('.fixme').offset().top;       // get initial position of the element

$(window).scroll(function() {                  // assign scroll event listener

    var currentScroll = $(window).scrollTop(); // get current position

    if (currentScroll >= fixmeTop) {           // apply position: fixed if you
        $('.fixme').css({                      // scroll to that element or below it
            position: 'fixed',
            top: '0',
            left: '0'
        });
    } else {                                   // apply position: static
        $('.fixme').css({                      // if you scroll above it
            position: 'static'
        });
    }

});

http://jsfiddle.net/5n5MA/2/

Access mysql remote database from command line

If you are on windows, try Visual Studio Code with MySQL plugins, an easy and integrated way to access MySQL data on a windows machine. And the database tables listed and can execute any custom queries.

Java - How do I make a String array with values?

Another way is with Arrays.setAll, or Arrays.fill:

String[] v = new String[1000];
Arrays.setAll(v, i -> Integer.toString(i * 30));
//v => ["0", "30", "60", "90"... ]

Arrays.fill(v, "initial value");
//v => ["initial value", "initial value"... ]

This is more usefull for initializing (possibly large) arrays where you can compute each element from its index.

How to get two or more commands together into a batch file

To get a user Input :

set /p pathName=Enter The Value:%=%
@echo %pathName%

enter image description here

p.s. this is also valid :

set /p pathName=Enter The Value:

Exception.Message vs Exception.ToString()

I'd say @Wim is right. You should use ToString() for logfiles - assuming a technical audience - and Message, if at all, to display to the user. One could argue that even that is not suitable for a user, for every exception type and occurance out there (think of ArgumentExceptions, etc.).

Also, in addition to the StackTrace, ToString() will include information you will not get otherwise. For example the output of fusion, if enabled to include log messages in exception "messages".

Some exception types even include additional information (for example from custom properties) in ToString(), but not in the Message.

How do I create a user with the same privileges as root in MySQL/MariaDB?

% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;

nullable object must have a value

I got this message when trying to access values of a null valued object.

sName = myObj.Name;

this will produce error. First you should check if object not null

if(myObj != null)
  sName = myObj.Name;

This works.

ERROR in ./node_modules/css-loader?

I am also facing the same problem, but I resolve.

npm install node-sass  

Above command work for me. As per your synario you can use the blow command.

Try 1

 npm install node-sass

Try 2

remove node_modules folder and run npm install

Try 3

npm rebuild node-sass

Try 4

npm install --save node-sass

For your ref you can go through this github link

Make a bucket public in Amazon S3

You can set a bucket policy as detailed in this blog post:

http://ariejan.net/2010/12/24/public-readable-amazon-s3-bucket-policy/


As per @robbyt's suggestion, create a bucket policy with the following JSON:

{
  "Version": "2008-10-17",
  "Statement": [{
    "Sid": "AllowPublicRead",
    "Effect": "Allow",
    "Principal": { "AWS": "*" },
    "Action": ["s3:GetObject"],
    "Resource": ["arn:aws:s3:::bucket/*" ]
  }]
}

Important: replace bucket in the Resource line with the name of your bucket.

PHP strtotime +1 month adding an extra month

It's jumping to March because today is 29th Jan, and adding a month gives 29th Feb, which doesn't exist, so it's moving to the next valid date.

This will happen on the 31st of a lot of months as well, but is obviously more noticable in the case of January to Feburary because Feb is shorter.

If you're not interested in the day of month and just want it to give the next month, you should specify the input date as the first of the current month. This will always give you the correct answer if you add a month.

For the same reason, if you want to always get the last day of the next month, you should start by calculating the first of the month after the one you want, and subtracting a day.

How to speed up insertion performance in PostgreSQL

If you happend to insert colums with UUIDs (which is not exactly your case) and to add to @Dennis answer (I can't comment yet), be advise than using gen_random_uuid() (requires PG 9.4 and pgcrypto module) is (a lot) faster than uuid_generate_v4()

=# explain analyze select uuid_generate_v4(),* from generate_series(1,10000);
                                                        QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------
 Function Scan on generate_series  (cost=0.00..12.50 rows=1000 width=4) (actual time=11.674..10304.959 rows=10000 loops=1)
 Planning time: 0.157 ms
 Execution time: 13353.098 ms
(3 filas)

vs


=# explain analyze select gen_random_uuid(),* from generate_series(1,10000);
                                                        QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------
 Function Scan on generate_series  (cost=0.00..12.50 rows=1000 width=4) (actual time=252.274..418.137 rows=10000 loops=1)
 Planning time: 0.064 ms
 Execution time: 503.818 ms
(3 filas)

Also, it's the suggested official way to do it

Note

If you only need randomly-generated (version 4) UUIDs, consider using the gen_random_uuid() function from the pgcrypto module instead.

This droped insert time from ~2 hours to ~10 minutes for 3.7M of rows.

Remove Android App Title Bar

for Title Bar

requestWindowFeature(Window.FEATURE_NO_TITLE);

for fullscreen

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

Place this after

super.onCreate(savedInstanceState);

but before

setContentView(R.layout.xml);

This worked for me.try this

onMeasure custom view explanation

onMeasure() is your opportunity to tell Android how big you want your custom view to be dependent the layout constraints provided by the parent; it is also your custom view's opportunity to learn what those layout constraints are (in case you want to behave differently in a match_parent situation than a wrap_content situation). These constraints are packaged up into the MeasureSpec values that are passed into the method. Here is a rough correlation of the mode values:

  • EXACTLY means the layout_width or layout_height value was set to a specific value. You should probably make your view this size. This can also get triggered when match_parent is used, to set the size exactly to the parent view (this is layout dependent in the framework).
  • AT_MOST typically means the layout_width or layout_height value was set to match_parent or wrap_content where a maximum size is needed (this is layout dependent in the framework), and the size of the parent dimension is the value. You should not be any larger than this size.
  • UNSPECIFIED typically means the layout_width or layout_height value was set to wrap_content with no restrictions. You can be whatever size you would like. Some layouts also use this callback to figure out your desired size before determine what specs to actually pass you again in a second measure request.

The contract that exists with onMeasure() is that setMeasuredDimension() MUST be called at the end with the size you would like the view to be. This method is called by all the framework implementations, including the default implementation found in View, which is why it is safe to call super instead if that fits your use case.

Granted, because the framework does apply a default implementation, it may not be necessary for you to override this method, but you may see clipping in cases where the view space is smaller than your content if you do not, and if you lay out your custom view with wrap_content in both directions, your view may not show up at all because the framework doesn't know how large it is!

Generally, if you are overriding View and not another existing widget, it is probably a good idea to provide an implementation, even if it is as simple as something like this:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    int desiredWidth = 100;
    int desiredHeight = 100;

    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    int width;
    int height;

    //Measure Width
    if (widthMode == MeasureSpec.EXACTLY) {
        //Must be this size
        width = widthSize;
    } else if (widthMode == MeasureSpec.AT_MOST) {
        //Can't be bigger than...
        width = Math.min(desiredWidth, widthSize);
    } else {
        //Be whatever you want
        width = desiredWidth;
    }

    //Measure Height
    if (heightMode == MeasureSpec.EXACTLY) {
        //Must be this size
        height = heightSize;
    } else if (heightMode == MeasureSpec.AT_MOST) {
        //Can't be bigger than...
        height = Math.min(desiredHeight, heightSize);
    } else {
        //Be whatever you want
        height = desiredHeight;
    }

    //MUST CALL THIS
    setMeasuredDimension(width, height);
}

Hope that Helps.

MySQL: How to set the Primary Key on phpMyAdmin?

MySQL can index the first x characters of a column,but a TEXT type is of variable length so mysql cant assure the uniqueness of the column.If you still want text column,use VARCHAR.

Show percent % instead of counts in charts of categorical variables

Here is a workaround for faceted data. (The accepted answer by @Andrew does not work in this case.) The idea is to calculate the percentage value using dplyr and then to use geom_col to create the plot.

library(ggplot2)
library(scales)
library(magrittr)
library(dplyr)

binwidth <- 30

mtcars.stats <- mtcars %>%
  group_by(cyl) %>%
  mutate(bin = cut(hp, breaks=seq(0,400, binwidth), 
               labels= seq(0+binwidth,400, binwidth)-(binwidth/2)),
         n = n()) %>%
  group_by(cyl, bin) %>%
  summarise(p = n()/n[1]) %>%
  ungroup() %>%
  mutate(bin = as.numeric(as.character(bin)))

ggplot(mtcars.stats, aes(x = bin, y= p)) +  
  geom_col() + 
  scale_y_continuous(labels = percent) +
  facet_grid(cyl~.)

This is the plot:

enter image description here

Remove characters except digits from string using Python?

my_string="sdfsdfsdfsfsdf353dsg345435sdfs525436654.dgg(" 
my_string=''.join((ch if ch in '0123456789' else '') for ch in my_string)
print(output:+my_string)

output: 353345435525436654

Generics in C#, using type of a variable as parameter

You can't use it in the way you describe. The point about generic types, is that although you may not know them at "coding time", the compiler needs to be able to resolve them at compile time. Why? Because under the hood, the compiler will go away and create a new type (sometimes called a closed generic type) for each different usage of the "open" generic type.

In other words, after compilation,

DoesEntityExist<int>

is a different type to

DoesEntityExist<string>

This is how the compiler is able to enfore compile-time type safety.

For the scenario you describe, you should pass the type as an argument that can be examined at run time.

The other option, as mentioned in other answers, is that of using reflection to create the closed type from the open type, although this is probably recommended in anything other than extreme niche scenarios I'd say.

How to print the full NumPy array, without truncation?

Use numpy.set_printoptions:

import sys
import numpy
numpy.set_printoptions(threshold=sys.maxsize)

"git rm --cached x" vs "git reset head --? x"?

Perhaps an example will help:

git rm --cached asd
git commit -m "the file asd is gone from the repository"

versus

git reset HEAD -- asd
git commit -m "the file asd remains in the repository"

Note that if you haven't changed anything else, the second commit won't actually do anything.

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

you can use this way

 map = new google.maps.Map(document.getElementById('map'), {
        zoom: 16,
        center: { lat: parseFloat(lat), lng: parseFloat(lng) },
        mapTypeId: 'terrain', 
        disableDefaultUI: true
 });

EX : center: { lat: parseFloat(lat), lng: parseFloat(lng) },

Convert Select Columns in Pandas Dataframe to Numpy Array

the easy way is the "values" property df.iloc[:,1:].values

a=df.iloc[:,1:]
b=df.iloc[:,1:].values

print(type(df))
print(type(a))
print(type(b))

so, you can get type

<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>
<class 'numpy.ndarray'>

What is ":-!!" in C code?

Some people seem to be confusing these macros with assert().

These macros implement a compile-time test, while assert() is a runtime test.

How to add a list item to an existing unordered list?

You can do it also in more 'object way' and still easy-to-read:

$('#content ul').append(
    $('<li>').append(
        $('<a>').attr('href','/user/messages').append(
            $('<span>').attr('class', 'tab').append("Message center")
)));    

You don't have to fight with quotes then, but must keep trace of braces :)

"This operation requires IIS integrated pipeline mode."

For Visual Studio 2012 while debugging that error accrued

Website Menu -> Use IIS Express did it for me

How to set max and min value for Y axis

There's so many conflicting answers to this, most of which had no effect for me.

I was finally able to set (or retrieve current) X-axis minimum & maximum displayed values with chart.options.scales.xAxes[0].ticks.min (even if min & max are only a subset of the data assigned to the chart.)

Using a time scale in my case, I used:

chart.options.scales.xAxes[0].ticks.min = 1590969600000;  //Jun 1, 2020
chart.options.scales.xAxes[0].ticks.max = 1593561600000;  //Jul 1, 2020
chart.update();

(I found no need to set the step values or beginAtZero, etc.)

SQL: set existing column as Primary Key in MySQL

ALTER TABLE your_table
ADD PRIMARY KEY (Drugid);

Centering the pagination in bootstrap

This css works for me:

.dataTables_paginate {
   float: none !important;
   text-align: center !important;
}

Change R default library path using .libPaths in Rprofile.site fails to work

I was looking into this because R was having issues installing into the default location and was instead just putting the packages into the temp folder. It turned out to be the latest update for Mcaffee Endpoint Security which apparently has issues with R. You can disable the threat protection while you install the packages and it will work properly.

How to get Last record from Sqlite?

I think it would be better if you use the method query from SQLiteDatabase class instead of the whole SQL string, which would be:

 Cursor cursor = sqLiteDatabase.query(TABLE, allColluns, null, null, null, null, ID +" DESC", "1");

The last two parameters are ORDER BY and LIMIT.

You can see more at: http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html

bitwise XOR of hex numbers in python

here's a better function

def strxor(a, b):     # xor two strings of different lengths
    if len(a) > len(b):
        return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)])
    else:
        return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b[:len(a)])])

Why do I have ORA-00904 even when the column is present?

Oracle will throw ORA-00904 if executing user does not have proper permissions on objects involved in the query.

Oracle row count of table by count(*) vs NUM_ROWS from DBA_TABLES

According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.

This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.

select num_rows from all_tables where table_name = 'MY_TABLE'

This query counts the current number of rows in MY_TABLE

select count(*) from my_table

By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.

  1. In the documentation there's an asterisk by the column name, which leads to this note:

    Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.

    This means that unless you have gathered statistics on the table then this column will not have any data.

  2. Statistics gathered in 11g+ with the default estimate_percent, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.

If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.

Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.

Declaring a variable and setting its value from a SELECT query in Oracle

SELECT INTO

DECLARE
   the_variable NUMBER;

BEGIN
   SELECT my_column INTO the_variable FROM my_table;
END;

Make sure that the query only returns a single row:

By default, a SELECT INTO statement must return only one row. Otherwise, PL/SQL raises the predefined exception TOO_MANY_ROWS and the values of the variables in the INTO clause are undefined. Make sure your WHERE clause is specific enough to only match one row

If no rows are returned, PL/SQL raises NO_DATA_FOUND. You can guard against this exception by selecting the result of an aggregate function, such as COUNT(*) or AVG(), where practical. These functions are guaranteed to return a single value, even if no rows match the condition.

A SELECT ... BULK COLLECT INTO statement can return multiple rows. You must set up collection variables to hold the results. You can declare associative arrays or nested tables that grow as needed to hold the entire result set.

The implicit cursor SQL and its attributes %NOTFOUND, %FOUND, %ROWCOUNT, and %ISOPEN provide information about the execution of a SELECT INTO statement.

maxlength ignored for input type="number" in Chrome

The absolute solution that I've recently just tried is:

<input class="class-name" placeholder="1234567" name="elementname"  type="text" maxlength="4" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" />

Why is there no ForEach extension method on IEnumerable?

One workaround is to write .ToList().ForEach(x => ...).

pros

Easy to understand - reader only needs to know what ships with C#, not any additional extension methods.

Syntactic noise is very mild (only adds a little extranious code).

Doesn't usually cost extra memory, since a native .ForEach() would have to realize the whole collection, anyway.

cons

Order of operations isn't ideal. I'd rather realize one element, then act on it, then repeat. This code realizes all elements first, then acts on them each in sequence.

If realizing the list throws an exception, you never get to act on a single element.

If the enumeration is infinite (like the natural numbers), you're out of luck.

Really killing a process in Windows

Process Hacker has numerous ways of killing a process.

(Right-click the process, then go to Miscellaneous->Terminator.)

Get row-index values of Pandas DataFrame as list?

To get the index values as a list/list of tuples for Index/MultiIndex do:

df.index.values.tolist()  # an ndarray method, you probably shouldn't depend on this

or

list(df.index.values)  # this will always work in pandas

Is there a way to list all resources in AWS

I'd go with the "tag editor" in "resource groups" for this, as suggested by Ashwini.

You can easily list all resources in all regions without any setup etc.
And although this does include all the default VPCs + security groups etc (so you'll get ~140 items even if your account is empty), you can still fairly easily filter this, either within tag editor, or export to csv and filter in Excel, for example.

css to make bootstrap navbar transparent

Update 2019

Bootstrap 4 - The Navbar is transparent by default

Most of the answers here are misleading because they relate to Bootstrap 3. By default, the Bootstrap 4 Navbar is transparent. Just remember to use navbar-light or navbar-dark so the link colors work against the contrast of the background color...

https://www.codeply.com/go/FTDyj4KZlQ

<nav class="navbar navbar-expand-sm fixed-top navbar-light">
    <div class="container">
        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbar1">
            <span class="navbar-toggler-icon"></span>
        </button>
        <a class="navbar-brand" href="#">Brand</a>
        <div class="collapse navbar-collapse" id="navbar1">
            <ul class="navbar-nav">
                <li class="nav-item active">
                    <a class="nav-link" href="#">Link</a>
                </li>
            </ul>
        </div>
    </div>
</nav>

What are the different usecases of PNG vs. GIF vs. JPEG vs. SVG?

GIF is limited to 256 colors and do not support real transparency. You should use PNG instead of GIF because it offers better compression and features. PNG is great for small and simple images like logos, icons, etc.

JPEG has better compression with complex images like photos.

ActionBar text color

It's an old topic but for future readers, using ToolBar makes everything very easy:

Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
toolbar.setTitle(R.string.app_name);
toolbar.setTitleTextColor(getResources().getColor(R.color.someColor));
setSupportActionBar(toolbar);

Read from database and fill DataTable

Connection object is for illustration only. The DataAdapter is the key bit:

Dim strSql As String = "SELECT EmpCode,EmpID,EmpName FROM dbo.Employee"
Dim dtb As New DataTable
Using cnn As New SqlConnection(connectionString)
  cnn.Open()
  Using dad As New SqlDataAdapter(strSql, cnn)
    dad.Fill(dtb)
  End Using
  cnn.Close()
End Using

How do I set a variable to the output of a command in Bash?

You need to use either

$(command-here)

or

`command-here`

Example

#!/bin/bash

VAR1="$1"
VAR2="$2"

MOREF="$(sudo run command against "$VAR1" | grep name | cut -c7-)"

echo "$MOREF"

How to comment multiple lines in Visual Studio Code?

All the key board shorcuts for VS code can be found in the link : Link

  • Add a Line comment Ctrl+K Ctrl+C
  • Remove a line comment Ctrl+K Ctrl+U
  • More shortcut Ctrl+/

Solution to "subquery returns more than 1 row" error

When one gets the error 'sub-query returns more than 1 row', the database is actually telling you that there is an unresolvable circular reference. It's a bit like using a spreadsheet and saying cell A1 = B1 and then saying B1 = A1. This error is typically associated with a scenario where one needs to have a double nested sub-query. I would recommend you look up a thing called a 'cross-tab query' this is the type of query one normally needs to solve this problem. It's basically an outer join (left or right) nested inside a sub-query or visa versa. One can also solve this problem with a double join (also considered to be a type of cross-tab query) such as below:

CREATE DEFINER=`root`@`localhost` PROCEDURE `SP_GET_VEHICLES_IN`(
    IN P_email VARCHAR(150),
    IN P_credentials VARCHAR(150)
)
BEGIN
    DECLARE V_user_id INT(11);
    SET V_user_id = (SELECT user_id FROM users WHERE email = P_email AND credentials = P_credentials LIMIT 1);
    SELECT vehicles_in.vehicle_id, vehicles_in.make_id, vehicles_in.model_id, vehicles_in.model_year,
    vehicles_in.registration, vehicles_in.date_taken, make.make_label, model.model_label
    FROM make
    LEFT OUTER JOIN vehicles_in ON vehicles_in.make_id = make.make_id
    LEFT OUTER JOIN model ON model.make_id = make.make_id AND vehicles_in.model_id = model.model_id
    WHERE vehicles_in.user_id = V_user_id;
END

In the code above notice that there are three tables in amongst the SELECT clause and these three tables show up after the FROM clause and after the two LEFT OUTER JOIN clauses, these three tables must be distinct amongst the FROM and LEFT OUTER JOIN clauses to be syntactically correct.

It is noteworthy that this is a very important construct to know as a developer especially if you're writing periodical report queries and it's probably the most important skill for any complex cross referencing, so all developers should study these constructs (cross-tab and double join).

Another thing I must warn about is: If you are going to use a cross-tab as a part of a working system and not just a periodical report, you must check the record count and reconfigure the join conditions until the minimum records are returned, otherwise large tables and cross-tabs can grind your server to a halt. Hope this helps.

Why is a div with "display: table-cell;" not affected by margin?

You can use inner divs to set the margin.

<div style="display: table-cell;">
   <div style="margin:5px;background-color: red;">1</div>
</div>
<div style="display: table-cell; ">
  <div style="margin:5px;background-color: green;">1</div>
</div>

JS Fiddle

Access-Control-Allow-Origin and Angular.js $http

Adding below to server.js resolved mine

    server.post('/your-rest-endpt/*', function(req,res){
    console.log('');
    console.log('req.url: '+req.url);
    console.log('req.headers: ');   
    console.dir(req.headers);
    console.log('req.body: ');
    console.dir(req.body);  

    var options = {
        host: 'restAPI-IP' + ':' + '8080'

        , protocol: 'http'
        , pathname: 'your-rest-endpt/'
    };
    console.log('options: ');
    console.dir(options);   

    var reqUrl = url.format(options);
    console.log("Forward URL: "+reqUrl);

    var parsedUrl = url.parse(req.url, true);
    console.log('parsedUrl: ');
    console.dir(parsedUrl);

    var queryParams = parsedUrl.query;

    var path = parsedUrl.path;
    var substr = path.substring(path.lastIndexOf("rest/"));
    console.log('substr: ');
    console.dir(substr);

    reqUrl += substr;
    console.log("Final Forward URL: "+reqUrl);

    var newHeaders = {
    };

    //Deep-copy it, clone it, but not point to me in shallow way...
    for (var headerKey in req.headers) {
        newHeaders[headerKey] = req.headers[headerKey];
    };

    var newBody = (req.body == null || req.body == undefined ? {} : req.body);

    if (newHeaders['Content-type'] == null
            || newHeaders['Content-type'] == undefined) {
        newHeaders['Content-type'] = 'application/json';
        newBody = JSON.stringify(newBody);
    }

    var requestOptions = {
        headers: {
            'Content-type': 'application/json'
        }
        ,body: newBody
        ,method: 'POST'
    };

    console.log("server.js : routes to URL : "+ reqUrl);

    request(reqUrl, requestOptions, function(error, response, body){
        if(error) {
            console.log('The error from Tomcat is --> ' + error.toString());
            console.dir(error);
            //return false;
        }

        if (response.statusCode != null 
                && response.statusCode != undefined
                && response.headers != null
                && response.headers != undefined) {
            res.writeHead(response.statusCode, response.headers);
        } else {
            //404 Not Found
            res.writeHead(404);         
        }
        if (body != null
                && body != undefined) {

            res.write(body);            
        }
        res.end();
    });
});

Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab

I will soon released a new version of my app to support to galaxy ace.

You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree

In order to solve your problem you should do this:

this._camera = Camera.open();     
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});

Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);

params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);

don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true

to turn off the led just release the camera

Remove spacing between table cells and rows

If you see table class it has border-spacing: 2px; You could override table class in your css and set its border-spacing: 0px!important in table; I did it like

table {
      border-collapse: separate;
      white-space: normal;
      line-height: normal;
      font-weight: normal;
      font-size: medium;
      font-style: normal;
      color: -internal-quirk-inherit;
      text-align: start;
      border-spacing: 0px!important;
      font-variant: normal;   }

It saved my day.Hope it would be of help. Thanks.

Get user location by IP address

An Alternative to using an API is to use HTML 5 location Navigator to query the browser about the User location. I was looking for a similar approach as in the subject question but I found that HTML 5 Navigator works better and cheaper for my situation. Please consider that your scinario might be different. To get the User position using Html5 is very easy:

function getLocation()
{
    if (navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
    else
    {
        console.log("Geolocation is not supported by this browser.");
     }
}

function showPosition(position)
{
      console.log("Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude); 
}

Try it yourself on W3Schools Geolocation Tutorial

while EOF in JAVA?

The others told you enough about your issue with multiple calls of readLine().

I just wanted to leave sth about code style: While you see this line = assignement and != null check together in one while condition in most examples (like @gotomanners example here) I prefer using a for for it.

It is much more readable in my opinion ...

for (String line = in.readLine(); line != null; line = in.readLine()) {
    ...
}

Another nice way to write it you see in @TheCapn's example. But when you write it that way you easily see that's what a for-loop is made for.

I do not like assignments scrambled with conditions in one line. It is bad style in my opinion. But because it is so MUCH popular for that special case here to do it that way I would not consider it really bad style. (But cannot understand who established this bad style to become that popular.)

Why use 'virtual' for class properties in Entity Framework model definitions?

The virtual keyword in C# enables a method or property to be overridden by child classes. For more information please refer to the MSDN documentation on the 'virtual' keyword

UPDATE: This doesn't answer the question as currently asked, but I'll leave it here for anyone looking for a simple answer to the original, non-descriptive question asked.

Isn't the size of character in Java 2 bytes?

The constructor String(byte[] bytes) takes the bytes from the buffer and encodes them to characters.

It uses the platform default charset to encode bytes to characters. If you know, your file contains text, that is encoded in a different charset, you can use the String(byte[] bytes, String charsetName) to use the correct encoding (from bytes to characters).

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

This is the result in Firefox 78.0.2 (64-Bit):

img {
    border: none;
        border-top-color: currentcolor;
        border-top-style: none;
        border-top-width: medium;
        border-right-color: currentcolor;
        border-right-style: none;
        border-right-width: medium;
        border-bottom-color: currentcolor;
        border-bottom-style: none;
        border-bottom-width: medium;
        border-left-color: currentcolor;
        border-left-style: none;
        border-left-width: medium;
}

img {
    border: 0;
        border-top-color: currentcolor;
        border-top-style: none;
        border-top-width: 0px;
        border-right-color: currentcolor;
        border-right-style: none;
        border-right-width: 0px;
        border-bottom-color: currentcolor;
        border-bottom-style: none;
        border-bottom-width: 0px;
        border-left-color: currentcolor;
        border-left-style: none;
        border-left-width: 0px;
        border-image-outset: 0;
        border-image-repeat: stretch;
        border-image-slice: 100%;
        border-image-source: none;
        border-image-width: 1;
}

Date: 20200720

How to do a SQL NOT NULL with a DateTime?

SELECT * FROM Table where codtable not in (Select codtable from Table where fecha is null)

How to find text in a column and saving the row number where it is first found - Excel VBA

Check for "projtemp" and then check if the previous one is a number entry (like 19,18..etc..) if that is so then get the row no of that proj temp ....

and if that is not so ..then re-check that the previous entry is projtemp or a number entry ...

Counting lines, words, and characters within a text file using Python

fname = "feed.txt"
feed = open(fname, 'r')

num_lines = len(feed.splitlines())
num_words = 0
num_chars = 0

for line in lines:
    num_words += len(line.split())

Difference between webdriver.Dispose(), .Close() and .Quit()

My understanding is driver.close(); will close the current browser, and driver.quit(); will terminate all the browser that.

Best way to list files in Java, sorted by Date Modified?

I think your solution is the only sensible way. The only way to get the list of files is to use File.listFiles() and the documentation states that this makes no guarantees about the order of the files returned. Therefore you need to write a Comparator that uses File.lastModified() and pass this, along with the array of files, to Arrays.sort().

How to delete a module in Android Studio

The most reliable way I have found to do this it to go to project structure and remove it from dependencies and remove it from your setting.gradle file.

It will appear as if it is fully deleted at his point but it is not. If you try to re add the module it will say that it already exist in the project.

The final step is to go to the location of your project using file explorer etc and delete the module.

This work 100% of the time on studio 1.3.1

C# DLL config file

you can use this code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace GClass1
{
[Guid("D6F88E95-8A27-4ae6-B6DE-0542A0FC7039")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface _GesGasConnect
{
    [DispId(1)]
    int SetClass1Ver(string version);


}

[Guid("13FE32AD-4BF8-495f-AB4D-6C61BD463EA4")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("InterfacesSMS.Setting")]
public class Class1 : _Class1
{
    public Class1() { }


    public int SetClass1(string version)
    {
        return (DateTime.Today.Day);
    }
}
}

How can I make a div stick to the top of the screen once it's been scrolled to?

My solution is a little verbose, but it handles variable positioning from the left edge for centered layouts.

// Ensurs that a element (usually a div) stays on the screen
//   aElementToStick   = The jQuery selector for the element to keep visible
global.makeSticky = function (aElementToStick) {
    var $elementToStick = $(aElementToStick);
    var top = $elementToStick.offset().top;
    var origPosition = $elementToStick.css('position');

    function positionFloater(a$Win) {
        // Set the original position to allow the browser to adjust the horizontal position
        $elementToStick.css('position', origPosition);

        // Test how far down the page is scrolled
        var scrollTop = a$Win.scrollTop();
        // If the page is scrolled passed the top of the element make it stick to the top of the screen
        if (top < scrollTop) {
            // Get the horizontal position
            var left = $elementToStick.offset().left;
            // Set the positioning as fixed to hold it's position
            $elementToStick.css('position', 'fixed');
            // Reuse the horizontal positioning
            $elementToStick.css('left', left);
            // Hold the element at the top of the screen
            $elementToStick.css('top', 0);
        }
    }

    // Perform initial positioning
    positionFloater($(window));

    // Reposition when the window resizes
    $(window).resize(function (e) {
        positionFloater($(this));
    });

    // Reposition when the window scrolls
    $(window).scroll(function (e) {
        positionFloater($(this));
    });
};

How do I force a DIV block to extend to the bottom of a page even if it has no content?

Your problem is not that the div is not at 100% height, but that the container around it is not.This will help in the browser I suspect you are using:

html,body { height:100%; }

You may need to adjust padding and margins as well, but this will get you 90% of the way there.If you need to make it work with all browsers you will have to mess around with it a bit.

This site has some excellent examples:

http://www.brunildo.org/test/html_body_0.html
http://www.brunildo.org/test/html_body_11b.html
http://www.brunildo.org/test/index.html

I also recommend going to http://quirksmode.org/

fatal: early EOF fatal: index-pack failed

I've experience the same problem. The REPO was too big to be downloaded via SSH. Just like @elin3t recommended, I've cloned over HTTP/HTTPS and change the REMOTE URL in .git/config to use the SSH REPO.

Entity framework code-first null foreign key

I have the same problem now , I have foreign key and i need put it as nullable, to solve this problem you should put

    modelBuilder.Entity<Country>()
        .HasMany(c => c.Users)
        .WithOptional(c => c.Country)
        .HasForeignKey(c => c.CountryId)
        .WillCascadeOnDelete(false);

in DBContext class I am sorry for answer you very late :)

Redirect Windows cmd stdout and stderr to a single file

There is, however, no guarantee that the output of SDTOUT and STDERR are interweaved line-by-line in timely order, using the POSIX redirect merge syntax.

If an application uses buffered output, it may happen that the text of one stream is inserted in the other at a buffer boundary, which may appear in the middle of a text line.

A dedicated console output logger (I.e. the "StdOut/StdErr Logger" by 'LoRd MuldeR') may be more reliable for such a task.

See: MuldeR's OpenSource Projects

DateDiff to output hours and minutes

Small change like this can be done

  SELECT  EmplID
        , EmplName
        , InTime
        , [TimeOut]
        , [DateVisited]
        , CASE WHEN minpart=0 
        THEN CAST(hourpart as nvarchar(200))+':00' 
        ELSE CAST((hourpart-1) as nvarchar(200))+':'+ CAST(minpart as nvarchar(200))END as 'total time'
        FROM 
        (
        SELECT   EmplID, EmplName, InTime, [TimeOut], [DateVisited],
        DATEDIFF(Hour,InTime, [TimeOut]) as hourpart, 
        DATEDIFF(minute,InTime, [TimeOut])%60 as minpart  
        from times) source

link_to image tag. how to add class to a tag

Best will be:

link_to image_tag("Search.png", :border => 0, :alt => '', :title => ''), pages_search_path, :class => 'dock-item'

"Parse Error : There is a problem parsing the package" while installing Android application

The reason is apk is not signed. Once the apk is signed, the issue will be resolved. http://ionicframework.com/docs/guide/publishing.html Please use the link on instructions to sign the apk.

how to change listen port from default 7001 to something different?

As my experience, you can add another domain which listens different port than 7001, and use this domain in to deploy app.

Here's an example: http://st-curriculum.oracle.com/obe/fmw/wls/10g/r3/installconfig/install_wls/install_wls.htm

HTH.

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

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

Setting the height of a DIV dynamically

inspired by @jason-bunting, same thing for either height or width:

function resizeElementDimension(element, doHeight) {
  dim = (doHeight ? 'Height' : 'Width')
  ref = (doHeight ? 'Top' : 'Left')

  var x = 0;
  var body = window.document.body;
  if(window['inner' + dim])
    x = window['inner' + dim]
  else if (body.parentElement['client' + dim])
    x = body.parentElement['client' + dim]
  else if (body && body['client' + dim])
    x = body['client' + dim]

  element.style[dim.toLowerCase()] = ((x - element['offset' + ref]) + "px");
}

How to show uncommitted changes in Git and some Git diffs in detail

For me, the only thing which worked is

git diff HEAD

including the staged files, git diff --cached only shows staged files.

Calculate age given the birth date in the format YYYYMMDD

Works perfect for me, guys.

getAge(birthday) {
    const millis = Date.now() - Date.parse(birthday);
    return new Date(millis).getFullYear() - 1970;
}

Why use 'git rm' to remove a file instead of 'rm'?

If you just use rm, you will need to follow it up with git add <fileRemoved>. git rm does this in one step.

You can also use git rm --cached which will remove the file from the index (staging it for deletion on the next commit), but keep your copy in the local file system.

Allow only numbers and dot in script

You can use this

Javascript

function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)&&(charCode!=46)) {
        return false;
    }
    return true;
}

Usage

 <input onkeypress="return isNumber(event)" class="form-control">

Using Enum values as String literals

package com.common.test;

public  enum Days {


    monday(1,"Monday"),tuesday(2,"Tuesday"),wednesday(3,"Wednesday"),
    thrusday(4,"Thrusday"),friday(5,"Friday"),saturday(6,"Saturday"),sunday(7,"Sunday");

    private int id;
    private String desc;


    Days(int id,String desc){
        this.id=id;
        this.desc=desc;
    }

    public static String getDay(int id){

        for (Days day : Days.values()) {
            if (day.getId() == id) {
                return day.getDesc();
            }
        }
        return null;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }



};

Delete element in a slice

In golang's wiki it show some tricks for slice, including delete an element from slice.

Link: enter link description here

For example a is the slice which you want to delete the number i element.

a = append(a[:i], a[i+1:]...)

OR

a = a[:i+copy(a[i:], a[i+1:])]

I need to convert an int variable to double

You have to cast one (or both) of the arguments to the division operator to double:

double firstSolution = (b1 * a22 - b2 * a12) / (double)(a11 * a22 - a12 * a21);

Since you are performing the same calculation twice I'd recommend refactoring your code:

double determinant = a11 * a22 - a12 * a21;
double firstSolution = (b1 * a22 - b2 * a12) / determinant;
double secondSolution = (b2 * a11 - b1 * a21) / determinant;

This works in the same way, but now there is an implicit cast to double. This conversion from int to double is an example of a widening primitive conversion.

In Maven how to exclude resources from the generated jar?

By convention, the directory src/main/resources contains the resources that will be used by the application. So Maven will include them in the final JAR.

Thus in your application, you will access them using the getResourceAsStream() method, as the resources are loaded in the classpath.

If you need to have them outside your application, do not store them in src/main/resources as they will be bundled by Maven. Of course, you can exclude them (using the link given by chkal) but it is better to create another directory (for example src/main/external-resources) in order to keep the conventions regarding the src/main/resources directory.

In the latter case, you will have to deliver the resources independently as your JAR file (this can be achieved by using the Assembly plugin). If you need to access them in your Eclipse environment, go to the Properties of your project, then in Java Build Path in Sources tab, add the folder (for example src/main/external-resources). Eclipse will then add this directory in the classpath.

window.history.pushState refreshing the browser

window.history.pushState({urlPath:'/page1'},"",'/page1')

Only works after page is loaded, and when you will click on refresh it doesn't mean that there is any real URL.

What you should do here is knowing to which URL you are getting redirected when you reload this page. And on that page you can get the conditions by getting the current URL and making all of your conditions.

tar: add all files and directories in current directory INCLUDING .svn and so on

If disk space space is not an issue, this could also be a very easy thing to do:

mkdir backup
cp -r ./* backup
tar -zcvf backup.tar.gz ./backup

Cast Object to Generic Type for returning

If you do not want to depend on throwing exception (which you probably should not) you can try this:

public static <T> T cast(Object o, Class<T> clazz) {
    return clazz.isInstance(o) ? clazz.cast(o) : null;
}

Keystore type: which one to use?

There are a few more types than what's listed in the standard name list you've linked to. You can find more in the cryptographic providers documentation. The most common are certainly JKS (the default) and PKCS12 (for PKCS#12 files, often with extension .p12 or sometimes .pfx).

JKS is the most common if you stay within the Java world. PKCS#12 isn't Java-specific, it's particularly convenient to use certificates (with private keys) backed up from a browser or coming from OpenSSL-based tools (keytool wasn't able to convert a keystore and import its private keys before Java 6, so you had to use other tools).

If you already have a PKCS#12 file, it's often easier to use the PKCS12 type directly. It's possible to convert formats, but it's rarely necessary if you can choose the keystore type directly.

In Java 7, PKCS12 was mainly useful as a keystore but less for a truststore (see the difference between a keystore and a truststore), because you couldn't store certificate entries without a private key. In contrast, JKS doesn't require each entry to be a private key entry, so you can have entries that contain only certificates, which is useful for trust stores, where you store the list of certificates you trust (but you don't have the private key for them).

This has changed in Java 8, so you can now have certificate-only entries in PKCS12 stores too. (More details about these changes and further plans can be found in JEP 229: Create PKCS12 Keystores by Default.)

There are a few other keystore types, perhaps less frequently used (depending on the context), those include:

  • PKCS11, for PKCS#11 libraries, typically for accessing hardware cryptographic tokens, but the Sun provider implementation also supports NSS stores (from Mozilla) through this.
  • BKS, using the BouncyCastle provider (commonly used for Android).
  • Windows-MY/Windows-ROOT, if you want to access the Windows certificate store directly.
  • KeychainStore, if you want to use the OSX keychain directly.

How to round a number to n decimal places in Java

Assuming value is a double, you can do:

(double)Math.round(value * 100000d) / 100000d

That's for 5 digits precision. The number of zeros indicate the number of decimals.

Virtualbox shared folder permissions

Add yourself to the vboxsf group within the guest VM.

Solution 1

Run sudo adduser $USER vboxsf from terminal.
(On Suse it's sudo usermod --append --groups vboxsf $USER)

To take effect you should log out and then log in, or you may need to reboot.

Solution 2

Edit the file /etc/group (you will need root privileges). Look for the line vboxsf:x:999 and add at the end :yourusername -- use this solution if you don't have sudo.

To take effect you should log out and then log in, or you may need to reboot.

Best radio-button implementation for IOS

I've written a controller for handling the logic behind an array of radio buttons. It's open source and on GitHub, check it out!

https://github.com/goosoftware/GSRadioButtonSetController

unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.9

I increase max memory to start node-chrome with -Xmx3g, and it's work for me

Propagate all arguments in a bash shell script

If you include $@ in a quoted string with other characters the behavior is very odd when there are multiple arguments, only the first argument is included inside the quotes.

Example:

#!/bin/bash
set -x
bash -c "true foo $@"

Yields:

$ bash test.sh bar baz
+ bash -c 'true foo bar' baz

But assigning to a different variable first:

#!/bin/bash
set -x
args="$@"
bash -c "true foo $args"

Yields:

$ bash test.sh bar baz
+ args='bar baz'
+ bash -c 'true foo bar baz'

Make a directory and copy a file

Use the FileSystemObject object, namely, its CreateFolder and CopyFile methods. Basically, this is what your script will look like:

Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")

' Create a new folder
oFSO.CreateFolder "C:\MyFolder"

' Copy a file into the new folder
' Note that the destination folder path must end with a path separator (\)
oFSO.CopyFile "\\server\folder\file.ext", "C:\MyFolder\"

You may also want to add additional logic, like checking whether the folder you want to create already exists (because CreateFolder raises an error in this case) or specifying whether or not to overwrite the file being copied. So, you can end up with this:

Const strFolder = "C:\MyFolder\", strFile = "\\server\folder\file.ext"
Const Overwrite = True
Dim oFSO

Set oFSO = CreateObject("Scripting.FileSystemObject")

If Not oFSO.FolderExists(strFolder) Then
  oFSO.CreateFolder strFolder
End If

oFSO.CopyFile strFile, strFolder, Overwrite

how to use Spring Boot profiles

mvn spring-boot:run -Dspring-boot.run.profiles=foo,bar

**Source- **https://docs.spring.io/spring-boot/docs/current/maven-plugin/examples/run-profiles.html

Basically it is need when you multiple application-{environment}.properties is present inside in your project. by default, if you passed -Drun.profiles on command line or activeByDefault true in

 <profile>
    <id>dev</id>
    <properties>
        <activatedProperties>dev</activatedProperties>
    </properties>
    <activation>
        <activeByDefault>true</activeByDefault>
    </activation>
</profile>

Nothing defined like above it will choose by default application.properties otherwise you need to select by appending -Drun.profiles={dev/stage/prod}.

TL;DR

mvn spring-boot:run -Drun.profiles=dev

How to execute Python code from within Visual Studio Code

  1. First you have install an extension called "Code Runner"
  2. After than look at the right top corner of VS Code, you will see the run button and hit this.
  3. And you can see at the bottom of vs code your code is executed.
  4. You can make your own keyboard shortcut for "Code Runner" to speed up your coding.

What are database normal forms and can you give examples?

Here's a quick, admittedly butchered response, but in a sentence:

1NF : Your table is organized as an unordered set of data, and there are no repeating columns.

2NF: You don't repeat data in one column of your table because of another column.

3NF: Every column in your table relates only to your table's key -- you wouldn't have a column in a table that describes another column in your table which isn't the key.

For more detail, see wikipedia...

A div with auto resize when changing window width\height

In this scenario, the outer <div> has a width and height of 90%. The inner div> has a width of 100% of its parent. Both scale when re-sizing the window.

HTML

<div>
    <div>Hello there</div>
</div>

CSS

html, body {
    width: 100%;
    height: 100%;
}

body > div {
    width: 90%;
    height: 100%;
    background: green;
}

body > div > div {
    width: 100%;
    background: red;
}

Demo

Try before buy

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

For my case, the problem was due to losing of the internet connection in my WiFi.

Get timezone from users browser using moment(timezone).js

You can also get your wanted time using the following JS code:

new Date(`${post.data.created_at} GMT+0200`)

In this example, my received dates were in GMT+0200 timezone. Instead of it can be every single timezone. And the returned data will be the date in your timezone. Hope this will help anyone to save time

Using CMake with GNU Make: How can I see the exact commands?

If you use the CMake GUI then swap to the advanced view and then the option is called CMAKE_VERBOSE_MAKEFILE.

Number of processors/cores in command line

If you need an os independent method, works across Windows and Linux. Use python

$ python -c 'import multiprocessing as m; print m.cpu_count()'
16

Validating input using java.util.Scanner

If you are parsing string data from the console or similar, the best way is to use regular expressions. Read more on that here: http://java.sun.com/developer/technicalArticles/releases/1.4regex/

Otherwise, to parse an int from a string, try Integer.parseInt(string). If the string is not a number, you will get an exception. Otherise you can then perform your checks on that value to make sure it is not negative.

String input;
int number;
try
{
    number = Integer.parseInt(input);
    if(number > 0)
    {
        System.out.println("You positive number is " + number);
    }
} catch (NumberFormatException ex)
{
     System.out.println("That is not a positive number!");
}

To get a character-only string, you would probably be better of looping over each character checking for digits, using for instance Character.isLetter(char).

String input
for(int i = 0; i<input.length(); i++)
{
   if(!Character.isLetter(input.charAt(i)))
   {
      System.out.println("This string does not contain only letters!");
      break;
   }
}

Good luck!

how to read a text file using scanner in Java?

If you are working in some IDE like Eclipse or NetBeans, you should have that a.txt file in the root directory of your project. (and not in the folder where your .class files are built or anywhere else)

If not, you should specify the absolute path to that file.


Edit:
You would put the .txt file in the same place with the .class(usually also the .java file because you compile in the same folder) compiled files if you compile it by hand with javac. This is because it uses the relative path and the path tells the JVM the path where the executable file is located.

If you use some IDE, it will generate the compiled files for you using a Makefile or something similar for Windows and will consider it's default file structure, so he knows that the relative path begins from the root folder of the project.

Override standard close (X) button in a Windows Form

One thing these answers lack, and which newbies are probably looking for, is that while it's nice to have an event:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    // do something
}

It's not going to do anything at all unless you register the event. Put this in the class constructor:

this.FormClosing += Form1_FormClosing;

PHP error: Notice: Undefined index:

I did define all the variables that was the first thing I checked. I know it's not required in PHP, but old habits die hard. Then I sanatized the info like this:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name1"])) {
    $name1Err = " First Name is a required field.";
  } else {
      $name1 = test_input($_POST["name1"]);
    // check if name only contains letters and whitespace
      if (!preg_match("/^[a-zA-Z ]*$/",$name1)) {
      $name1Err = "Only letters and white space allowed";

of course test_input is another function that does a trim, strilashes, and htmlspecialchars. I think the input is pretty well sanitized. Not trying to be rude just showing what I did. When it came to the email I also checked to see if it was the proper format. I think the real answer is in the fact that some variables are local and some are global. I have got it working without errors for now so, while I'm extremely busy right now I'll accept shutting off errors as my answer. Don't worry I'll figure it out it's just not vitally important right now!

Matplotlib 2 Subplots, 1 Colorbar

I noticed that almost every solution posted involved ax.imshow(im, ...) and did not normalize the colors displayed to the colorbar for the multiple subfigures. The im mappable is taken from the last instance, but what if the values of the multiple im-s are different? (I'm assuming these mappables are treated in the same way that the contour-sets and surface-sets are treated.) I have an example using a 3d surface plot below that creates two colorbars for a 2x2 subplot (one colorbar per one row). Although the question asks explicitly for a different arrangement, I think the example helps clarify some things. I haven't found a way to do this using plt.subplots(...) yet because of the 3D axes unfortunately.

Example Plot

If only I could position the colorbars in a better way... (There is probably a much better way to do this, but at least it should be not too difficult to follow.)

import matplotlib
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

cmap = 'plasma'
ncontours = 5

def get_data(row, col):
    """ get X, Y, Z, and plot number of subplot
        Z > 0 for top row, Z < 0 for bottom row """
    if row == 0:
        x = np.linspace(1, 10, 10, dtype=int)
        X, Y = np.meshgrid(x, x)
        Z = np.sqrt(X**2 + Y**2)
        if col == 0:
            pnum = 1
        else:
            pnum = 2
    elif row == 1:
        x = np.linspace(1, 10, 10, dtype=int)
        X, Y = np.meshgrid(x, x)
        Z = -np.sqrt(X**2 + Y**2)
        if col == 0:
            pnum = 3
        else:
            pnum = 4
    print("\nPNUM: {}, Zmin = {}, Zmax = {}\n".format(pnum, np.min(Z), np.max(Z)))
    return X, Y, Z, pnum

fig = plt.figure()
nrows, ncols = 2, 2
zz = []
axes = []
for row in range(nrows):
    for col in range(ncols):
        X, Y, Z, pnum = get_data(row, col)
        ax = fig.add_subplot(nrows, ncols, pnum, projection='3d')
        ax.set_title('row = {}, col = {}'.format(row, col))
        fhandle = ax.plot_surface(X, Y, Z, cmap=cmap)
        zz.append(Z)
        axes.append(ax)

## get full range of Z data as flat list for top and bottom rows
zz_top = zz[0].reshape(-1).tolist() + zz[1].reshape(-1).tolist()
zz_btm = zz[2].reshape(-1).tolist() + zz[3].reshape(-1).tolist()
## get top and bottom axes
ax_top = [axes[0], axes[1]]
ax_btm = [axes[2], axes[3]]
## normalize colors to minimum and maximum values of dataset
norm_top = matplotlib.colors.Normalize(vmin=min(zz_top), vmax=max(zz_top))
norm_btm = matplotlib.colors.Normalize(vmin=min(zz_btm), vmax=max(zz_btm))
cmap = cm.get_cmap(cmap, ncontours) # number of colors on colorbar
mtop = cm.ScalarMappable(cmap=cmap, norm=norm_top)
mbtm = cm.ScalarMappable(cmap=cmap, norm=norm_btm)
for m in (mtop, mbtm):
    m.set_array([])

# ## create cax to draw colorbar in
# cax_top = fig.add_axes([0.9, 0.55, 0.05, 0.4])
# cax_btm = fig.add_axes([0.9, 0.05, 0.05, 0.4])
cbar_top = fig.colorbar(mtop, ax=ax_top, orientation='vertical', shrink=0.75, pad=0.2) #, cax=cax_top)
cbar_top.set_ticks(np.linspace(min(zz_top), max(zz_top), ncontours))
cbar_btm = fig.colorbar(mbtm, ax=ax_btm, orientation='vertical', shrink=0.75, pad=0.2) #, cax=cax_btm)
cbar_btm.set_ticks(np.linspace(min(zz_btm), max(zz_btm), ncontours))

plt.show()
plt.close(fig)
## orientation of colorbar = 'horizontal' if done by column

Regular expression negative lookahead

A negative lookahead says, at this position, the following regex can not match.

Let's take a simplified example:

a(?!b(?!c))

a      Match: (?!b) succeeds
ac     Match: (?!b) succeeds
ab     No match: (?!b(?!c)) fails
abe    No match: (?!b(?!c)) fails
abc    Match: (?!b(?!c)) succeeds

The last example is a double negation: it allows a b followed by c. The nested negative lookahead becomes a positive lookahead: the c should be present.

In each example, only the a is matched. The lookahead is only a condition, and does not add to the matched text.

Converting milliseconds to a date (jQuery/JavaScript)

If you want custom formatting for your date I offer a simple function for it:

var now = new Date;
console.log( now.customFormat( "#DD#/#MM#/#YYYY# #hh#:#mm#:#ss#" ) );

Here are the tokens supported:

token:     description:             example:
#YYYY#     4-digit year             1999
#YY#       2-digit year             99
#MMMM#     full month name          February
#MMM#      3-letter month name      Feb
#MM#       2-digit month number     02
#M#        month number             2
#DDDD#     full weekday name        Wednesday
#DDD#      3-letter weekday name    Wed
#DD#       2-digit day number       09
#D#        day number               9
#th#       day ordinal suffix       nd
#hhhh#     2-digit 24-based hour    17
#hhh#      military/24-based hour   17
#hh#       2-digit hour             05
#h#        hour                     5
#mm#       2-digit minute           07
#m#        minute                   7
#ss#       2-digit second           09
#s#        second                   9
#ampm#     "am" or "pm"             pm
#AMPM#     "AM" or "PM"             PM

And here's the code:

//*** This code is copyright 2002-2016 by Gavin Kistner, [email protected]
//*** It is covered under the license viewable at http://phrogz.net/JS/_ReuseLicense.txt
Date.prototype.customFormat = function(formatString){
  var YYYY,YY,MMMM,MMM,MM,M,DDDD,DDD,DD,D,hhhh,hhh,hh,h,mm,m,ss,s,ampm,AMPM,dMod,th;
  YY = ((YYYY=this.getFullYear())+"").slice(-2);
  MM = (M=this.getMonth()+1)<10?('0'+M):M;
  MMM = (MMMM=["January","February","March","April","May","June","July","August","September","October","November","December"][M-1]).substring(0,3);
  DD = (D=this.getDate())<10?('0'+D):D;
  DDD = (DDDD=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][this.getDay()]).substring(0,3);
  th=(D>=10&&D<=20)?'th':((dMod=D%10)==1)?'st':(dMod==2)?'nd':(dMod==3)?'rd':'th';
  formatString = formatString.replace("#YYYY#",YYYY).replace("#YY#",YY).replace("#MMMM#",MMMM).replace("#MMM#",MMM).replace("#MM#",MM).replace("#M#",M).replace("#DDDD#",DDDD).replace("#DDD#",DDD).replace("#DD#",DD).replace("#D#",D).replace("#th#",th);
  h=(hhh=this.getHours());
  if (h==0) h=24;
  if (h>12) h-=12;
  hh = h<10?('0'+h):h;
  hhhh = hhh<10?('0'+hhh):hhh;
  AMPM=(ampm=hhh<12?'am':'pm').toUpperCase();
  mm=(m=this.getMinutes())<10?('0'+m):m;
  ss=(s=this.getSeconds())<10?('0'+s):s;
  return formatString.replace("#hhhh#",hhhh).replace("#hhh#",hhh).replace("#hh#",hh).replace("#h#",h).replace("#mm#",mm).replace("#m#",m).replace("#ss#",ss).replace("#s#",s).replace("#ampm#",ampm).replace("#AMPM#",AMPM);
};

How do I print out the contents of an object in Rails for easy debugging?

define the to_s method in your model. For example

class Person < ActiveRecord::Base
  def to_s
    "Name:#{self.name} Age:#{self.age} Weight: #{self.weight}"
  end
end

Then when you go to print it with #puts it will display that string with those variables.

Checkbox angular material checked by default

this works for me in Angular 7

// in component.ts
checked: boolean = true;

changeValue(value) {
    this.checked = !value;
}

// in component.html
<mat-checkbox value="checked" (click)="changeValue(checked)" color="primary">
   some Label
</mat-checkbox>

I hope help someone ... greetings. let me know if someone have some easiest

What is the Swift equivalent of respondsToSelector?

another possible syntax by swift..

 if let delegate = self.delegate, method = delegate.somemethod{
        method()
    }

How do I join two SQLite tables in my Android application?

An alternate way is to construct a view which is then queried just like a table. In many database managers using a view can result in better performance.

CREATE VIEW xyz SELECT q.question, a.alternative  
   FROM tbl_question AS q, tbl_alternative AS a
  WHERE q.categoryid = a.categoryid 
    AND q._id = a.questionid;

This is from memory so there may be some syntactic issues. http://www.sqlite.org/lang_createview.html

I mention this approach because then you can use SQLiteQueryBuilder with the view as you implied that it was preferred.

Run PowerShell command from command prompt (no ps1 script)

This works from my Windows 10's cmd.exe prompt

powershell -ExecutionPolicy Bypass -Command "Import-Module C:\Users\william\ps1\TravelBook; Get-TravelBook Hawaii"

This example shows

  1. how to chain multiple commands
  2. how to import module with module path
  3. how to run a function defined in the module
  4. No need for those fancy "&".

Git diff against a stash

This works for me on git version 1.8.5.2:

git diff stash HEAD

JPQL SELECT between date statement

Try this query (replace t.eventsDate with e.eventsDate):

SELECT e FROM Events e WHERE e.eventsDate BETWEEN :startDate AND :endDate

excel plot against a date time x series

Try using an X-Y Scatter graph with datetime formatted as YYYY-MM-DD HH:MM.

This provides a reasonable graph for me (using Excel 2010).

Excel Datetime XY Scatter

Get host domain from URL?

try following statement

 Uri myuri = new Uri(System.Web.HttpContext.Current.Request.Url.AbsoluteUri);
 string pathQuery = myuri.PathAndQuery;
 string hostName = myuri.ToString().Replace(pathQuery , "");

Example1

 Input : http://localhost:4366/Default.aspx?id=notlogin
 Ouput : http://localhost:4366

Example2

 Input : http://support.domain.com/default.aspx?id=12345
 Output: support.domain.com

How to pass multiple parameters in json format to a web service using jquery?

I think the best way is:

data: "{'Ids':['2','2']}"

To read this values Ids[0], Ids[1].

How to test an Oracle Stored Procedure with RefCursor return type?

Something like

create or replace procedure my_proc( p_rc OUT SYS_REFCURSOR )
as
begin
  open p_rc
   for select 1 col1
         from dual;
end;
/

variable rc refcursor;
exec my_proc( :rc );
print rc;

will work in SQL*Plus or SQL Developer. I don't have any experience with Embarcardero Rapid XE2 so I have no idea whether it supports SQL*Plus commands like this.

Associating enums with strings in C#

C# doesn't support enumerated strings, but for most situations you can use a List or Dictionary to get the desired effect.

E.g. To print pass/fail results:

List<string> PassFail = new List<string> { "FAIL", "PASS" };
bool result = true;
Console.WriteLine("Test1: " + PassFail[result.GetHashCode()]);

How to use __doPostBack()

Here's a brief tutorial on how __doPostBack() works.

To be honest, I don't use it much; at least directly. Many server controls, (e.g., Button, LinkButton, ImageButton, parts of the GridView, etc.) use __doPostBack as their post back mechanism.

SQL Query Multiple Columns Using Distinct on One Column Only

You must use an aggregate function on the columns against which you are not grouping. In this example, I arbitrarily picked the Min function. You are combining the rows with the same FruitType value. If I have two rows with the same FruitType value but different Fruit_Id values for example, what should the system do?

Select Min(tblFruit_id) As tblFruit_id
    , tblFruit_FruitType
From tblFruit
Group By tblFruit_FruitType

SQL Fiddle example

How to Force New Google Spreadsheets to refresh and recalculate?

I know that you are looking for an auto-refresh; perhaps some coming in here may be happy with a quick fix for a manual button (like the checkbox proposed above). I actually just stumbled upon a similar solution to the checkbox: select the cells you want to refresh, and then press CTRL and the "+" key. Seems to work in Office 365 v16; hope it works for others in need.

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

That is an HTTP header. You would configure your webserver or webapp to send this header ideally. Perhaps in htaccess or PHP.

Alternatively you might be able to use

<head>...<meta http-equiv="Access-Control-Allow-Origin" content="*">...</head>

I do not know if that would work. Not all HTTP headers can be configured directly in the HTML.

This works as an alternative to many HTTP headers, but see @EricLaw's comment below. This particular header is different.

Caveat

This answer is strictly about how to set headers. I do not know anything about allowing cross domain requests.

About HTTP Headers

Every request and response has headers. The browser sends this to the webserver

GET /index.htm HTTP/1.1

Then the headers

Host: www.example.com
User-Agent: (Browser/OS name and version information)
.. Additional headers indicating supported compression types and content types and other info

Then the server sends a response

Content-type: text/html
Content-length: (number of bytes in file (optional))
Date: (server clock)
Server: (Webserver name and version information)

Additional headers can be configured for example Cache-Control, it all depends on your language (PHP, CGI, Java, htaccess) and webserver (Apache, etc).

What's the difference between interface and @interface in java?

interface: defines the contract for a class which implements it

@interface: defines the contract for an annotation

How to read all of Inputstream in Server Socket JAVA

int c;
    String raw = "";
    do {
        c = inputstream.read();
        raw+=(char)c;
    } while(inputstream.available()>0);

InputStream.available() shows the available bytes only after one byte is read, hence do .. while

Invoke a second script with arguments from a script

Aha. This turned out to be a simple problem of there being spaces in the path to the script.

Changing the Invoke-Expression line to:

Invoke-Expression "& `"$scriptPath`" $argumentList"

...was enough to get it to kick off. Thanks to Neolisk for your help and feedback!

What are the differences between a program and an application?

A "program" can be as simple as a "set of instructions" to implement a logic.

It can be part of an "application", "component", "service" or another "program".

Application is a possibly a collection of coordinating program instances to solve a user's purpose.

How to find item with max value using linq?

With EF or LINQ to SQL:

var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();

With LINQ to Objects I suggest to use morelinq extension MaxBy (get morelinq from nuget):

var item = items.MaxBy(i => i.Value);

How to return a struct from a function in C++?

You have a scope problem. Define the struct before the function, not inside it.

PHP new line break in emails

if you are outputting the code as html - change /n -->
and do echo $message;

New lines (\r\n) are not working in email body

This worked for me.

$message  = nl2br("
===============================\r\n
www.domain.com \r\n
===============================\r\n
From: ".$from."\r\n
To: ".$to."\r\n
Subject: ".$subject."\r\n
Message: ".$_POST['form-message']);

What's the best way to iterate an Android Cursor?

I'd just like to point out a third alternative which also works if the cursor is not at the start position:

if (cursor.moveToFirst()) {
    do {
        // do what you need with the cursor here
    } while (cursor.moveToNext());
}

How to use Chrome's network debugger with redirects

This has been changed since v32, thanks to @Daniel Alexiuc & @Thanatos for their comments.


Current (= v32)

At the top of the "Network" tab of DevTools, there's a checkbox to switch on the "Preserve log" functionality. If it is checked, the network log is preserved on page load.

Chrome v33 DevTools Network Tab: Preserve Log

The little red dot on the left now has the purpose to switch network logging on and off completely.


Older versions

In older versions of Chrome (v21 here), there's a little, clickable red dot in the footer of the "Network" tab.

Chrome v22 DevTools Network Tab: Preserve Log Upon Navigation

If you hover over it, it will tell you, that it will "Preserve Log Upon Navigation" when it is activated. It holds the promise.

Expression must be a modifiable lvalue

You test k = M instead of k == M.
Maybe it is what you want to do, in this case, write if (match == 0 && (k = M))

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

This is a well-known issue and based on this answer you could add setLenient:

Gson gson = new GsonBuilder()
        .setLenient()
        .create();

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(client)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build();

Now, if you add this to your retrofit, it gives you another error:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

This is another well-known error you can find answer here (this error means that your server response is not well-formatted); So change server response to return something:

{
    android:[
        { ver:"1.5", name:"Cupcace", api:"Api Level 3" }
        ...
    ]
}

For better comprehension, compare your response with Github api.

Suggestion: to find out what's going on to your request/response add HttpLoggingInterceptor in your retrofit.

Based on this answer your ServiceHelper would be:

private ServiceHelper() {
        httpClient = new OkHttpClient.Builder();
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        httpClient.interceptors().add(interceptor);
        Retrofit retrofit = createAdapter().build();
        service = retrofit.create(IService.class);
    }

Also don't forget to add:

compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'

Compiling php with curl, where is curl installed?

php curl lib is just a wrapper of cUrl, so, first of all, you should install cUrl. Download the cUrl source to your linux server. Then, use the follow commands to install:

tar zxvf cUrl_src_taz
cd cUrl_src_taz
./configure --prefix=/curl/install/home
make
make test    (optional)
make install
ln -s  /curl/install/home/bin/curl-config /usr/bin/curl-config

Then, copy the head files in the "/curl/install/home/include/" to "/usr/local/include". After all above steps done, the php curl extension configuration could find the original curl, and you can use the standard php extension method to install php curl.
Hope it helps you, :)

React PropTypes : Allow different types of PropTypes for one prop

Here is pro example of using multi proptypes and single proptype.

import React, { Component } from 'react';
import { string, shape, array, oneOfType } from 'prop-types';

class MyComponent extends Component {
  /**
   * Render
   */
  render() {
    const { title, data } = this.props;

    return (
      <>
        {title}
        <br />
        {data}
      </>
    );
  }
}

/**
 * Define component props
 */
MyComponent.propTypes = {
  data: oneOfType([array, string, shape({})]),
  title: string,
};

export default MyComponent;

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

I used the following two steps which I found in the comments/posts linked in the other answers:

Step one: Convert the x.509 cert and key to a pkcs12 file

openssl pkcs12 -export -in server.crt -inkey server.key \
               -out server.p12 -name [some-alias] \
               -CAfile ca.crt -caname root

Note: Make sure you put a password on the pkcs12 file - otherwise you'll get a null pointer exception when you try to import it. (In case anyone else had this headache). (Thanks jocull!)

Note 2: You might want to add the -chain option to preserve the full certificate chain. (Thanks Mafuba)

Step two: Convert the pkcs12 file to a Java keystore

keytool -importkeystore \
        -deststorepass [changeit] -destkeypass [changeit] -destkeystore server.keystore \
        -srckeystore server.p12 -srcstoretype PKCS12 -srcstorepass some-password \
        -alias [some-alias]

Finished

OPTIONAL Step zero: Create self-signed certificate

openssl genrsa -out server.key 2048
openssl req -new -out server.csr -key server.key
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Cheers!

JSON array get length

I came here and looking how to get the number of elements inside a JSONArray. From your question i used length() like that:

JSONArray jar = myjson.getJSONArray("_types");
System.out.println(jar.length());

and it worked as expected. On the other hand jar.size();(as proposed in the other answer) is not working for me.

So for future users searching (like me) how to get the size of a JSONArray, length() works just fine.

Insertion sort vs Bubble Sort Algorithms

Another difference, I didn't see here:

Bubble sort has 3 value assignments per swap: you have to build a temporary variable first to save the value you want to push forward(no.1), than you have to write the other swap-variable into the spot you just saved the value of(no.2) and then you have to write your temporary variable in the spot other spot(no.3). You have to do that for each spot - you want to go forward - to sort your variable to the correct spot.

With insertion sort you put your variable to sort in a temporary variable and then put all variables in front of that spot 1 spot backwards, as long as you reach the correct spot for your variable. That makes 1 value assignement per spot. In the end you write your temp-variable into the the spot.

That makes far less value assignements, too.

This isn't the strongest speed-benefit, but i think it can be mentioned.

I hope, I expressed myself understandable, if not, sorry, I'm not a nativ Britain

Backporting Python 3 open(encoding="utf-8") to Python 2

Here's one way:

with open("filename.txt", "rb") as f:
    contents = f.read().decode("UTF-8")

what is right way to do API call in react js?

Use fetch method inside componentDidMount to update state:

componentDidMount(){
  fetch('https://randomuser.me/api/')
      .then(({ results }) => this.setState({ person: results }));
}

I ran into a merge conflict. How can I abort the merge?

An alternative, which preserves the state of the working copy is:

git stash
git merge --abort
git stash pop

I generally advise against this, because it is effectively like merging in Subversion as it throws away the branch relationships in the following commit.

Display unescaped HTML in Vue.js

Before using v-html, you have to make sure that the element which you escape is sanitized in case you allow user input, otherwise you expose your app to xss vulnerabilities.

More info here: https://vuejs.org/v2/guide/security.html

I highly encourage you that instead of using v-html to use this npm package

Why can't I inherit static classes?

Although you can access "inherited" static members through the inherited classes name, static members are not really inherited. This is in part why they can't be virtual or abstract and can't be overridden. In your example, if you declared a Base.Method(), the compiler will map a call to Inherited.Method() back to Base.Method() anyway. You might as well call Base.Method() explicitly. You can write a small test and see the result with Reflector.

So... if you can't inherit static members, and if static classes can contain only static members, what good would inheriting a static class do?

Javascript Error Null is not an Object

I think the error because the elements are undefined ,so you need to add window.onload event which this event will defined your elements when the window is loaded.

window.addEventListener('load',Loaded,false);


    function Loaded(){
    var myButton = document.getElementById("myButton");
    var myTextfield = document.getElementById("myTextfield");

    function greetUser(userName) {
    var greeting = "Hello " + userName + "!";
    document.getElementsByTagName ("h2")[0].innerHTML = greeting;
    }

    myButton.onclick = function() {
    var userName = myTextfield.value;
    greetUser(userName);

    return false;
    }
    }

Search for a string in Enum and return the Enum

You can use Enum.Parse to get an enum value from the name. You can iterate over all values with Enum.GetNames, and you can just cast an int to an enum to get the enum value from the int value.

Like this, for example:

public MyColours GetColours(string colour)
{
    foreach (MyColours mc in Enum.GetNames(typeof(MyColours))) {
        if (mc.ToString().Contains(colour)) {
            return mc;
        }
    }
    return MyColours.Red; // Default value
}

or:

public MyColours GetColours(string colour)
{
    return (MyColours)Enum.Parse(typeof(MyColours), colour, true); // true = ignoreCase
}

The latter will throw an ArgumentException if the value is not found, you may want to catch it inside the function and return the default value.

Where can I find "make" program for Mac OS X Lion?

Xcode 5.1 no longer provides command line tools in the Preferences section. You now go to https://developer.apple.com/downloads/index.action, and select the command line tools version for your OS X release. The installer puts them in /usr/bin.

how to set select element as readonly ('disabled' doesnt pass select value on server)

without disabling the selected value on submitting..

$('#selectID option:not(:selected)').prop('disabled', true);

If you use Jquery version lesser than 1.7
$('#selectID option:not(:selected)').attr('disabled', true);

It works for me..

Add an element to an array in Swift

You can also pass in a variable and/or object if you wanted to.

var str1:String = "John"
var str2:String = "Bob"

var myArray = ["Steve", "Bill", "Linus", "Bret"]

//add to the end of the array with append
myArray.append(str1)
myArray.append(str2)

To add them to the front:

//use 'insert' instead of append
myArray.insert(str1, atIndex:0)
myArray.insert(str2, atIndex:0)

//Swift 3
myArray.insert(str1, at: 0)
myArray.insert(str2, at: 0)

As others have already stated, you can no longer use '+=' as of xCode 6.1

PHP filesize MB/KB conversion

Even nicer is this version I created from a plugin I found:

function filesize_formatted($path)
{
    $size = filesize($path);
    $units = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
    $power = $size > 0 ? floor(log($size, 1024)) : 0;
    return number_format($size / pow(1024, $power), 2, '.', ',') . ' ' . $units[$power];
}

Note from filesize() doc

Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB

How to change the button color when it is active using bootstrap?

HTML--

<div class="col-sm-12" id="my_styles">
   <button type="submit" class="btn btn-warning" id="1">Button1</button>
   <button type="submit" class="btn btn-warning" id="2">Button2</button>
</div>

css--

.active{
         background:red;
    }
 button.btn:active{
     background:red;
 }

jQuery--

jQuery("#my_styles .btn").click(function(){
    jQuery("#my_styles .btn").removeClass('active');
    jQuery(this).toggleClass('active'); 

});

view the live demo on jsfiddle

SQL Views - no variables?

How often do you need to refresh the view? I have a similar case where the new data comes once a month; then I have to load it, and during the loading processes I have to create new tables. At that moment I alter my view to consider the changes. I used as base the information in this other question:

Create View Dynamically & synonyms

In there, it is proposed to do it 2 ways:

  1. using synonyms.
  2. Using dynamic SQL to create view (this is what helped me achieve my result).

How to "add existing frameworks" in Xcode 4?

Follow the screen shots

Go to linked framework and libraries

enter image description here

you are ready to Go!

What happens when a duplicate key is put into a HashMap?

You may find your answer in the javadoc of Map#put(K, V) (which actually returns something):

public V put(K key,
             V value)

Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for this key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)

Parameters:
key - key with which the specified value is to be associated.
value - value to be associated with the specified key.

Returns:
previous value associated with specified key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with the specified key, if the implementation supports null values.)

So if you don't assign the returned value when calling mymap.put("1", "a string"), it just becomes unreferenced and thus eligible for garbage collection.

"google is not defined" when using Google Maps V3 in Firefox remotely

You can try the following:

First, add async defer. This specifies that the script will be executed asynchronously as soon as it is available and when the page has finished parsing.

Second, add the initMap() function as a callback in a script tag inside your html. In this way the map will be initialized before the document.ready and window.onload:

<script async defer src="{{ 'https://maps.googleapis.com/maps/api/js?key=$key&language='.$language.'&region='.$country.'&callback=initMap' }}"></script>

<script>
    var map;
    function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
            center: {lat: -34.397, lng: 150.644},
            zoom: 4,
            disableDefaultUI: false,
            scrollwheel: false,
            styles: [{ ... }]
        });
    }
</script> 

Finally, you can use the map object inside your js files.

How to properly apply a lambda function into a pandas data frame column

You need to add else in your lambda function. Because you are telling what to do in case your condition(here x < 90) is met, but you are not telling what to do in case the condition is not met.

sample['PR'] = sample['PR'].apply(lambda x: 'NaN' if x < 90 else x) 

jQuery '.each' and attaching '.click' event

One solution you could use is to assign a more generalized class to any div you want the click event handler bound to.

For example:

HTML:

<body>
<div id="dog" class="selected" data-selected="false">dog</div>
<div id="cat" class="selected" data-selected="true">cat</div>
<div id="mouse" class="selected" data-selected="false">mouse</div>

<div class="dog"><img/></div>
<div class="cat"><img/></div>
<div class="mouse"><img/></div>
</body>

JS:

$( ".selected" ).each(function(index) {
    $(this).on("click", function(){
        // For the boolean value
        var boolKey = $(this).data('selected');
        // For the mammal value
        var mammalKey = $(this).attr('id'); 
    });
});

How to use PrimeFaces p:fileUpload? Listener method is never invoked or UploadedFile is null / throws an error / not usable

bean.xhtml

    <h:form enctype="multipart/form-data">    
<p:outputLabel value="Choose your file" for="submissionFile" />
                <p:fileUpload id="submissionFile"
                    value="#{bean.file}"
                    fileUploadListener="#{bean.uploadFile}" mode="advanced"
                    auto="true" dragDropSupport="false" update="messages"
                    sizeLimit="100000" fileLimit="1" allowTypes="/(\.|\/)(pdf)$/" />

</h:form>

Bean.java

@ManagedBean

@ViewScoped public class Submission implements Serializable {

private UploadedFile file;

//Gets
//Sets

public void uploadFasta(FileUploadEvent event) throws FileNotFoundException, IOException, InterruptedException {

    String content = IOUtils.toString(event.getFile().getInputstream(), "UTF-8");

    String filePath = PATH + "resources/submissions/" + nameOfMyFile + ".pdf";

    MyFileWriter.writeFile(filePath, content);

    FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
            event.getFile().getFileName() + " is uploaded.", null);
    FacesContext.getCurrentInstance().addMessage(null, message);

}

}

web.xml

    <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<filter>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
</filter-mapping>

How Can I Remove “public/index.php” in the URL Generated Laravel?

Rename the server.php in the your Laravel root folder to index.php and copy the .htaccess file from /public directory to your Laravel root folder.

Delete an element in a JSON object

with open('writing_file.json', 'w') as w:
    with open('reading_file.json', 'r') as r:
        for line in r:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            w.write(json.dumps(element))

this is the method i use..

How to get the current date and time

import org.joda.time.DateTime;

DateTime now = DateTime.now();

Sorting a list with stream.sorted() in Java

Use list.sort instead:

list.sort((o1, o2) -> o1.getItem().getValue().compareTo(o2.getItem().getValue()));

and make it more succinct using Comparator.comparing:

list.sort(Comparator.comparing(o -> o.getItem().getValue()));

After either of these, list itself will be sorted.

Your issue is that list.stream.sorted returns the sorted data, it doesn't sort in place as you're expecting.

Input from the keyboard in command line application

Before

enter image description here

*******************.

Correction

enter image description here

The simplest way to comma-delimit a list?

There is a pretty way to achieve this using Java 8:

List<String> list = Arrays.asList(array);
String joinedString = String.join(",", list);

Java: Multiple class declarations in one file

No. You can't. But it is very possible in Scala:

class Foo {val bar = "a"}
class Bar {val foo = "b"}

How to assert two list contain the same elements in Python?

Converting your lists to sets will tell you that they contain the same elements. But this method cannot confirm that they contain the same number of all elements. For example, your method will fail in this case:

L1 = [1,2,2,3]
L2 = [1,2,3,3]

You are likely better off sorting the two lists and comparing them:

def checkEqual(L1, L2):
    if sorted(L1) == sorted(L2):
        print "the two lists are the same"
        return True
    else:
        print "the two lists are not the same"
        return False

Note that this does not alter the structure/contents of the two lists. Rather, the sorting creates two new lists

Search in lists of lists by given index

You're always going to have a loop - someone might come along with a clever one-liner that hides the loop within a call to map() or similar, but it's always going to be there.

My preference would always be to have clean and simple code, unless performance is a major factor.

Here's perhaps a more Pythonic version of your code:

data = [['a','b'], ['a','c'], ['b','d']]
search = 'c'
for sublist in data:
    if sublist[1] == search:
        print "Found it!", sublist
        break
# Prints: Found it! ['a', 'c']

It breaks out of the loop as soon as it finds a match.

(You have a typo, by the way, in ['b''d'].)

What is REST call and how to send a REST call?

REST is just a software architecture style for exposing resources.

  • Use HTTP methods explicitly.
  • Be stateless.
  • Expose directory structure-like URIs.
  • Transfer XML, JavaScript Object Notation (JSON), or both.

A typical REST call to return information about customer 34456 could look like:

http://example.com/customer/34456

Have a look at the IBM tutorial for REST web services

convert string to specific datetime format?

No need to apply anything. Just add this code at the end of variable to which date is assigned. For example

   @todaydate = "2011-05-19 10:30:14"
   @todaytime.to_time.strftime('%a %b %d %H:%M:%S %Z %Y')

You will get proper format as you like. You can check this at Rails Console

Loading development environment (Rails 3.0.4)
ruby-1.9.2-p136 :001 > todaytime = "2011-05-19 10:30:14"
 => "2011-05-19 10:30:14" 
ruby-1.9.2-p136 :002 > todaytime
 => "2011-05-19 10:30:14" 
ruby-1.9.2-p136 :003 > todaytime.to_time
 => 2011-05-19 10:30:14 UTC
ruby-1.9.2-p136 :008 > todaytime.to_time.strftime('%a %b %d %H:%M:%S %Z %Y')
 => "Thu May 19 10:30:14 UTC 2011"

Try 'date_format' gem to show date in different format.

Check if selected dropdown value is empty using jQuery

Try this it will work --

if($('#EventStartTimeMin').val() === " ") {

    alert("Please enter start time!");

}

How to iterate over rows in a DataFrame in Pandas

You can write your own iterator that implements namedtuple

from collections import namedtuple

def myiter(d, cols=None):
    if cols is None:
        v = d.values.tolist()
        cols = d.columns.values.tolist()
    else:
        j = [d.columns.get_loc(c) for c in cols]
        v = d.values[:, j].tolist()

    n = namedtuple('MyTuple', cols)

    for line in iter(v):
        yield n(*line)

This is directly comparable to pd.DataFrame.itertuples. I'm aiming at performing the same task with more efficiency.


For the given dataframe with my function:

list(myiter(df))

[MyTuple(c1=10, c2=100), MyTuple(c1=11, c2=110), MyTuple(c1=12, c2=120)]

Or with pd.DataFrame.itertuples:

list(df.itertuples(index=False))

[Pandas(c1=10, c2=100), Pandas(c1=11, c2=110), Pandas(c1=12, c2=120)]

A comprehensive test
We test making all columns available and subsetting the columns.

def iterfullA(d):
    return list(myiter(d))

def iterfullB(d):
    return list(d.itertuples(index=False))

def itersubA(d):
    return list(myiter(d, ['col3', 'col4', 'col5', 'col6', 'col7']))

def itersubB(d):
    return list(d[['col3', 'col4', 'col5', 'col6', 'col7']].itertuples(index=False))

res = pd.DataFrame(
    index=[10, 30, 100, 300, 1000, 3000, 10000, 30000],
    columns='iterfullA iterfullB itersubA itersubB'.split(),
    dtype=float
)

for i in res.index:
    d = pd.DataFrame(np.random.randint(10, size=(i, 10))).add_prefix('col')
    for j in res.columns:
        stmt = '{}(d)'.format(j)
        setp = 'from __main__ import d, {}'.format(j)
        res.at[i, j] = timeit(stmt, setp, number=100)

res.groupby(res.columns.str[4:-1], axis=1).plot(loglog=True);

enter image description here

enter image description here

How do I sort a Set to a List in Java?

You can convert a set into an ArrayList, where you can sort the ArrayList using Collections.sort(List).

Here is the code:

keySet = (Set) map.keySet();
ArrayList list = new ArrayList(keySet);     
Collections.sort(list);

What is the difference between ManualResetEvent and AutoResetEvent in .NET?

Yes, thats right.

You can get an idea by the usage of these two.

If you need to tell that you are finished with some work and other (threads) waiting for this can now proceed, you should use ManualResetEvent.

If you need to have mutual exclusive access to any resource, you should use AutoResetEvent.

jQuery: Wait/Delay 1 second without executing code

If you are using ES6 features and you're in an async function, you can effectively halt the code execution for a certain time with this function:

const delay = millis => new Promise((resolve, reject) => {
  setTimeout(_ => resolve(), millis)
});

This is how you use it:

await delay(5000);

It will stall for the requested amount of milliseconds, but only if you're in an async function. Example below:

const myFunction = async function() {
  // first code block ...

  await delay(5000);

  // some more code, executed 5 seconds after the first code block finishes
}

CSS transition with visibility not working

This is not a bug- you can only transition on ordinal/calculable properties (an easy way of thinking of this is any property with a numeric start and end number value..though there are a few exceptions).

This is because transitions work by calculating keyframes between two values, and producing an animation by extrapolating intermediate amounts.

visibility in this case is a binary setting (visible/hidden), so once the transition duration elapses, the property simply switches state, you see this as a delay- but it can actually be seen as the final keyframe of the transition animation, with the intermediary keyframes not having been calculated (what constitutes the values between hidden/visible? Opacity? Dimension? As it is not explicit, they are not calculated).

opacity is a value setting (0-1), so keyframes can be calculated across the duration provided.

A list of transitionable (animatable) properties can be found here

Delete item from array and shrink array

without using the System.arraycopy method you can delete an element from an array with the following

    int i = 0;
    int x = 0;
    while(i < oldArray.length){
        if(oldArray[i] == 3)i++;

        intArray[x] = oldArray[i];
        i++;
        x++;
    }

where 3 is the value you want to remove.

Correct way of looping through C++ arrays

sizeof tells you the size of a thing, not the number of elements in it. A more C++11 way to do what you are doing would be:

#include <array>
#include <string>
#include <iostream>

int main()
{
    std::array<std::string, 3> texts { "Apple", "Banana", "Orange" };
    for (auto& text : texts) {
        std::cout << text << '\n';
    }
    return 0;
}

ideone demo: http://ideone.com/6xmSrn

How to "grep" for a filename instead of the contents of a file?

As Pablo said, you need to use find instead of grep, but there's no need to pipe find to grep. find has that functionality built in:

find . -regex 'f[[:alnum:]]\.frm'

find is a very powerful program for searching for files by name and supports searching by file type, depth limiting, combining different search terms with boolean operations, and executing arbitrary commands on found files. See the find man page for more information.

Can I add a custom attribute to an HTML tag?

use data-any , I use them a lot

<aside data-area="asidetop" data-type="responsive" class="top">

Why would you use String.Equals over ==?

There's a writeup on this article which you might find to be interesting, with some quotes from Jon Skeet. It seems like the use is pretty much the same.

Jon Skeet states that the performance of instance Equals "is slightly better when the strings are short—as the strings increase in length, that difference becomes completely insignificant."

Convert date field into text in Excel

If that is one table and have nothing to do with this - the simplest solution can be copy&paste to notepad then copy&paste back to excel :P

html button to send email

You can use mailto, here is the HTML code:

<a href="mailto:EMAILADDRESS">

Replace EMAILADDRESS with your email.

Check whether values in one data frame column exist in a second data frame

Use %in% as follows

A$C %in% B$C

Which will tell you which values of column C of A are in B.

What is returned is a logical vector. In the specific case of your example, you get:

A$C %in% B$C
# [1]  TRUE FALSE  TRUE  TRUE

Which you can use as an index to the rows of A or as an index to A$C to get the actual values:

# as a row index
A[A$C %in% B$C,  ]  # note the comma to indicate we are indexing rows

# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4  # returns all values of A$C that are in B$C

We can negate it too:

A$C[!A$C %in% B$C]
[1] 2   # returns all values of A$C that are NOT in B$C



If you want to know if a specific value is in B$C, use the same function:

  2 %in% B$C   # "is the value 2 in B$C ?"  
  # FALSE

  A$C[2] %in% B$C  # "is the 2nd element of A$C in B$C ?"  
  # FALSE

How to list the files inside a JAR file?

erickson's answer worked perfectly:

Here's the working code.

CodeSource src = MyClass.class.getProtectionDomain().getCodeSource();
List<String> list = new ArrayList<String>();

if( src != null ) {
    URL jar = src.getLocation();
    ZipInputStream zip = new ZipInputStream( jar.openStream());
    ZipEntry ze = null;

    while( ( ze = zip.getNextEntry() ) != null ) {
        String entryName = ze.getName();
        if( entryName.startsWith("images") &&  entryName.endsWith(".png") ) {
            list.add( entryName  );
        }
    }

 }
 webimages = list.toArray( new String[ list.size() ] );

And I have just modify my load method from this:

File[] webimages = ... 
BufferedImage image = ImageIO.read(this.getClass().getResource(webimages[nextIndex].getName() ));

To this:

String  [] webimages = ...

BufferedImage image = ImageIO.read(this.getClass().getResource(webimages[nextIndex]));

HttpWebRequest-The remote server returned an error: (400) Bad Request

What type of authentication do you use? Send the credentials using the properties Ben said before and setup a cookie handler. You already allow redirection, check your webserver if any redirection occurs (NTLM auth does for sure). If there is a redirection you need to store the session which is mostly stored in a session cookie.

org.hibernate.MappingException: Unknown entity

You can enable entity scan by adding below annotation on Application .java @EntityScan(basePackageClasses=YourEntityClassName.class)

Or you can set the packageToScan in your session factory. sessionFactory.setPackagesToScan(“com.all.entity”);

How to make vim paste from (and copy to) system's clipboard?

The "* and "+ registers are for the system's clipboard (:help registers). Depending on your system, they may do different things. For instance, on systems that don't use X11 like OSX or Windows, the "* register is used to read and write to the system clipboard. On X11 systems both registers can be used. See :help x11-selection for more details, but basically the "* is analogous to X11's _PRIMARY_ selection (which usually copies things you select with the mouse and pastes with the middle mouse button) and "+ is analogous to X11's _CLIPBOARD_ selection (which is the clipboard proper).

If all that went over your head, try using "*yy or "+yy to copy a line to your system's clipboard. Assuming you have the appropriate compile options, one or the other should work.

You might like to remap this to something more convenient for you. For example, you could put vnoremap <C-c> "*y in your ~/.vimrc so that you can visually select and press Ctrl+c to yank to your system's clipboard.

Be aware that copying/pasting from the system clipboard will not work if :echo has('clipboard') returns 0. In this case, vim is not compiled with the +clipboard feature and you'll have to install a different version or recompile it. Some linux distros supply a minimal vim installation by default, but if you install the vim-gtk or vim-gtk3 package you can get the extra features nonetheless.

You also may want to have a look at the 'clipboard' option described in :help cb. In this case you can :set clipboard=unnamed or :set clipboard=unnamedplus to make all yanking/deleting operations automatically copy to the system clipboard. This could be an inconvenience in some cases where you are storing something else in the clipboard as it will override it.

To paste you can use "+p or "*p (again, depending on your system and/or desired selection) or you can map these to something else. I type them explicitly, but I often find myself in insert mode. If you're in insert mode you can still paste them with proper indentation by using <C-r><C-p>* or <C-r><C-p>+. See :help i_CTRL-R_CTRL-P.

It's also worth mentioning vim's paste option (:help paste). This puts vim into a special "paste mode" that disables several other options, allowing you to easily paste into vim using your terminal emulator's or multiplexer's familiar paste shortcut. (Simply type :set paste to enable it, paste your content and then type :set nopaste to disable it.) Alternatively, you can use the pastetoggle option to set a keycode that toggles the mode (:help pastetoggle).

I recommend using registers instead of these options, but if they are still too scary, this can be a convenient workaround while you're perfecting your vim chops.

See :help clipboard for more detailed information.

How to explicitly obtain post data in Spring MVC?

Spring MVC runs on top of the Servlet API. So, you can use HttpServletRequest#getParameter() for this:

String value1 = request.getParameter("value1");
String value2 = request.getParameter("value2");

The HttpServletRequest should already be available to you inside Spring MVC as one of the method arguments of the handleRequest() method.

enabling cross-origin resource sharing on IIS7

I can't post comments so I have to put this in a separate answer, but it's related to the accepted answer by Shah.

I initially followed Shahs answer (thank you!) by re configuring the OPTIONSVerbHandler in IIS, but my settings were restored when I redeployed my application.

I ended up removing the OPTIONSVerbHandler in my Web.config instead.

<handlers>
    <remove name="OPTIONSVerbHandler"/>
</handlers>

Close pre-existing figures in matplotlib when running from eclipse

Nothing works in my case using the scripts above but I was able to close these figures from eclipse console bar by clicking on Terminate ALL (two red nested squares icon).

How to add a new line in textarea element?

I think you are confusing the syntax of different languages.

  • &#10; is (the HtmlEncoded value of ASCII 10 or) the linefeed character literal in a HTML string. But the line feed character does NOT render as a line break in HTML (see notes at bottom).

  • \n is the linefeed character literal (ASCII 10) in a Javascript string.

  • <br/> is a line break in HTML. Many other elements, eg <p>, <div>, etc also render line breaks unless overridden with some styles.

Hopefully the following illustration will make it clearer:

_x000D_
_x000D_
T.innerText = "Position of LF: " + t.value.indexOf("\n");_x000D_
_x000D_
p1.innerHTML = t.value;_x000D_
p2.innerHTML = t.value.replace("\n", "<br/>");_x000D_
p3.innerText = t.value.replace("\n", "<br/>");
_x000D_
<textarea id="t">Line 1&#10;Line 2</textarea>_x000D_
_x000D_
<p id='T'></p>_x000D_
<p id='p1'></p>_x000D_
<p id='p2'></p>_x000D_
<p id='p3'></p>
_x000D_
_x000D_
_x000D_

A few points to note about Html:

  • The innerHTML value of the TEXTAREA element does not render Html. Try the following: <textarea>A <a href='x'>link</a>.</textarea> to see.
  • The P element renders all contiguous white spaces (including new lines) as one space.
  • The LF character does not render to a new line or line break in HTML.
  • The TEXTAREA renders LF as a new line inside the text area box.

How to check if BigDecimal variable == 0 in java?

GriffeyDog is definitely correct:

Code:

BigDecimal myBigDecimal = new BigDecimal("00000000.000000");
System.out.println("bestPriceBigDecimal=" + myBigDecimal);
System.out.println("BigDecimal.valueOf(0.000000)=" + BigDecimal.valueOf(0.000000));
System.out.println(" equals=" + myBigDecimal.equals(BigDecimal.ZERO));
System.out.println("compare=" + (0 == myBigDecimal.compareTo(BigDecimal.ZERO)));

Results:

myBigDecimal=0.000000
BigDecimal.valueOf(0.000000)=0.0
 equals=false
compare=true

While I understand the advantages of the BigDecimal compare, I would not consider it an intuitive construct (like the ==, <, >, <=, >= operators are). When you are holding a million things (ok, seven things) in your head, then anything you can reduce your cognitive load is a good thing. So I built some useful convenience functions:

public static boolean equalsZero(BigDecimal x) {
    return (0 == x.compareTo(BigDecimal.ZERO));
}
public static boolean equals(BigDecimal x, BigDecimal y) {
    return (0 == x.compareTo(y));
}
public static boolean lessThan(BigDecimal x, BigDecimal y) {
    return (-1 == x.compareTo(y));
}
public static boolean lessThanOrEquals(BigDecimal x, BigDecimal y) {
    return (x.compareTo(y) <= 0);
}
public static boolean greaterThan(BigDecimal x, BigDecimal y) {
    return (1 == x.compareTo(y));
}
public static boolean greaterThanOrEquals(BigDecimal x, BigDecimal y) {
    return (x.compareTo(y) >= 0);
}

Here is how to use them:

    System.out.println("Starting main Utils");
    BigDecimal bigDecimal0 = new BigDecimal(00000.00);
    BigDecimal bigDecimal2 = new BigDecimal(2);
    BigDecimal bigDecimal4 = new BigDecimal(4);  
    BigDecimal bigDecimal20 = new BigDecimal(2.000);
    System.out.println("Positive cases:");
    System.out.println("bigDecimal0=" + bigDecimal0 + " == zero is " + Utils.equalsZero(bigDecimal0));
    System.out.println("bigDecimal2=" + bigDecimal2 + " <  bigDecimal4=" + bigDecimal4 + " is " + Utils.lessThan(bigDecimal2, bigDecimal4));
    System.out.println("bigDecimal2=" + bigDecimal2 + " == bigDecimal20=" + bigDecimal20 + " is " + Utils.equals(bigDecimal2, bigDecimal20));
    System.out.println("bigDecimal2=" + bigDecimal2 + " <= bigDecimal20=" + bigDecimal20 + " is " + Utils.equals(bigDecimal2, bigDecimal20));
    System.out.println("bigDecimal2=" + bigDecimal2 + " <= bigDecimal4=" + bigDecimal4 + " is " + Utils.lessThanOrEquals(bigDecimal2, bigDecimal4));
    System.out.println("bigDecimal4=" + bigDecimal4 + " >  bigDecimal2=" + bigDecimal2 + " is " + Utils.greaterThan(bigDecimal4, bigDecimal2));
    System.out.println("bigDecimal4=" + bigDecimal4 + " >= bigDecimal2=" + bigDecimal2 + " is " + Utils.greaterThanOrEquals(bigDecimal4, bigDecimal2));
    System.out.println("bigDecimal2=" + bigDecimal2 + " >= bigDecimal20=" + bigDecimal20 + " is " + Utils.greaterThanOrEquals(bigDecimal2, bigDecimal20));
    System.out.println("Negative cases:");
    System.out.println("bigDecimal2=" + bigDecimal2 + " == zero is " + Utils.equalsZero(bigDecimal2));
    System.out.println("bigDecimal2=" + bigDecimal2 + " == bigDecimal4=" + bigDecimal4 + " is " + Utils.equals(bigDecimal2, bigDecimal4));
    System.out.println("bigDecimal4=" + bigDecimal4 + " <  bigDecimal2=" + bigDecimal2 + " is " + Utils.lessThan(bigDecimal4, bigDecimal2));
    System.out.println("bigDecimal4=" + bigDecimal4 + " <= bigDecimal2=" + bigDecimal2 + " is " + Utils.lessThanOrEquals(bigDecimal4, bigDecimal2));
    System.out.println("bigDecimal2=" + bigDecimal2 + " >  bigDecimal4=" + bigDecimal4 + " is " + Utils.greaterThan(bigDecimal2, bigDecimal4));
    System.out.println("bigDecimal2=" + bigDecimal2 + " >= bigDecimal4=" + bigDecimal4 + " is " + Utils.greaterThanOrEquals(bigDecimal2, bigDecimal4));

The results look like this:

Positive cases:
bigDecimal0=0 == zero is true
bigDecimal2=2 <  bigDecimal4=4 is true
bigDecimal2=2 == bigDecimal20=2 is true
bigDecimal2=2 <= bigDecimal20=2 is true
bigDecimal2=2 <= bigDecimal4=4 is true
bigDecimal4=4 >  bigDecimal2=2 is true
bigDecimal4=4 >= bigDecimal2=2 is true
bigDecimal2=2 >= bigDecimal20=2 is true
Negative cases:
bigDecimal2=2 == zero is false
bigDecimal2=2 == bigDecimal4=4 is false
bigDecimal4=4 <  bigDecimal2=2 is false
bigDecimal4=4 <= bigDecimal2=2 is false
bigDecimal2=2 >  bigDecimal4=4 is false
bigDecimal2=2 >= bigDecimal4=4 is false

C# Switch-case string starting with

If the problem domain has some kind of string header concept, this could be modelled as an enum.

switch(GetStringHeader(s))
{
    case StringHeader.ABC: ...
    case StringHeader.QWERTY: ...
    ...
}

StringHeader GetStringHeader(string s)
{
    if (s.StartsWith("ABC")) return StringHeader.ABC;
    ...
}

enum StringHeader { ABC, QWERTY, ... }