Programs & Examples On #Trilateration

How to get out of while loop in java with Scanner method "hasNext" as condition?

You can simply use one of the system dependent end-of-file indicators ( d for Unix/Linux/Ubuntu, z for windows) to make the while statement false. This should get you out of the loop nicely. :)

Difference between & and && in Java?

& is bitwise AND operator comparing bits of each operand.
For example,

int a = 4;
int b = 7;
System.out.println(a & b); // prints 4
//meaning in an 32 bit system
// 00000000 00000000 00000000 00000100
// 00000000 00000000 00000000 00000111
// ===================================
// 00000000 00000000 00000000 00000100


&& is logical AND operator comparing boolean values of operands only. It takes two operands indicating a boolean value and makes a lazy evaluation on them.

Debugging WebSocket in Google Chrome

I have used Chrome extension called Simple WebSocket Client v0.1.3 that is published by user hakobera. It is very simple in its usage where it allows opening websockets on a given URL, send messages and close the socket connection. It is very minimalistic.

How to get Map data using JDBCTemplate.queryForMap

I know this is really old, but this is the simplest way to query for Map.

Simply implement the ResultSetExtractor interface to define what type you want to return. Below is an example of how to use this. You'll be mapping it manually, but for a simple map, it should be straightforward.

jdbcTemplate.query("select string1,string2 from table where x=1", new ResultSetExtractor<Map>(){
    @Override
    public Map extractData(ResultSet rs) throws SQLException,DataAccessException {
        HashMap<String,String> mapRet= new HashMap<String,String>();
        while(rs.next()){
            mapRet.put(rs.getString("string1"),rs.getString("string2"));
        }
        return mapRet;
    }
});

This will give you a return type of Map that has multiple rows (however many your query returned) and not a list of Maps. You can view the ResultSetExtractor docs here: http://docs.spring.io/spring-framework/docs/2.5.6/api/org/springframework/jdbc/core/ResultSetExtractor.html

Jenkins CI: How to trigger builds on SVN commit

I made a tool using Python with some bash to trigger a Jenkins build. Basically you have to collect these two values from post-commit when a commit hits the SVN server:

REPOS="$1"
REV="$2"

Then you use "svnlook dirs-changed $1 -r $2" to get the path which is has just committed. Then from that you can check which repository you want to build. Imagine you have hundred of thousand of projects. You can't check the whole repository, right?

You can check out my script from GitHub.

How may I sort a list alphabetically using jQuery?

Something like this:

var mylist = $('#myUL');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
   return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });

From this page: http://www.onemoretake.com/2009/02/25/sorting-elements-with-jquery/

Above code will sort your unordered list with id 'myUL'.

OR you can use a plugin like TinySort. https://github.com/Sjeiti/TinySort

git diff file against its last change

One of the ways to use git diff is:

git diff <commit> <path>

And a common way to refer one commit of the last commit is as a relative path to the actual HEAD. You can reference previous commits as HEAD^ (in your example this will be 123abc) or HEAD^^ (456def in your example), etc ...

So the answer to your question is:

git diff HEAD^^ myfile

Why does Date.parse give incorrect results?

Until the 5th edition spec came out, the Date.parse method was completely implementation dependent (new Date(string) is equivalent to Date.parse(string) except the latter returns a number rather than a Date). In the 5th edition spec the requirement was added to support a simplified (and slightly incorrect) ISO-8601 (also see What are valid Date Time Strings in JavaScript?). But other than that, there was no requirement for what Date.parse / new Date(string) should accept other than that they had to accept whatever Date#toString output (without saying what that was).

As of ECMAScript 2017 (edition 8), implementations were required to parse their output for Date#toString and Date#toUTCString, but the format of those strings was not specified.

As of ECMAScript 2019 (edition 9) the format for Date#toString and Date#toUTCString, have been specified as (respectively):

  1. ddd MMM DD YYYY HH:mm:ss ZZ [(timezone name)]
    e.g. Tue Jul 10 2018 18:39:58 GMT+0530 (IST)
  2. ddd, DD MMM YYYY HH:mm:ss Z
    e.g. Tue 10 Jul 2018 13:09:58 GMT

providing 2 more formats that Date.parse should parse reliably in new implementations (noting that support is not ubiquitous and non–compliant implementations will remain in use for some time).

I would recommend that date strings are parsed manually and the Date constructor used with year, month and day arguments to avoid ambiguity:

// parse a date in yyyy-mm-dd format
function parseDate(input) {

  let parts = input.split('-');

  // new Date(year, month [, day [, hours[, minutes[, seconds[, ms]]]]])
  return new Date(parts[0], parts[1]-1, parts[2]); // Note: months are 0-based
}

Global javascript variable inside document.ready

declare this

var intro;

outside of $(document).ready() because, $(document).ready() will hide your variable from global scope.

Code

var intro;

$(document).ready(function() {
    if ($('.intro_check').is(':checked')) {
        intro = true;
        $('.intro').wrap('<div class="disabled"></div>');
    };
    $('.intro_check').change(function(){
        if(this.checked) {
            intro = false;
            $('.enabled').removeClass('enabled').addClass('disabled');
        } else {
            intro = true;
            if($('.intro').exists()) {
                $('.disabled').removeClass('disabled').addClass('enabled'); 
            } else {
                $('.intro').wrap('<div class="disabled"></div>');
            }
        }
    });
});

According to @Zakaria comment

Another way:

window.intro = undefined;

$(document).ready(function() {
    if ($('.intro_check').is(':checked')) {
        window.intro = true;
        $('.intro').wrap('<div class="disabled"></div>');
    };
    $('.intro_check').change(function(){
        if(this.checked) {
            window.intro = false;
            $('.enabled').removeClass('enabled').addClass('disabled');
        } else {
            window.intro = true;
            if($('.intro').exists()) {
                $('.disabled').removeClass('disabled').addClass('enabled'); 
            } else {
                $('.intro').wrap('<div class="disabled"></div>');
            }
        }
    });
});

Note

console.log(intro);

outside of DOM ready function (currently you've) will log undefined, but within DOM ready it will give you true/ false.

Your outer console.log execute before DOM ready execute, because DOM ready execute after all resource appeared to DOM i.e after DOM is prepared, so I think you'll always get absurd result.


According to comment of @W0rldart

I need to use it outside of DOM ready function

You can use following approach:

var intro = undefined;

$(document).ready(function() {
    if ($('.intro_check').is(':checked')) {
        intro = true;
        introCheck();
        $('.intro').wrap('<div class="disabled"></div>');
    };
    $('.intro_check').change(function() {
        if (this.checked) {
            intro = true;
        } else {
            intro = false;
        }
        introCheck();
    });

});

function introCheck() {
    console.log(intro);
}

After change the value of intro I called a function that will fire with new value of intro.

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

I was using the p12 which I exported with Keychain in my MacBook, however, it didn't work on my java-apns server code. What I had to do was to create a new p12 key as stated here, using my already generated pem keys:

openssl pkcs12 -export -in your_app.pem -inkey your_key.pem -out your_app_key.p12

Then updated the path to that new p12 file and everything worked perfectly.

How to use Simple Ajax Beginform in Asp.net MVC 4?

Besides the previous post instructions, I had to install the package Microsoft.jQuery.Unobtrusive.Ajax and add to the view the following line

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

Check if any ancestor has a class using jQuery

if ($elem.parents('.left').length) {

}

How to create a readonly textbox in ASP.NET MVC3 Razor

UPDATE: Now it's very simple to add HTML attributes to the default editor templates. It neans instead of doing this:

@Html.TextBoxFor(m => m.userCode, new { @readonly="readonly" })

you simply can do this:

@Html.EditorFor(m => m.userCode, new { htmlAttributes = new { @readonly="readonly" } })

Benefits: You haven't to call .TextBoxFor, etc. for templates. Just call .EditorFor.


While @Shark's solution works correctly, and it is simple and useful, my solution (that I use always) is this one: Create an editor-template that can handles readonly attribute:

  1. Create a folder named EditorTemplates in ~/Views/Shared/
  2. Create a razor PartialView named String.cshtml
  3. Fill the String.cshtml with this code:

    @if(ViewData.ModelMetadata.IsReadOnly) {
        @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
            new { @class = "text-box single-line readonly", @readonly = "readonly", disabled = "disabled" })
    } else {
        @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
            new { @class = "text-box single-line" })
    }
    
  4. In model class, put the [ReadOnly(true)] attribute on properties which you want to be readonly.

For example,

public class Model {
    // [your-annotations-here]
    public string EditablePropertyExample { get; set; }

    // [your-annotations-here]
    [ReadOnly(true)]
    public string ReadOnlyPropertyExample { get; set; }
}

Now you can use Razor's default syntax simply:

@Html.EditorFor(m => m.EditablePropertyExample)
@Html.EditorFor(m => m.ReadOnlyPropertyExample)

The first one renders a normal text-box like this:

<input class="text-box single-line" id="field-id" name="field-name" />

And the second will render to;

<input readonly="readonly" disabled="disabled" class="text-box single-line readonly" id="field-id" name="field-name" />

You can use this solution for any type of data (DateTime, DateTimeOffset, DataType.Text, DataType.MultilineText and so on). Just create an editor-template.

HTML5 Email input pattern attribute

I used following Regex to satisfy for following emails.

[email protected] # Minimum three characters
[email protected] # Accepts Caps as well.
[email protected] # Accepts . before @

Code

<input type="email" pattern="[A-Za-z0-9._%+-]{3,}@[a-zA-Z]{3,}([.]{1}[a-zA-Z]{2,}|[.]{1}[a-zA-Z]{2,}[.]{1}[a-zA-Z]{2,})" />

How to run a command as a specific user in an init script?

On RHEL systems, the /etc/rc.d/init.d/functions script is intended to provide similar to what you want. If you source that at the top of your init script, all of it's functions become available.

The specific function provided to help with this is daemon. If you are intending to use it to start a daemon-like program, a simple usage would be:

daemon --user=username command

If that is too heavy-handed for what you need, there is runuser (see man runuser for full info; some versions may need -u prior to the username):

/sbin/runuser username -s /bin/bash -c "command(s) to run as user username"

How, in general, does Node.js handle 10,000 concurrent requests?

Single Threaded Event Loop Model Processing Steps:

  • Clients Send request to Web Server.

  • Node JS Web Server internally maintains a Limited Thread pool to provide services to the Client Requests.

  • Node JS Web Server receives those requests and places them into a Queue. It is known as “Event Queue”.

  • Node JS Web Server internally has a Component, known as “Event Loop”. Why it got this name is that it uses indefinite loop to receive requests and process them.

  • Event Loop uses Single Thread only. It is main heart of Node JS Platform Processing Model.

  • Event Loop checks any Client Request is placed in Event Queue. If not then wait for incoming requests for indefinitely.

  • If yes, then pick up one Client Request from Event Queue

    1. Starts process that Client Request
    2. If that Client Request Does Not requires any Blocking IO Operations, then process everything, prepare response and send it back to client.
    3. If that Client Request requires some Blocking IO Operations like interacting with Database, File System, External Services then it will follow different approach
  • Checks Threads availability from Internal Thread Pool
  • Picks up one Thread and assign this Client Request to that thread.
  • That Thread is responsible for taking that request, process it, perform Blocking IO operations, prepare response and send it back to the Event Loop

    very nicely explained by @Rambabu Posa for more explanation go throw this Link

Converting newline formatting from Mac to Windows

Expanding on the answers of Anne and JosephH, using perl in a short perl script, since i'm too lazy to type the perl-one-liner very time.
Create a file, named for example "unix2dos.pl" and put it in a directory in your path. Edit the file to contain the 2 lines:

#!/usr/bin/perl -wpi
s/\n|\r\n/\r\n/g;

Assuming that "which perl" returns "/usr/bin/perl" on your system. Make the file executable (chmod u+x unix2dos.pl).

Example:
$ echo "hello" > xxx
$ od -c xxx (checking that the file ends with a nl)
0000000 h e l l o \n

$ unix2dos.pl xxx
$ od -c xxx (checking that it ends now in cr lf)
0000000 h e l l o \r \n

Test class with a new() call in it with Mockito

For the future I would recommend Eran Harel's answer (refactoring moving new to factory that can be mocked). But if you don't want to change the original source code, use very handy and unique feature: spies. From the documentation:

You can create spies of real objects. When you use the spy then the real methods are called (unless a method was stubbed).

Real spies should be used carefully and occasionally, for example when dealing with legacy code.

In your case you should write:

TestedClass tc = spy(new TestedClass());
LoginContext lcMock = mock(LoginContext.class);
when(tc.login(anyString(), anyString())).thenReturn(lcMock);

Error parsing yaml file: mapping values are not allowed here

Maybe this will help someone else, but I've seen this error when the RHS of the mapping contains a colon without enclosing quotes, such as:

someKey: another key: Change to make today: work out more

should be

someKey: another key: "Change to make today: work out more"

How can I use JQuery to post JSON data?

The top answer worked fine but I suggest saving your JSON data into a variable before posting it is a little bit cleaner when sending a long form or dealing with large data in general.

_x000D_
_x000D_
var Data = {_x000D_
"name":"jonsa",_x000D_
"e-mail":"[email protected]",_x000D_
"phone":1223456789_x000D_
};_x000D_
_x000D_
_x000D_
$.ajax({_x000D_
    type: 'POST',_x000D_
    url: '/form/',_x000D_
    data: Data,_x000D_
    success: function(data) { alert('data: ' + data); },_x000D_
    contentType: "application/json",_x000D_
    dataType: 'json'_x000D_
});
_x000D_
_x000D_
_x000D_

How to use jQuery to get the current value of a file input field

Jquery works differently in IE and other browsers. You can access the last file name by using

alert($('input').attr('value'));

In IE the above alert will give the complete path but in other browsers it will give only the file name.

MySQL create stored procedure syntax with delimiter

MY SQL STORED PROCEDURE CREATION

DELIMiTER $$
create procedure GetUserRolesEnabled(in UserId int)
Begin

select * from users
where id=UserId ;
END $$
DELIMITER ;

Decode Hex String in Python 3

Something like:

>>> bytes.fromhex('4a4b4c').decode('utf-8')
'JKL'

Just put the actual encoding you are using.

How to do a LIKE query with linq?

var StudentList = dbContext.Students.SqlQuery("Select * from Students where Email like '%gmail%'").ToList<Student>();

User can use this of like query in Linq and fill the student model.

Get total size of file in bytes

You can use the length() method on File which returns the size in bytes.

How to implement a SQL like 'LIKE' operator in java?

http://josql.sourceforge.net/ has what you need. Look for org.josql.expressions.LikeExpression.

Declare and initialize a Dictionary in Typescript

Edit: This has since been fixed in the latest TS versions. Quoting @Simon_Weaver's comment on the OP's post:

Note: this has since been fixed (not sure which exact TS version). I get these errors in VS, as you would expect: Index signatures are incompatible. Type '{ firstName: string; }' is not assignable to type 'IPerson'. Property 'lastName' is missing in type '{ firstName: string; }'.


Apparently this doesn't work when passing the initial data at declaration. I guess this is a bug in TypeScript, so you should raise one at the project site.

You can make use of the typed dictionary by splitting your example up in declaration and initialization, like:

var persons: { [id: string] : IPerson; } = {};
persons["p1"] = { firstName: "F1", lastName: "L1" };
persons["p2"] = { firstName: "F2" }; // will result in an error

Disable Transaction Log

You can't do without transaction logs in SQL Server, under any circumstances. The engine simply won't function.

You CAN set your recovery model to SIMPLE on your dev machines - that will prevent transaction log bloating when tran log backups aren't done.

ALTER DATABASE MyDB SET RECOVERY SIMPLE;

Clear MySQL query cache without restarting server

according the documentation, this should do it...

RESET QUERY CACHE 

Second line in li starts under the bullet after CSS-reset

The li tag has a property called list-style-position. This makes your bullets inside or outside the list. On default, it’s set to inside. That makes your text wrap around it. If you set it to outside, the text of your li tags will be aligned.

The downside of that is that your bullets won't be aligned with the text outside the ul. If you want to align it with the other text you can use a margin.

ul li {
    /*
     * We want the bullets outside of the list,
     * so the text is aligned. Now the actual bullet
     * is outside of the list’s container
     */
    list-style-position: outside;

    /*
     * Because the bullet is outside of the list’s
     * container, indent the list entirely
     */
    margin-left: 1em;
}

Edit 15th of March, 2014 Seeing people are still coming in from Google, I felt like the original answer could use some improvement

  • Changed the code block to provide just the solution
  • Changed the indentation unit to em’s
  • Each property is applied to the ul element
  • Good comments :)

Test if a vector contains a given element

Also to find the position of the element "which" can be used as

pop <- c(3,4,5,7,13)

which(pop==13)

and to find the elements which are not contained in the target vector, one may do this:

pop <- c(1,2,4,6,10)

Tset <- c(2,10,7)   # Target set

pop[which(!(pop%in%Tset))]

Rails how to run rake task

Rake::Task['reklamer:orville'].invoke

or

Rake::Task['reklamer:orville'].invoke(args)

invalid command code ., despite escaping periods, using sed

Simply add an extension to the -i flag. This basically creates a backup file with the original file.

sed -i.bakup 's/linenumber/number/' ~/.vimrc

sed will execute without the error

Android Material and appcompat Manifest merger failed

if you are using capacitor, upgrade to capacitor/core 2.0.1 or up in your package.json

Toolbar overlapping below status bar

Use android:fitsSystemWindows="true" in the root view of your layout (LinearLayout in your case). And android:fitsSystemWindows is an

internal attribute to adjust view layout based on system windows such as the status bar. If true, adjusts the padding of this view to leave space for the system windows. Will only take effect if this view is in a non-embedded activity.

Must be a boolean value, either "true" or "false".

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

This corresponds to the global attribute resource symbol fitsSystemWindows.

Function to calculate R2 (R-squared) in R

You can also use the summary for linear models:

summary(lm(obs ~ mod, data=df))$r.squared 

How to update fields in a model without creating a new record in django?

If you get a model instance from the database, then calling the save method will always update that instance. For example:

t = TemperatureData.objects.get(id=1)
t.value = 999  # change field
t.save() # this will update only

If your goal is prevent any INSERTs, then you can override the save method, test if the primary key exists and raise an exception. See the following for more detail:

How can I align button in Center or right using IONIC framework?

And if we want to align a checkbox to the right, we can use item-end.

<ion-checkbox checked="true" item-end></ion-checkbox>

Throw away local commits in Git

For local commits which are not being pushed, you can also use git rebase -i to delete or squash a commit.

How do I Set Background image in Flutter?

We can use Container and mark its height as infinity

body: Container(
      height: double.infinity,
      width: double.infinity,
      child: FittedBox(
        fit: BoxFit.cover,
        child: Image.network(
          'https://cdn.pixabay.com/photo/2016/10/02/22/17/red-t-shirt-1710578_1280.jpg',
        ),
      ),
    ));

Output:

enter image description here

Volatile Vs Atomic

Volatile and Atomic are two different concepts. Volatile ensures, that a certain, expected (memory) state is true across different threads, while Atomics ensure that operation on variables are performed atomically.

Take the following example of two threads in Java:

Thread A:

value = 1;
done = true;

Thread B:

if (done)
  System.out.println(value);

Starting with value = 0 and done = false the rule of threading tells us, that it is undefined whether or not Thread B will print value. Furthermore value is undefined at that point as well! To explain this you need to know a bit about Java memory management (which can be complex), in short: Threads may create local copies of variables, and the JVM can reorder code to optimize it, therefore there is no guarantee that the above code is run in exactly that order. Setting done to true and then setting value to 1 could be a possible outcome of the JIT optimizations.

volatile only ensures, that at the moment of access of such a variable, the new value will be immediately visible to all other threads and the order of execution ensures, that the code is at the state you would expect it to be. So in case of the code above, defining done as volatile will ensure that whenever Thread B checks the variable, it is either false, or true, and if it is true, then value has been set to 1 as well.

As a side-effect of volatile, the value of such a variable is set thread-wide atomically (at a very minor cost of execution speed). This is however only important on 32-bit systems that i.E. use long (64-bit) variables (or similar), in most other cases setting/reading a variable is atomic anyways. But there is an important difference between an atomic access and an atomic operation. Volatile only ensures that the access is atomically, while Atomics ensure that the operation is atomically.

Take the following example:

i = i + 1;

No matter how you define i, a different Thread reading the value just when the above line is executed might get i, or i + 1, because the operation is not atomically. If the other thread sets i to a different value, in worst case i could be set back to whatever it was before by thread A, because it was just in the middle of calculating i + 1 based on the old value, and then set i again to that old value + 1. Explanation:

Assume i = 0
Thread A reads i, calculates i+1, which is 1
Thread B sets i to 1000 and returns
Thread A now sets i to the result of the operation, which is i = 1

Atomics like AtomicInteger ensure, that such operations happen atomically. So the above issue cannot happen, i would either be 1000 or 1001 once both threads are finished.

select certain columns of a data table

You can create a method that looks like this:

  public static DataTable SelectedColumns(DataTable RecordDT_, string col1, string col2)
    {
        DataTable TempTable = RecordDT_;

        System.Data.DataView view = new System.Data.DataView(TempTable);
        System.Data.DataTable selected = view.ToTable("Selected", false, col1, col2);
        return selected;
    }

You can return as many columns as possible.. just add the columns as call parameters as shown below:

public DataTable SelectedColumns(DataTable RecordDT_, string col1, string col2,string col3,...)

and also add the parameters to this line:

System.Data.DataTable selected = view.ToTable("Selected", false,col1, col2,col3,...);

Then simply implement the function as:

 DataTable myselectedColumnTable=SelectedColumns(OriginalTable,"Col1","Col2",...);

Thanks...

If list index exists, do X

A lot of answers, not the simple one.

To check if a index 'id' exists at dictionary dict:

dic = {}
dic['name'] = "joao"
dic['age']  = "39"

if 'age' in dic

returns true if 'age' exists.

Cannot lower case button text in android studio

You could add android:textAllCaps="false" to the button.

The button text might be transformed to uppercase by your app's theme that applies to all buttons. Check themes / styles files for setting the attribute android:textAllCaps.

How do I get a string format of the current date time, in python?

#python3

import datetime
print(
    '1: test-{date:%Y-%m-%d_%H:%M:%S}.txt'.format( date=datetime.datetime.now() )
    )

d = datetime.datetime.now()
print( "2a: {:%B %d, %Y}".format(d))

# see the f" to tell python this is a f string, no .format
print(f"2b: {d:%B %d, %Y}")

print(f"3: Today is {datetime.datetime.now():%Y-%m-%d} yay")

1: test-2018-02-14_16:40:52.txt

2a: March 04, 2018

2b: March 04, 2018

3: Today is 2018-11-11 yay


Description:

Using the new string format to inject value into a string at placeholder {}, value is the current time.

Then rather than just displaying the raw value as {}, use formatting to obtain the correct date format.

https://docs.python.org/3/library/string.html#formatexamples

RecyclerView: Inconsistency detected. Invalid item position

Use

notifyDataSetChanged()

instead

notifyItemRangeInserted(0, YourArrayList.size())

in this case.

How do you convert a byte array to a hexadecimal string in C?

You can solve with snprintf and malloc.

char c_buff[50];

u8_number_val[] = { 0xbb, 0xcc, 0xdd, 0x0f, 0xef, 0x0f, 0x0e, 0x0d, 0x0c };

char *s_temp = malloc(u8_size * 2 + 1);

for (uint8_t i = 0; i < u8_size; i++)
{
    snprintf(s_temp  + i * 2, 3, "%02x", u8_number_val[i]);
}

snprintf(c_buff, strlen(s_temp)+1, "%s", s_temp );

printf("%s\n",c_buff);

free(s);

OUT: bbccdd0fef0f0e0d0c

How to initialize a list of strings (List<string>) with many string values

List<string> animals= new List<string>();
animals.Add("dog");
animals.Add("tiger");

iOS app with framework crashed on device, dyld: Library not loaded, Xcode 6 Beta

I got same kind of issue in iOS 9.x version

ISSUE IS: App crashes as soon as I open the app with below error.

dyld: Library not loaded: /System/Library/Frameworks/UserNotifications.framework/UserNotifications Referenced from: /var/containers/Bundle/Application/######/TestApp.app/TestApp Reason: image not found

I have resolved this issue by changing Required to Optional in Linked Frameworks and Libraries for UserNotifications.framework framework.

Scroll event listener javascript

For those who found this question hoping to find an answer that doesn't involve jQuery, you hook into the window "scroll" event using normal event listening. Say we want to add scroll listening to a number of CSS-selector-able elements:

// what should we do when scrolling occurs
var runOnScroll =  function(evt) {
  // not the most exciting thing, but a thing nonetheless
  console.log(evt.target);
};

// grab elements as array, rather than as NodeList
var elements = document.querySelectorAll("...");
elements = Array.prototype.slice.call(elements);

// and then make each element do something on scroll
elements.forEach(function(element) {
  window.addEventListener("scroll", runOnScroll, {passive: true});
});

(Using the passive attribute to tell the browser that this event won't interfere with scrolling itself)

For bonus points, you can give the scroll handler a lock mechanism so that it doesn't run if we're already scrolling:

// global lock, so put this code in a closure of some sort so you're not polluting.
var locked = false;
var lastCall = false;

var runOnScroll =  function(evt) {
  if(locked) return;

  if (lastCall) clearTimeout(lastCall);
  lastCall = setTimeout(() => {
    runOnScroll(evt);
    // you do this because you want to handle the last
    // scroll event, even if it occurred while another
    // event was being processed.
  }, 200);

  // ...your code goes here...

  locked = false;
};

Where are logs located?

You should be checking the root directory and not the app directory.

Look in $ROOT/storage/laravel.log not app/storage/laravel.log, where root is the top directory of the project.

Gridview row editing - dynamic binding to a DropDownList

I am using a ListView instead of a GridView in 3.5. When the user wants to edit I have set the selected item of the dropdown to the exising value of that column for the record. I am able to access the dropdown in the ItemDataBound event. Here's the code:

protected void listViewABC_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    // This stmt is used to execute the code only in case of edit 
    if (((ListView)(sender)).EditIndex != -1 && ((ListViewDataItem)(e.Item)).DisplayIndex == ((ListView)(sender)).EditIndex)
    {
        ((DropDownList)(e.Item.FindControl("ddlXType"))).SelectedValue = ((MyClass)((ListViewDataItem)e.Item).DataItem).XTypeId.ToString();
        ((DropDownList)(e.Item.FindControl("ddlIType"))).SelectedValue = ((MyClass)((ListViewDataItem)e.Item).DataItem).ITypeId.ToString();
    }
}

How to add data into ManyToMany field?

There's a whole page of the Django documentation devoted to this, well indexed from the contents page.

As that page states, you need to do:

my_obj.categories.add(fragmentCategory.objects.get(id=1))

or

my_obj.categories.create(name='val1')

Python time measure function

Decorator method using decorator Python library:

import decorator

@decorator
def timing(func, *args, **kwargs):
    '''Function timing wrapper
        Example of using:
        ``@timing()``
    '''

    fn = '%s.%s' % (func.__module__, func.__name__)

    timer = Timer()
    with timer:
        ret = func(*args, **kwargs)

    log.info(u'%s - %0.3f sec' % (fn, timer.duration_in_seconds()))
    return ret

See post on my Blog:

post on mobilepro.pl Blog

my post on Google Plus

How to find whether MySQL is installed in Red Hat?

Usually you can find a program under a subdirectory "../bin". System programs are under /usr/bin or /bin. To check where files of mysql package are placed, on RHEL 6 type like this :

rpm -ql mysql (which is the main part of the package)

and the result is a list of "exe" files such as "mysqladmin" tool. About to know the version of the server, run the command:

mysqladmin -u "valid-user" version

Could not find folder 'tools' inside SDK

By default it looks for the SDK tools in "C:\Documents and Settings\user\android-sdks". Some times we install it at another location. So you just have to select the correct path and it will done.

Can't type in React input text field

I also have same problem and in my case I injected reducer properly but still I couldn't type in field. It turns out if you are using immutable you have to use redux-form/immutable.

import {reducer as formReducer} from 'redux-form/immutable';
const reducer = combineReducers{

    form: formReducer
}
import {Field, reduxForm} from 'redux-form/immutable';
/* your component */

Notice that your state should be like state->form otherwise you have to explicitly config the library also the name for state should be form. see this issue

OWIN Security - How to Implement OAuth2 Refresh Tokens

I don't think that you should be using an array to maintain tokens. Neither you need a guid as a token.

You can easily use context.SerializeTicket().

See my below code.

public class RefreshTokenProvider : IAuthenticationTokenProvider
{
    public async Task CreateAsync(AuthenticationTokenCreateContext context)
    {
        Create(context);
    }

    public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
    {
        Receive(context);
    }

    public void Create(AuthenticationTokenCreateContext context)
    {
        object inputs;
        context.OwinContext.Environment.TryGetValue("Microsoft.Owin.Form#collection", out inputs);

        var grantType = ((FormCollection)inputs)?.GetValues("grant_type");

        var grant = grantType.FirstOrDefault();

        if (grant == null || grant.Equals("refresh_token")) return;

        context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(Constants.RefreshTokenExpiryInDays);

        context.SetToken(context.SerializeTicket());
    }

    public void Receive(AuthenticationTokenReceiveContext context)
    {
        context.DeserializeTicket(context.Token);

        if (context.Ticket == null)
        {
            context.Response.StatusCode = 400;
            context.Response.ContentType = "application/json";
            context.Response.ReasonPhrase = "invalid token";
            return;
        }

        if (context.Ticket.Properties.ExpiresUtc <= DateTime.UtcNow)
        {
            context.Response.StatusCode = 401;
            context.Response.ContentType = "application/json";
            context.Response.ReasonPhrase = "unauthorized";
            return;
        }

        context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(Constants.RefreshTokenExpiryInDays);
        context.SetTicket(context.Ticket);
    }
}

HTML5 Canvas 100% Width Height of Viewport?

http://jsfiddle.net/mqFdk/10/

<!DOCTYPE html>
<html>
<head>
    <title>aj</title>
</head>
<body>

    <canvas id="c"></canvas>

</body>
</html>

with CSS

body { 
       margin: 0; 
       padding: 0
     }
#c { 
     position: absolute; 
     width: 100%; 
     height: 100%; 
     overflow: hidden
   }

How do I look inside a Python object?

There is a python code library build just for this purpose: inspect Introduced in Python 2.7

How to use hex() without 0x in Python?

You can simply write

hex(x)[2:]

to get the first two characters removed.

Date Conversion from String to sql Date in Java giving different output?

mm stands for "minutes". Use MM instead:

SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy");

How to merge two files line by line in Bash

Check

man paste

possible followed by some command like untabify or tabs2spaces

Deleting multiple columns based on column names in Pandas

df = df[[col for col in df.columns if not ('Unnamed' in col)]]

Center a H1 tag inside a DIV

On the hX tag

width: 100px;
margin-left: auto;
margin-right: auto;

Display only 10 characters of a long string?

Although this won't limit the string to exactly 10 characters, why not let the browser do the work for you with CSS:

.no-overflow {
    white-space: no-wrap;
    text-overflow: ellipsis;
    overflow: hidden;
}

and then for the table cell that contains the string add the above class and set the maximum permitted width. The result should end up looking better than anything done based on measuring the string length.

Deploying just HTML, CSS webpage to Tomcat

If you want to create a .war file you can deploy to a Tomcat instance using the Manager app, create a folder, put all your files in that folder (including an index.html file) move your terminal window into that folder, and execute the following command:

zip -r <AppName>.war *

I've tested it with Tomcat 8 on the Mac, but it should work anywhere

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(R.id.imageview);     imageView.setImageBitmap(bitmap);  } 

Use Toast inside Fragment

If you are using kotlin then the context will be already defined in the fragment. So just use that context. Try the following code to show a toast message.

Toast.makeText(context , "your_text", Toast.LENGTH_SHORT).show()

What is CDATA in HTML?

CDATA has no meaning at all in HTML.

CDATA is an XML construct which sets a tag's contents that is normally #PCDATA - parsed character data, to be instead taken as #CDATA, that is, non-parsed character data. It is only relevant and valid in XHTML.

It is used in script tags to avoid parsing < and &. In HTML, this is not needed, because in HTML, script is already #CDATA.

How to save traceback / sys.exc_info() values in a variable?

Use traceback.extract_stack() if you want convenient access to module and function names and line numbers.

Use ''.join(traceback.format_stack()) if you just want a string that looks like the traceback.print_stack() output.

Notice that even with ''.join() you will get a multi-line string, since the elements of format_stack() contain \n. See output below.

Remember to import traceback.

Here's the output from traceback.extract_stack(). Formatting added for readability.

>>> traceback.extract_stack()
[
   ('<string>', 1, '<module>', None),
   ('C:\\Python\\lib\\idlelib\\run.py', 126, 'main', 'ret = method(*args, **kwargs)'),
   ('C:\\Python\\lib\\idlelib\\run.py', 353, 'runcode', 'exec(code, self.locals)'),
   ('<pyshell#1>', 1, '<module>', None)
]

Here's the output from ''.join(traceback.format_stack()). Formatting added for readability.

>>> ''.join(traceback.format_stack())
'  File "<string>", line 1, in <module>\n
   File "C:\\Python\\lib\\idlelib\\run.py", line 126, in main\n
       ret = method(*args, **kwargs)\n
   File "C:\\Python\\lib\\idlelib\\run.py", line 353, in runcode\n
       exec(code, self.locals)\n  File "<pyshell#2>", line 1, in <module>\n'

Make outer div be automatically the same height as its floating content

Use jQuery:

Set Parent Height = Child offsetHeight.

$(document).ready(function() {
    $(parent).css("height", $(child).attr("offsetHeight"));
}

How do you check what version of SQL Server for a database using TSQL?

Try this:

SELECT
    'the sqlserver is ' + substring(@@VERSION, 21, 5) AS [sql version]

AngularJS: How to set a variable inside of a template?

It's not the best answer, but its also an option: since you can concatenate multiple expressions, but just the last one is rendered, you can finish your expression with "" and your variable will be hidden.

So, you could define the variable with:

{{f = forecast[day.iso]; ""}}

UTL_FILE.FOPEN() procedure not accepting path for directory?

The directory name seems to be case sensitive. I faced the same issue but when I provided the directory name in upper case it worked.

How do I perform a Perl substitution on a string while keeping the original?

I hate foo and bar .. who dreamed up these non descriptive terms in programming anyway?

my $oldstring = "replace donotreplace replace donotreplace replace donotreplace";

my $newstring = $oldstring;
$newstring =~ s/replace/newword/g; # inplace replacement

print $newstring;
%: newword donotreplace newword donotreplace newword donotreplace

How to remove an unpushed outgoing commit in Visual Studio?

Try to rebase your local master branch onto your remote/origin master branch and resolve any conflicts in the process.

How to tell if tensorflow is using gpu acceleration from inside python shell?

Apart from using sess = tf.Session(config=tf.ConfigProto(log_device_placement=True)) which is outlined in other answers as well as in the official TensorFlow documentation, you can try to assign a computation to the gpu and see whether you have an error.

import tensorflow as tf
with tf.device('/gpu:0'):
    a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
    b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
    c = tf.matmul(a, b)

with tf.Session() as sess:
    print (sess.run(c))

Here

  • "/cpu:0": The CPU of your machine.
  • "/gpu:0": The GPU of your machine, if you have one.

If you have a gpu and can use it, you will see the result. Otherwise you will see an error with a long stacktrace. In the end you will have something like this:

Cannot assign a device to node 'MatMul': Could not satisfy explicit device specification '/device:GPU:0' because no devices matching that specification are registered in this process


Recently a few helpful functions appeared in TF:

You can also check for available devices in the session:

with tf.Session() as sess:
  devices = sess.list_devices()

devices will return you something like

[_DeviceAttributes(/job:tpu_worker/replica:0/task:0/device:CPU:0, CPU, -1, 4670268618893924978),
 _DeviceAttributes(/job:tpu_worker/replica:0/task:0/device:XLA_CPU:0, XLA_CPU, 17179869184, 6127825144471676437),
 _DeviceAttributes(/job:tpu_worker/replica:0/task:0/device:XLA_GPU:0, XLA_GPU, 17179869184, 16148453971365832732),
 _DeviceAttributes(/job:tpu_worker/replica:0/task:0/device:TPU:0, TPU, 17179869184, 10003582050679337480),
 _DeviceAttributes(/job:tpu_worker/replica:0/task:0/device:TPU:1, TPU, 17179869184, 5678397037036584928)

Mockito: Inject real objects into private @Autowired fields

Use @Spy annotation

@RunWith(MockitoJUnitRunner.class)
public class DemoTest {
    @Spy
    private SomeService service = new RealServiceImpl();

    @InjectMocks
    private Demo demo;

    /* ... */
}

Mockito will consider all fields having @Mock or @Spy annotation as potential candidates to be injected into the instance annotated with @InjectMocks annotation. In the above case 'RealServiceImpl' instance will get injected into the 'demo'

For more details refer

Mockito-home

@Spy

@Mock

Server cannot set status after HTTP headers have been sent IIS7.5

I remember the part from this exception : "Cannot modify header information - headers already sent by" occurring in PHP. It occurred when the headers were already sent in the redirection phase and any other output was generated e.g.:

echo "hello"; header("Location:http://stackoverflow.com");

Pardon me and do correct me if I am wrong but I am still learning MS Technologies and I was trying to help.

How to install CocoaPods?

Year 2020, Installing Cocoapods v1.9.1 in Mac OS Catalina

  1. First setup your Xcode version in your mac using terminal.

$ sudo xcode-select -switch /Applications/Xcode.app

  1. Next, Install cocoapods using terminal.

$ sudo gem install cocoapods

For More information, visit official website https://cocoapods.org/

How can I send JSON response in symfony2 controller

To complete @thecatontheflat answer I would recommend to also wrap your action inside of a try … catch block. This will prevent your JSON endpoint from breaking on exceptions. Here's the skeleton I use:

public function someAction()
{
    try {

        // Your logic here...

        return new JsonResponse([
            'success' => true,
            'data'    => [] // Your data here
        ]);

    } catch (\Exception $exception) {

        return new JsonResponse([
            'success' => false,
            'code'    => $exception->getCode(),
            'message' => $exception->getMessage(),
        ]);

    }
}

This way your endpoint will behave consistently even in case of errors and you will be able to treat them right on a client side.

What is this CSS selector? [class*="span"]

It selects all elements where the class name contains the string "span" somewhere. There's also ^= for the beginning of a string, and $= for the end of a string. Here's a good reference for some CSS selectors.

I'm only familiar with the bootstrap classes spanX where X is an integer, but if there were other selectors that ended in span, it would also fall under these rules.

It just helps to apply blanket CSS rules.

Value of type 'T' cannot be converted to

I know similar code that the OP posted in this question from generic parsers. From a performance perspective, you should use Unsafe.As<TFrom, TResult>(ref TFrom source), which can be found in the System.Runtime.CompilerServices.Unsafe NuGet package. It avoids boxing for value types in these scenarios. I also think that Unsafe.As results in less machine code produced by the JIT than casting twice (using (TResult) (object) actualString), but I haven't checked that out.

public TResult ParseSomething<TResult>(ParseContext context)
{
    if (typeof(TResult) == typeof(string))
    {
        var token = context.ParseNextToken();
        string parsedString = token.ParseToDotnetString();
        return Unsafe.As<string, TResult>(ref parsedString);
    }
    else if (typeof(TResult) == typeof(int))
    {
        var token = context.ParseNextToken();
        int parsedInt32 = token.ParseToDotnetInt32();
        // This will not box which might be critical to performance
        return Unsafe.As<int, TResult>(ref parsedInt32); 
    }
    // other cases omitted for brevity's sake
}

Unsafe.As will be replaced by the JIT with efficient machine code instructions, as you can see in the official CoreFX repo:

Source Code of Unsafe.As

Convert json to a C# array?

just take the string and use the JavaScriptSerializer to deserialize it into a native object. For example, having this json:

string json = "[{Name:'John Simith',Age:35},{Name:'Pablo Perez',Age:34}]"; 

You'd need to create a C# class called, for example, Person defined as so:

public class Person
{
 public int Age {get;set;}
 public string Name {get;set;}
}

You can now deserialize the JSON string into an array of Person by doing:

JavaScriptSerializer js = new JavaScriptSerializer();
Person [] persons =  js.Deserialize<Person[]>(json);

Here's a link to JavaScriptSerializer documentation.

Note: my code above was not tested but that's the idea Tested it. Unless you are doing something "exotic", you should be fine using the JavascriptSerializer.

Can you remove elements from a std::list while iterating through it?

If you think of the std::list like a queue, then you can dequeue and enqueue all the items that you want to keep, but only dequeue (and not enqueue) the item you want to remove. Here's an example where I want to remove 5 from a list containing the numbers 1-10...

std::list<int> myList;

int size = myList.size(); // The size needs to be saved to iterate through the whole thing

for (int i = 0; i < size; ++i)
{
    int val = myList.back()
    myList.pop_back() // dequeue
    if (val != 5)
    {
         myList.push_front(val) // enqueue if not 5
    }
}

myList will now only have numbers 1-4 and 6-10.

What is a vertical tab?

A vertical tab was the opposite of a line feed i.e. it went upwards by one line. It had nothing to do with tab positions. If you want to prove this, try it on an RS232 terminal.

Docker container not starting (docker start)

What I need is to use Docker with MariaDb on different port /3301/ on my Ubuntu machine because I already had MySql installed and running on 3306.

To do this after half day searching did it using:

docker run -it -d -p 3301:3306 -v ~/mdbdata/mariaDb:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root --name mariaDb mariadb

This pulls the image with latest MariaDb, creates container called mariaDb, and run mysql on port 3301. All data of which is located in home directory in /mdbdata/mariaDb.

To login in mysql after that can use:

mysql -u root -proot -h 127.0.0.1 -P3301

Used sources are:

The answer of Iarks in this article /using -it -d was the key :) /

how-to-install-and-use-docker-on-ubuntu-16-04

installing-and-using-mariadb-via-docker

mariadb-and-docker-use-cases-part-1

Good luck all!

Where is HttpContent.ReadAsAsync?

It looks like it is an extension method (in System.Net.Http.Formatting):

HttpContentExtensions Class

Update:

PM> install-package Microsoft.AspNet.WebApi.Client

According to the System.Net.Http.Formatting NuGet package page, the System.Net.Http.Formatting package is now legacy and can instead be found in the Microsoft.AspNet.WebApi.Client package available on NuGet here.

URL to compose a message in Gmail (with full Gmail interface and specified to, bcc, subject, etc.)

The GMail web client supports mailto: links

For regular @gmail.com accounts: https://mail.google.com/mail/?extsrc=mailto&url=...

For G Suite accounts on domain gsuitedomain.com: https://mail.google.com/a/gsuitedomain.com/mail/?extsrc=mailto&url=...

... needs to be replaced with a urlencoded mailto: link.

Demo: https://mail.google.com/mail/?extsrc=mailto&url=mailto%3A%3Fto%3Dsomeguy%40gmail.com%26bcc%3Dmyattorney%40gmail.com%2Cbuzzfeed%40gmail.com%26subject%3DHi%2520There%26body%3Dbody%2520goes%2520here

Learn more about mailto: links by reading RFC6068

How to parse a CSV file using PHP

I been seeking the same thing without using some unsupported PHP class. Excel CSV dosn't always use the quote separators and escapes the quotes using "" because the algorithm was probably made back the 80's or something. After looking at several .csv parsers in the comments section on PHP.NET, I seen ones that even used callbacks or eval'd code and they either didnt work like needed or simply didnt work at all. So, I wrote my own routines for this and they work in the most basic PHP configuration. The array keys can either be numeric or named as the fields given in the header row. Hope this helps.

    function SW_ImplodeCSV(array $rows, $headerrow=true, $mode='EXCEL', $fmt='2D_FIELDNAME_ARRAY')
    // SW_ImplodeCSV - returns 2D array as string of csv(MS Excel .CSV supported)
    // AUTHOR: [email protected]
    // RELEASED: 9/21/13 BETA
      { $r=1; $row=array(); $fields=array(); $csv="";
        $escapes=array('\r', '\n', '\t', '\\', '\"');  //two byte escape codes
        $escapes2=array("\r", "\n", "\t", "\\", "\""); //actual code

        if($mode=='EXCEL')// escape code = ""
         { $delim=','; $enclos='"'; $rowbr="\r\n"; }
        else //mode=STANDARD all fields enclosed
           { $delim=','; $enclos='"'; $rowbr="\r\n"; }

          $csv=""; $i=-1; $i2=0; $imax=count($rows);

          while( $i < $imax )
          {
            // get field names
            if($i == -1)
             { $row=$rows[0];
               if($fmt=='2D_FIELDNAME_ARRAY')
                { $i2=0; $i2max=count($row);
                  while( list($k, $v) = each($row) )
                   { $fields[$i2]=$k;
                     $i2++;
                   }
                }
               else //if($fmt='2D_NUMBERED_ARRAY')
                { $i2=0; $i2max=(count($rows[0]));
                  while($i2<$i2max)
                   { $fields[$i2]=$i2;
                     $i2++;
                   }
                }

               if($headerrow==true) { $row=$fields; }
               else                 { $i=0; $row=$rows[0];}
             }
            else
             { $row=$rows[$i];
             }

            $i2=0;  $i2max=count($row); 
            while($i2 < $i2max)// numeric loop (order really matters here)
            //while( list($k, $v) = each($row) )
             { if($i2 != 0) $csv=$csv.$delim;

               $v=$row[$fields[$i2]];

               if($mode=='EXCEL') //EXCEL 2quote escapes
                    { $newv = '"'.(str_replace('"', '""', $v)).'"'; }
               else  //STANDARD
                    { $newv = '"'.(str_replace($escapes2, $escapes, $v)).'"'; }
               $csv=$csv.$newv;
               $i2++;
             }

            $csv=$csv."\r\n";

            $i++;
          }

         return $csv;
       }

    function SW_ExplodeCSV($csv, $headerrow=true, $mode='EXCEL', $fmt='2D_FIELDNAME_ARRAY')
     { // SW_ExplodeCSV - parses CSV into 2D array(MS Excel .CSV supported)
       // AUTHOR: [email protected]
       // RELEASED: 9/21/13 BETA
       //SWMessage("SW_ExplodeCSV() - CALLED HERE -");
       $rows=array(); $row=array(); $fields=array();// rows = array of arrays

       //escape code = '\'
       $escapes=array('\r', '\n', '\t', '\\', '\"');  //two byte escape codes
       $escapes2=array("\r", "\n", "\t", "\\", "\""); //actual code

       if($mode=='EXCEL')
        {// escape code = ""
          $delim=','; $enclos='"'; $esc_enclos='""'; $rowbr="\r\n";
        }
       else //mode=STANDARD 
        {// all fields enclosed
          $delim=','; $enclos='"'; $rowbr="\r\n";
        }

       $indxf=0; $indxl=0; $encindxf=0; $encindxl=0; $enc=0; $enc1=0; $enc2=0; $brk1=0; $rowindxf=0; $rowindxl=0; $encflg=0;
       $rowcnt=0; $colcnt=0; $rowflg=0; $colflg=0; $cell="";
       $headerflg=0; $quotedflg=0;
       $i=0; $i2=0; $imax=strlen($csv);   

       while($indxf < $imax)
         {
           //find first *possible* cell delimiters
           $indxl=strpos($csv, $delim, $indxf);  if($indxl===false) { $indxl=$imax; }
           $encindxf=strpos($csv, $enclos, $indxf); if($encindxf===false) { $encindxf=$imax; }//first open quote
           $rowindxl=strpos($csv, $rowbr, $indxf); if($rowindxl===false) { $rowindxl=$imax; }

           if(($encindxf>$indxl)||($encindxf>$rowindxl))
            { $quoteflg=0; $encindxf=$imax; $encindxl=$imax;
              if($rowindxl<$indxl) { $indxl=$rowindxl; $rowflg=1; }
            }
           else 
            { //find cell enclosure area (and real cell delimiter)
              $quoteflg=1;
              $enc=$encindxf; 
              while($enc<$indxl) //$enc = next open quote
               {// loop till unquoted delim. is found
                 $enc=strpos($csv, $enclos, $enc+1); if($enc===false) { $enc=$imax; }//close quote
                 $encindxl=$enc; //last close quote
                 $indxl=strpos($csv, $delim, $enc+1); if($indxl===false)  { $indxl=$imax; }//last delim.
                 $enc=strpos($csv, $enclos, $enc+1); if($enc===false) { $enc=$imax; }//open quote
                 if(($indxl==$imax)||($enc==$imax)) break;
               }
              $rowindxl=strpos($csv, $rowbr, $enc+1); if($rowindxl===false) { $rowindxl=$imax; }
              if($rowindxl<$indxl) { $indxl=$rowindxl; $rowflg=1; }
            }

           if($quoteflg==0)
            { //no enclosured content - take as is
              $colflg=1;
              //get cell 
             // $cell=substr($csv, $indxf, ($indxl-$indxf)-1);
              $cell=substr($csv, $indxf, ($indxl-$indxf));
            }
           else// if($rowindxl > $encindxf)
            { // cell enclosed
              $colflg=1;

             //get cell - decode cell content
              $cell=substr($csv, $encindxf+1, ($encindxl-$encindxf)-1);

              if($mode=='EXCEL') //remove EXCEL 2quote escapes
                { $cell=str_replace($esc_enclos, $enclos, $cell);
                }
              else //remove STANDARD esc. sceme
                { $cell=str_replace($escapes, $escapes2, $cell);
                }
            }

           if($colflg)
            {// read cell into array
              if( ($fmt=='2D_FIELDNAME_ARRAY') && ($headerflg==1) )
               { $row[$fields[$colcnt]]=$cell; }
              else if(($fmt=='2D_NUMBERED_ARRAY')||($headerflg==0))
               { $row[$colcnt]=$cell; } //$rows[$rowcnt][$colcnt] = $cell;

              $colcnt++; $colflg=0; $cell="";
              $indxf=$indxl+1;//strlen($delim);
            }
           if($rowflg)
            {// read row into big array
              if(($headerrow) && ($headerflg==0))
                {  $fields=$row;
                   $row=array();
                   $headerflg=1;
                }
              else
                { $rows[$rowcnt]=$row;
                  $row=array();
                  $rowcnt++; 
                }
               $colcnt=0; $rowflg=0; $cell="";
               $rowindxf=$rowindxl+2;//strlen($rowbr);
               $indxf=$rowindxf;
            }

           $i++;
           //SWMessage("SW_ExplodeCSV() - colcnt = ".$colcnt."   rowcnt = ".$rowcnt."   indxf = ".$indxf."   indxl = ".$indxl."   rowindxf = ".$rowindxf);
           //if($i>20) break;
         }

       return $rows;
     }

...bob can now go back to his speadsheets

What is the difference between "px", "dip", "dp" and "sp"?

I want to provide an easy way to understand dp. In fact, I think dp is the easiest one to understand. dp is just a physical length unit. It's of the same dimension as mm or inch. It's just convenient for us to write 50dp, 60dp rather than 50/160 inch or 60/160 inch, because one dp is just 1/160 inch whatever the screen size or resolution is.

The only problem is that, the android dpi of some screens are not accurate. For example, a screen classified to 160dpi may have 170dpi indeed. So the computation result of dp is fuzzy. It should be approximately the same as 1/160 inch.

Generating unique random numbers (integers) between 0 and 'x'

Just as another possible solution based on ES6 Set ("arr. that can contain unique values only").

Examples of usage:

// Get 4 unique rnd. numbers: from 0 until 4 (inclusive):
getUniqueNumbersInRange(4, 0, 5) //-> [5, 0, 4, 1];

// Get 2 unique rnd. numbers: from -1 until 2 (inclusive):
getUniqueNumbersInRange(2, -1, 2) //-> [1, -1];

// Get 0 unique rnd. numbers (empty result): from -1 until 2 (inclusive):
getUniqueNumbersInRange(0, -1, 2) //-> [];

// Get 7 unique rnd. numbers: from 1 until 7 (inclusive):
getUniqueNumbersInRange(7, 1, 7) //-> [ 3, 1, 6, 2, 7, 5, 4];

The implementation:

function getUniqueNumbersInRange(uniqueNumbersCount, fromInclusive, untilInclusive) {

    // 0/3. Check inputs.
    if (0 > uniqueNumbersCount) throw new Error('The number of unique numbers cannot be negative.');
    if (fromInclusive > untilInclusive) throw new Error('"From" bound "' + fromInclusive
        + '" cannot be greater than "until" bound "' + untilInclusive + '".');
    const rangeLength = untilInclusive - fromInclusive + 1;
    if (uniqueNumbersCount > rangeLength) throw new Error('The length of the range is ' + rangeLength + '=['
        + fromInclusive + '…' + untilInclusive + '] that is smaller than '
        + uniqueNumbersCount + ' (specified count of result numbers).');
    if (uniqueNumbersCount === 0) return [];


    // 1/3. Create a new "Set" – object that stores unique values of any type, whether primitive values or object references.
    // MDN - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
    // Support: Google Chrome 38+(2014.10), Firefox 13+, IE 11+
    const uniqueDigits = new Set();


    // 2/3. Fill with random numbers.        
    while (uniqueNumbersCount > uniqueDigits.size) {
        // Generate and add an random integer in specified range.
        const nextRngNmb = Math.floor(Math.random() * rangeLength) + fromInclusive;
        uniqueDigits.add(nextRngNmb);
    }


    // 3/3. Convert "Set" with unique numbers into an array with "Array.from()".
    // MDN – https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from
    // Support: Google Chrome 45+ (2015.09+), Firefox 32+, not IE
    const resArray = Array.from(uniqueDigits);
    return resArray;

}

The benefits of the current implementation:

  1. Have a basic check of input arguments – you will not get an unexpected output when the range is too small, etc.
  2. Support the negative range (not only from 0), e. g. randoms from -1000 to 500, etc.
  3. Expected behavior: the current most popular answer will extend the range (upper bound) on its own if input bounds are too small. An example: get 10000 unique numbers with a specified range from 0 until 10 need to throw an error due to too small range (10-0+1=11 possible unique numbers only). But the current top answer will hiddenly extend the range until 10000.

How to enable CORS in ASP.net Core WebAPI

In launchSettings.json, under iisSettings, set anonymousAuthentication to true:

"iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:4200/",
      "sslPort": 0
    }
  }

Then, in Startup.cs, under ConfigureServices, before services.AddMvc, add:

services.AddCors(options => options.AddPolicy("ApiCorsPolicy", builder =>
{
    builder
        .AllowAnyOrigin()
        .WithHeaders(HeaderNames.AccessControlAllowHeaders, "Content-Type")
        .AllowAnyMethod()
        .AllowCredentials();
}));

and then, in configure method, before app.UseMvc() add:

app.UseCors("ApiCorsPolicy");

In Bash, how to add "Are you sure [Y/n]" to any command or alias?

Confirmations are easily bypassed with carriage returns, and I find it useful to continually prompt for valid input.

Here's a function to make this easy. "invalid input" appears in red if Y|N is not received, and the user is prompted again.

prompt_confirm() {
  while true; do
    read -r -n 1 -p "${1:-Continue?} [y/n]: " REPLY
    case $REPLY in
      [yY]) echo ; return 0 ;;
      [nN]) echo ; return 1 ;;
      *) printf " \033[31m %s \n\033[0m" "invalid input"
    esac 
  done  
}

# example usage
prompt_confirm "Overwrite File?" || exit 0

You can change the default prompt by passing an argument

How do I retrieve my MySQL username and password?

IF you happen to have ODBC set up, you can get the password from the ODBC config file. This is in /etc/odbc.ini for Linux and in the Software/ODBC folder in the registry in Windows (there are several - it may take some hunting)

How to properly exit a C# application?

From MSDN:

Application.Exit

Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This is the code to use if you are have called Application.Run (WinForms applications), this method stops all running message loops on all threads and closes all windows of the application.

Environment.Exit

Terminates this process and gives the underlying operating system the specified exit code. This is the code to call when you are using console application.

This article, Application.Exit vs. Environment.Exit, points towards a good tip:

You can determine if System.Windows.Forms.Application.Run has been called by checking the System.Windows.Forms.Application.MessageLoop property. If true, then Run has been called and you can assume that a WinForms application is executing as follows.

if (System.Windows.Forms.Application.MessageLoop) 
{
    // WinForms app
    System.Windows.Forms.Application.Exit();
}
else
{
    // Console app
    System.Environment.Exit(1);
}

Reference: Why would Application.Exit fail to work?

Node.js Error: connect ECONNREFUSED

Sometimes it may occur, if there is any database connection in your code but you did not start the database server yet.

Im my case i have some piece of code to connect with mongodb

mongoose.connect("mongodb://localhost:27017/demoDb");

after i started the mongodb server with the command mongod this error is gone

How to set a string's color

setColor(). Assuming you use Graphics g in an AWT context.

Please refer to the documentation for additional information.

Change Image of ImageView programmatically in Android

You can use

val drawableCompat = ContextCompat.getDrawable(context, R.drawable.ic_emoticon_happy)

or in java java

Drawable drawableCompat = ContextCompat.getDrawable(getContext(), R.drawable.ic_emoticon_happy)

How to use refs in React with Typescript

If you wont to forward your ref, in Props interface you need to use RefObject<CmpType> type from import React, { RefObject } from 'react';

Neither BindingResult nor plain target object for bean name available as request attr

I have encountered this problem as well. Here is my solution:

Below is the error while running a small Spring Application:-

*HTTP Status 500 - 
--------------------------------------------------------------------------------
type Exception report
message 
description The server encountered an internal error () that prevented it from fulfilling this request.
exception 
org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/jsp/employe.jsp at line 12
9: <form:form method="POST" commandName="command"  action="/SpringWeb/addEmploye">
10:    <table>
11:     <tr>
12:         <td><form:label path="name">Name</form:label></td>
13:         <td><form:input path="name" /></td>
14:     </tr>
15:     <tr>
Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:465)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause 
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute
    org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:174)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:194)
    org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:129)
    org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:119)
    org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:89)
    org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:102)
    org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:79)
    org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspx_meth_form_005flabel_005f0(employe_jsp.java:185)
    org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspx_meth_form_005fform_005f0(employe_jsp.java:120)
    org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspService(employe_jsp.java:80)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.26 logs.*

In order to resolve this issue you need to do the following in the controller class:-

  1. Change the import package from "import org.springframework.web.portlet.ModelAndView;" to "import org.springframework.web.servlet.ModelAndView;"...
  2. Recompile and run the code... the problem should get resolved.

Convert generic List/Enumerable to DataTable?

try this

public static DataTable ListToDataTable<T>(IList<T> lst)
{

    currentDT = CreateTable<T>();

    Type entType = typeof(T);

    PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
    foreach (T item in lst)
    {
        DataRow row = currentDT.NewRow();
        foreach (PropertyDescriptor prop in properties)
        {

            if (prop.PropertyType == typeof(Nullable<decimal>) || prop.PropertyType == typeof(Nullable<int>) || prop.PropertyType == typeof(Nullable<Int64>))
            {
                if (prop.GetValue(item) == null)
                    row[prop.Name] = 0;
                else
                    row[prop.Name] = prop.GetValue(item);
            }
            else
                row[prop.Name] = prop.GetValue(item);                    

        }
        currentDT.Rows.Add(row);
    }

    return currentDT;
}

public static DataTable CreateTable<T>()
{
    Type entType = typeof(T);
    DataTable tbl = new DataTable(DTName);
    PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
    foreach (PropertyDescriptor prop in properties)
    {
        if (prop.PropertyType == typeof(Nullable<decimal>))
             tbl.Columns.Add(prop.Name, typeof(decimal));
        else if (prop.PropertyType == typeof(Nullable<int>))
            tbl.Columns.Add(prop.Name, typeof(int));
        else if (prop.PropertyType == typeof(Nullable<Int64>))
            tbl.Columns.Add(prop.Name, typeof(Int64));
        else
             tbl.Columns.Add(prop.Name, prop.PropertyType);
    }
    return tbl;
}

Post to another page within a PHP script

index.php

$url = 'http://[host]/test.php';
$json = json_encode(['name' => 'Jhonn', 'phone' => '128000000000']);

$options = ['http' => [
    'method' => 'POST',
    'header' => 'Content-type:application/json',
    'content' => $json
]];

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

test.php

$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
echo $data['name']; // Jhonn

In Java, how do I get the difference in seconds between 2 dates?

You should do

org.joda.time.Seconds.secondBetween(date1, date2)

The Definitive C Book Guide and List

Beginner

Introductory, no previous programming experience

  • C++ Primer * (Stanley Lippman, Josée Lajoie, and Barbara E. Moo) (updated for C++11) Coming at 1k pages, this is a very thorough introduction into C++ that covers just about everything in the language in a very accessible format and in great detail. The fifth edition (released August 16, 2012) covers C++11. [Review]

    * Not to be confused with C++ Primer Plus (Stephen Prata), with a significantly less favorable review.

  • Programming: Principles and Practice Using C++ (Bjarne Stroustrup, 2nd Edition - May 25, 2014) (updated for C++11/C++14) An introduction to programming using C++ by the creator of the language. A good read, that assumes no previous programming experience, but is not only for beginners.

Introductory, with previous programming experience

  • A Tour of C++ (Bjarne Stroustrup) (2nd edition for C++17) The “tour” is a quick (about 180 pages and 14 chapters) tutorial overview of all of standard C++ (language and standard library, and using C++11) at a moderately high level for people who already know C++ or at least are experienced programmers. This book is an extended version of the material that constitutes Chapters 2-5 of The C++ Programming Language, 4th edition.

  • Accelerated C++ (Andrew Koenig and Barbara Moo, 1st Edition - August 24, 2000) This basically covers the same ground as the C++ Primer, but does so on a fourth of its space. This is largely because it does not attempt to be an introduction to programming, but an introduction to C++ for people who've previously programmed in some other language. It has a steeper learning curve, but, for those who can cope with this, it is a very compact introduction to the language. (Historically, it broke new ground by being the first beginner's book to use a modern approach to teaching the language.) Despite this, the C++ it teaches is purely C++98. [Review]

Best practices

  • Effective C++ (Scott Meyers, 3rd Edition - May 22, 2005) This was written with the aim of being the best second book C++ programmers should read, and it succeeded. Earlier editions were aimed at programmers coming from C, the third edition changes this and targets programmers coming from languages like Java. It presents ~50 easy-to-remember rules of thumb along with their rationale in a very accessible (and enjoyable) style. For C++11 and C++14 the examples and a few issues are outdated and Effective Modern C++ should be preferred. [Review]

  • Effective Modern C++ (Scott Meyers) This is basically the new version of Effective C++, aimed at C++ programmers making the transition from C++03 to C++11 and C++14.

  • Effective STL (Scott Meyers) This aims to do the same to the part of the standard library coming from the STL what Effective C++ did to the language as a whole: It presents rules of thumb along with their rationale. [Review]


Intermediate

  • More Effective C++ (Scott Meyers) Even more rules of thumb than Effective C++. Not as important as the ones in the first book, but still good to know.

  • Exceptional C++ (Herb Sutter) Presented as a set of puzzles, this has one of the best and thorough discussions of the proper resource management and exception safety in C++ through Resource Acquisition is Initialization (RAII) in addition to in-depth coverage of a variety of other topics including the pimpl idiom, name lookup, good class design, and the C++ memory model. [Review]

  • More Exceptional C++ (Herb Sutter) Covers additional exception safety topics not covered in Exceptional C++, in addition to discussion of effective object-oriented programming in C++ and correct use of the STL. [Review]

  • Exceptional C++ Style (Herb Sutter) Discusses generic programming, optimization, and resource management; this book also has an excellent exposition of how to write modular code in C++ by using non-member functions and the single responsibility principle. [Review]

  • C++ Coding Standards (Herb Sutter and Andrei Alexandrescu) “Coding standards” here doesn't mean “how many spaces should I indent my code?” This book contains 101 best practices, idioms, and common pitfalls that can help you to write correct, understandable, and efficient C++ code. [Review]

  • C++ Templates: The Complete Guide (David Vandevoorde and Nicolai M. Josuttis) This is the book about templates as they existed before C++11. It covers everything from the very basics to some of the most advanced template metaprogramming and explains every detail of how templates work (both conceptually and at how they are implemented) and discusses many common pitfalls. Has excellent summaries of the One Definition Rule (ODR) and overload resolution in the appendices. A second edition covering C++11, C++14 and C++17 has been already published. [Review]

  • C++ 17 - The Complete Guide (Nicolai M. Josuttis) This book describes all the new features introduced in the C++17 Standard covering everything from the simple ones like 'Inline Variables', 'constexpr if' all the way up to 'Polymorphic Memory Resources' and 'New and Delete with overaligned Data'. [Review]

  • C++ in Action (Bartosz Milewski). This book explains C++ and its features by building an application from ground up. [Review]

  • Functional Programming in C++ (Ivan Cukic). This book introduces functional programming techniques to modern C++ (C++11 and later). A very nice read for those who want to apply functional programming paradigms to C++.

  • Professional C++ (Marc Gregoire, 5th Edition - Feb 2021) Provides a comprehensive and detailed tour of the C++ language implementation replete with professional tips and concise but informative in-text examples, emphasizing C++20 features. Uses C++20 features, such as modules and std::format throughout all examples.


Advanced

  • Modern C++ Design (Andrei Alexandrescu) A groundbreaking book on advanced generic programming techniques. Introduces policy-based design, type lists, and fundamental generic programming idioms then explains how many useful design patterns (including small object allocators, functors, factories, visitors, and multi-methods) can be implemented efficiently, modularly, and cleanly using generic programming. [Review]

  • C++ Template Metaprogramming (David Abrahams and Aleksey Gurtovoy)

  • C++ Concurrency In Action (Anthony Williams) A book covering C++11 concurrency support including the thread library, the atomics library, the C++ memory model, locks and mutexes, as well as issues of designing and debugging multithreaded applications. A second edition covering C++14 and C++17 has been already published. [Review]

  • Advanced C++ Metaprogramming (Davide Di Gennaro) A pre-C++11 manual of TMP techniques, focused more on practice than theory. There are a ton of snippets in this book, some of which are made obsolete by type traits, but the techniques, are nonetheless useful to know. If you can put up with the quirky formatting/editing, it is easier to read than Alexandrescu, and arguably, more rewarding. For more experienced developers, there is a good chance that you may pick up something about a dark corner of C++ (a quirk) that usually only comes about through extensive experience.


Reference Style - All Levels

  • The C++ Programming Language (Bjarne Stroustrup) (updated for C++11) The classic introduction to C++ by its creator. Written to parallel the classic K&R, this indeed reads very much like it and covers just about everything from the core language to the standard library, to programming paradigms to the language's philosophy. [Review] Note: All releases of the C++ standard are tracked in the question "Where do I find the current C or C++ standard documents?".

  • C++ Standard Library Tutorial and Reference (Nicolai Josuttis) (updated for C++11) The introduction and reference for the C++ Standard Library. The second edition (released on April 9, 2012) covers C++11. [Review]

  • The C++ IO Streams and Locales (Angelika Langer and Klaus Kreft) There's very little to say about this book except that, if you want to know anything about streams and locales, then this is the one place to find definitive answers. [Review]

C++11/14/17/… References:

  • The C++11/14/17 Standard (INCITS/ISO/IEC 14882:2011/2014/2017) This, of course, is the final arbiter of all that is or isn't C++. Be aware, however, that it is intended purely as a reference for experienced users willing to devote considerable time and effort to its understanding. The C++17 standard is released in electronic form for 198 Swiss Francs.

  • The C++17 standard is available, but seemingly not in an economical form – directly from the ISO it costs 198 Swiss Francs (about $200 US). For most people, the final draft before standardization is more than adequate (and free). Many will prefer an even newer draft, documenting new features that are likely to be included in C++20.

  • Overview of the New C++ (C++11/14) (PDF only) (Scott Meyers) (updated for C++14) These are the presentation materials (slides and some lecture notes) of a three-day training course offered by Scott Meyers, who's a highly respected author on C++. Even though the list of items is short, the quality is high.

  • The C++ Core Guidelines (C++11/14/17/…) (edited by Bjarne Stroustrup and Herb Sutter) is an evolving online document consisting of a set of guidelines for using modern C++ well. The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management and concurrency affecting application architecture and library design. The project was announced at CppCon'15 by Bjarne Stroustrup and others and welcomes contributions from the community. Most guidelines are supplemented with a rationale and examples as well as discussions of possible tool support. Many rules are designed specifically to be automatically checkable by static analysis tools.

  • The C++ Super-FAQ (Marshall Cline, Bjarne Stroustrup and others) is an effort by the Standard C++ Foundation to unify the C++ FAQs previously maintained individually by Marshall Cline and Bjarne Stroustrup and also incorporating new contributions. The items mostly address issues at an intermediate level and are often written with a humorous tone. Not all items might be fully up to date with the latest edition of the C++ standard yet.

  • cppreference.com (C++03/11/14/17/…) (initiated by Nate Kohl) is a wiki that summarizes the basic core-language features and has extensive documentation of the C++ standard library. The documentation is very precise but is easier to read than the official standard document and provides better navigation due to its wiki nature. The project documents all versions of the C++ standard and the site allows filtering the display for a specific version. The project was presented by Nate Kohl at CppCon'14.


Classics / Older

Note: Some information contained within these books may not be up-to-date or no longer considered best practice.

  • The Design and Evolution of C++ (Bjarne Stroustrup) If you want to know why the language is the way it is, this book is where you find answers. This covers everything before the standardization of C++.

  • Ruminations on C++ - (Andrew Koenig and Barbara Moo) [Review]

  • Advanced C++ Programming Styles and Idioms (James Coplien) A predecessor of the pattern movement, it describes many C++-specific “idioms”. It's certainly a very good book and might still be worth a read if you can spare the time, but quite old and not up-to-date with current C++.

  • Large Scale C++ Software Design (John Lakos) Lakos explains techniques to manage very big C++ software projects. Certainly, a good read, if it only was up to date. It was written long before C++ 98 and misses on many features (e.g. namespaces) important for large-scale projects. If you need to work in a big C++ software project, you might want to read it, although you need to take more than a grain of salt with it. The first volume of a new edition is released in 2019.

  • Inside the C++ Object Model (Stanley Lippman) If you want to know how virtual member functions are commonly implemented and how base objects are commonly laid out in memory in a multi-inheritance scenario, and how all this affects performance, this is where you will find thorough discussions of such topics.

  • The Annotated C++ Reference Manual (Bjarne Stroustrup, Margaret A. Ellis) This book is quite outdated in the fact that it explores the 1989 C++ 2.0 version - Templates, exceptions, namespaces and new casts were not yet introduced. Saying that however, this book goes through the entire C++ standard of the time explaining the rationale, the possible implementations, and features of the language. This is not a book to learn programming principles and patterns on C++, but to understand every aspect of the C++ language.

  • Thinking in C++ (Bruce Eckel, 2nd Edition, 2000). Two volumes; is a tutorial style free set of intro level books. Downloads: vol 1, vol 2. Unfortunately they're marred by a number of trivial errors (e.g. maintaining that temporaries are automatically const), with no official errata list. A partial 3rd party errata list is available at http://www.computersciencelab.com/Eckel.htm, but it is apparently not maintained.

  • Scientific and Engineering C++: An Introduction to Advanced Techniques and Examples (John Barton and Lee Nackman) It is a comprehensive and very detailed book that tried to explain and make use of all the features available in C++, in the context of numerical methods. It introduced at the time several new techniques, such as the Curiously Recurring Template Pattern (CRTP, also called Barton-Nackman trick). It pioneered several techniques such as dimensional analysis and automatic differentiation. It came with a lot of compilable and useful code, ranging from an expression parser to a Lapack wrapper. The code is still available online. Unfortunately, the books have become somewhat outdated in the style and C++ features, however, it was an incredible tour-de-force at the time (1994, pre-STL). The chapters on dynamics inheritance are a bit complicated to understand and not very useful. An updated version of this classic book that includes move semantics and the lessons learned from the STL would be very nice.

Error HRESULT E_FAIL has been returned from a call to a COM component VS2012 when debugging

I encountered this error after installing VS2019 but while trying to open a large solution (20+ projects), with both vcxproj and csproj projects, that target VS2015. The csproj all loaded fine, while the vcxproj all failed with the OP's error. Deleting the .vs folder did not work.

What did work was setting VC++'s "Fallback Location", under the "Browsing Database Fallback" settings.

Tools (menu)
-Options...
--Text Editor
---C/C++
---Advanced
----Browsing Database Fallback
-----Fallback Location

I set mine to D:\VC++\v16. Where I use v140 for VS2015 and v141 for VS2017. Also set "Always Use" and "Do not warn".

What's the difference between integer class and numeric class in R

To my understanding - we do not declare a variable with a data type so by default R has set any number without L to be a numeric. If you wrote:

> x <- c(4L, 5L, 6L, 6L)
> class(x)
>"integer" #it would be correct

Example of Integer:

> x<- 2L
> print(x)

Example of Numeric (kind of like double/float from other programming languages)

> x<-3.4
> print(x)

Horizontal Scroll Table in Bootstrap/CSS

Here is one possiblity for you if you are using Bootstrap 3

live view: http://fiddle.jshell.net/panchroma/vPH8N/10/show/

edit view: http://jsfiddle.net/panchroma/vPH8N/

I'm using the resposive table code from http://getbootstrap.com/css/#tables-responsive

ie:

<div class="table-responsive">
<table class="table">
...
</table>
</div>

What is the meaning of the CascadeType.ALL for a @ManyToOne JPA association

From the EJB3.0 Specification:

Use of the cascade annotation element may be used to propagate the effect of an operation to associated entities. The cascade functionality is most typically used in parent-child relationships.

If X is a managed entity, the remove operation causes it to become removed. The remove operation is cascaded to entities referenced by X, if the relationships from X to these other entities is annotated with the cascade=REMOVE or cascade=ALL annotation element value.

So in a nutshell, entity relationships defined with CascadeType.All will ensure that all persistence events such as persist, refresh, merge and remove that occur on the parent, will be passed to the child. Defining other CascadeType options provides the developer with a more granular level of control over how the entity association handles persistence.

For example if I had an object Book that contained a List of pages and I add a page object within this list. If the @OneToMany annotation defining the association between Book and Page is marked as CascadeType.All, persisting the Book would result in the Page also being persisted to the database.

Method List in Visual Studio Code

It is an extra part to the answer to this question here but I thought it might be useful. As many people mentioned, Visual Studio Code has the OUTLINE part which provides the ability to browse to different function and show them on the side.

I also wanted to add that if you check the follow cursor mark, it highlights that function name in the OUTLINE view, which is very helpful in browsing and seeing which function you are in.

enter image description here

No module named MySQLdb

I met the same situation under windows, and searched for the solution.

Seeing this post Install mysql-python (Windows).

It points out installing such a pip environment is difficult, needs many other dependencies.

But I finally know that if we use mysqlclient with a version down to 1.3.4, it don't need that requirements any more, so try:

pip install mysqlclient==1.3.4

Connect to SQL Server 2012 Database with C# (Visual Studio 2012)

Replacing server=localhost with server=.\SQLEXPRESS might do the job.

How to do relative imports in Python?

main.py
setup.py
app/ ->
    __init__.py
    package_a/ ->
       __init__.py
       module_a.py
    package_b/ ->
       __init__.py
       module_b.py
  1. You run python main.py.
  2. main.py does: import app.package_a.module_a
  3. module_a.py does import app.package_b.module_b

Alternatively 2 or 3 could use: from app.package_a import module_a

That will work as long as you have app in your PYTHONPATH. main.py could be anywhere then.

So you write a setup.py to copy (install) the whole app package and subpackages to the target system's python folders, and main.py to target system's script folders.

html - table row like a link

Thanks for this. You can change the hover icon by assigning a CSS class to the row like:

<tr class="pointer" onclick="document.location = 'links.html';">

and the CSS looks like:

<style>
    .pointer { cursor: pointer; }
</style>

How to get the current date without the time?

Well, you can get just today's date as a DateTime using the Today property:

 DateTime today = DateTime.Today;

or more generally, you can use the Date property. For example, if you wanted the UTC date you could use:

 DateTime dateTime = DateTime.UtcNow.Date;

It's not very clear whether that's what you need or not though... if you're just looking to print the date, you can use:

Console.WriteLine(dateTime.ToString("d"));

or use an explicit format:

Console.WriteLine(dateTime.ToString("dd/MM/yyyy"));

See more about standard and custom date/time format strings. Depending on your situation you may also want to specify the culture.

If you want a more expressive date/time API which allows you to talk about dates separately from times, you might want to look at the Noda Time project which I started. It's not ready for production just yet, but we'd love to hear what you'd like to do with it...

How to obtain Telegram chat_id for a specific user?

First, post a message in a chat where your bot is included (channel, group mentioning the bot, or one-to-one chat). Then, just run:

curl https://api.telegram.org/bot<TOKEN>/getUpdates | jq

Feel free to remove the | jq part if your dont have jq installed, it's only useful for pretty printing. You should get something like this:

enter image description here

You can see the chat ID in the returned json object, together with the chat name and associated message.

Convert MySql DateTime stamp into JavaScript's Date format

I think I may have found a simpler way, that nobody mentioned.

A MySQL DATETIME column can be converted to a unix timestamp through:

SELECT unix_timestamp(my_datetime_column) as stamp ...

We can make a new JavaScript Date object by using the constructor that requires milliseconds since the epoch. The unix_timestamp function returns seconds since the epoch, so we need to multiply by 1000:

SELECT unix_timestamp(my_datetime_column) * 1000 as stamp ...

The resulting value can be used directly to instantiate a correct Javascript Date object:

var myDate = new Date(<?=$row['stamp']?>);

Hope this helps.

Button background as transparent

Selectors work only for drawables, not styles. Reference


First, to make the button background transparent use the following attribute as this will not affect the material design animations:

style="?attr/buttonBarButtonStyle"

There are many ways to style your button. Check out this tutorial.

Second, to make the text bold on pressed, use this java code:

btn.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()) {
            // When the user clicks the Button
            case MotionEvent.ACTION_DOWN:
                btn.setTypeface(Typeface.DEFAULT_BOLD);
                break;

            // When the user releases the Button
            case MotionEvent.ACTION_UP:
                btn.setTypeface(Typeface.DEFAULT);
                break;
        }
        return false;
    }
});

Concatenate text files with Windows command line, dropping leading lines

I don't have enough reputation points to comment on the recommendation to use *.csv >> ConcatenatedFile.csv, but I can add a warning:

If you create ConcatenatedFile.csv file in the same directory that you are using for concatenation it will be added to itself.

Font awesome is not showing icon

For a start, you shouldn't have both font-awesome.css and font-awesome.min.css

Generally, use font-awesome.css during development, then switch to font-awesome.min.css once you're happy with the site.

Problems like this are often caused by relative paths and locations, so check where your html file is in relation to the css.

If your html file is in the base directory, and the css in a subfolder off the root, you would need: href="./css/font-awesome.css" (single period)

SQL Server IN vs. EXISTS Performance

I've done some testing on SQL Server 2005 and 2008, and on both the EXISTS and the IN come back with the exact same actual execution plan, as other have stated. The Optimizer is optimal. :)

Something to be aware of though, EXISTS, IN, and JOIN can sometimes return different results if you don't phrase your query just right: http://weblogs.sqlteam.com/mladenp/archive/2007/05/18/60210.aspx

Convert javascript object or array to json for ajax data

You can use JSON.stringify(object) with an object and I just wrote a function that'll recursively convert an array to an object, like this JSON.stringify(convArrToObj(array)), which is the following code (more detail can be found on this answer):

// Convert array to object
var convArrToObj = function(array){
    var thisEleObj = new Object();
    if(typeof array == "object"){
        for(var i in array){
            var thisEle = convArrToObj(array[i]);
            thisEleObj[i] = thisEle;
        }
    }else {
        thisEleObj = array;
    }
    return thisEleObj;
}

To make it more generic, you can override the JSON.stringify function and you won't have to worry about it again, to do this, just paste this at the top of your page:

// Modify JSON.stringify to allow recursive and single-level arrays
(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        return oldJSONStringify(convArrToObj(input));
    };
})();

And now JSON.stringify will accept arrays or objects! (link to jsFiddle with example)


Edit:

Here's another version that's a tad bit more efficient, although it may or may not be less reliable (not sure -- it depends on if JSON.stringify(array) always returns [], which I don't see much reason why it wouldn't, so this function should be better as it does a little less work when you use JSON.stringify with an object):

(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        if(oldJSONStringify(input) == '[]')
            return oldJSONStringify(convArrToObj(input));
        else
            return oldJSONStringify(input);
    };
})();

jsFiddle with example here

js Performance test here, via jsPerf

Split string into array of character strings

If characters beyond Basic Multilingual Plane are expected on input (some CJK characters, new emoji...), approaches such as "ab".split("(?!^)") cannot be used, because they break such characters (results into array ["a", "?", "?", "b"]) and something safer has to be used:

"ab".codePoints()
    .mapToObj(cp -> new String(Character.toChars(cp)))
    .toArray(size -> new String[size]);

React proptype array with shape

Yes, you need to use PropTypes.arrayOf instead of PropTypes.array in the code, you can do something like this:

import PropTypes from 'prop-types';

MyComponent.propTypes = {
  annotationRanges: PropTypes.arrayOf(
    PropTypes.shape({
      start: PropTypes.string.isRequired,
      end: PropTypes.number.isRequired
    }).isRequired
  ).isRequired
}

Also for more details about proptypes, visit Typechecking With PropTypes here

PHP, MySQL error: Column count doesn't match value count at row 1

The number of column parameters in your insert query is 9, but you've only provided 8 values.

INSERT INTO dbname (id, Name, Description, shortDescription, Ingredients, Method, Length, dateAdded, Username) VALUES ('', '%s', '%s', '%s', '%s', '%s', '%s', '%s')

The query should omit the "id" parameter, because it is auto-generated (or should be anyway):

INSERT INTO dbname (Name, Description, shortDescription, Ingredients, Method, Length, dateAdded, Username) VALUES ('', '%s', '%s', '%s', '%s', '%s', '%s', '%s')

How to make a website secured with https

4.Do I need to make all my pages secured or only the login page...

Just keep the login page under https

this will ensure there is no overhead when browsing other pages. the condition is you need to provide correct authentication settings in the web config. This is to ensure users who are not logged in will not be able to browse pages that would need authentication.

Convert JSON String to Pretty Print JSON output using Jackson

The new way using Jackson 1.9+ is the following:

Object json = OBJECT_MAPPER.readValue(diffResponseJson, Object.class);
String indented = OBJECT_MAPPER.writerWithDefaultPrettyPrinter()
                               .writeValueAsString(json);

The output will be correctly formatted!

Javascript split regex question

or just (anything but numbers):

date.split(/\D/);

jQuery check if an input is type checkbox?

You can use the pseudo-selector :checkbox with a call to jQuery's is function:

$('#myinput').is(':checkbox')

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]

I had met a similar problem, after i add a scope property of servlet dependency in pom.xml

 <dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

Then it was ok . maybe that will help you.

GROUP_CONCAT comma separator - MySQL

Query to achieve your requirment

SELECT id,GROUP_CONCAT(text SEPARATOR ' ') AS text FROM table_name group by id;

How can I initialize a String array with length 0 in Java?

Make a function which will not return null instead return an empty array you can go through below code to understand.

    public static String[] getJavaFileNameList(File inputDir) {
    String[] files = inputDir.list(new FilenameFilter() {
        @Override
        public boolean accept(File current, String name) {
            return new File(current, name).isFile() && (name.endsWith("java"));
        }
    });

    return files == null ? new String[0] : files;
}

Easy way of running the same junit test over and over?

Inspired by the following resources:

Example

Create and use a @Repeat annotation as follows:

public class MyTestClass {

    @Rule
    public RepeatRule repeatRule = new RepeatRule();

    @Test
    @Repeat(10)
    public void testMyCode() {
        //your test code goes here
    }
}

Repeat.java

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention( RetentionPolicy.RUNTIME )
@Target({ METHOD, ANNOTATION_TYPE })
public @interface Repeat {
    int value() default 1;
}

RepeatRule.java

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

public class RepeatRule implements TestRule {

    private static class RepeatStatement extends Statement {
        private final Statement statement;
        private final int repeat;    

        public RepeatStatement(Statement statement, int repeat) {
            this.statement = statement;
            this.repeat = repeat;
        }

        @Override
        public void evaluate() throws Throwable {
            for (int i = 0; i < repeat; i++) {
                statement.evaluate();
            }
        }

    }

    @Override
    public Statement apply(Statement statement, Description description) {
        Statement result = statement;
        Repeat repeat = description.getAnnotation(Repeat.class);
        if (repeat != null) {
            int times = repeat.value();
            result = new RepeatStatement(statement, times);
        }
        return result;
    }
}

PowerMock

Using this solution with @RunWith(PowerMockRunner.class), requires updating to Powermock 1.6.5 (which includes a patch).

ExecuteReader requires an open and available Connection. The connection's current state is Connecting

Sorry for only commenting in the first place, but i'm posting almost every day a similar comment since many people think that it would be smart to encapsulate ADO.NET functionality into a DB-Class(me too 10 years ago). Mostly they decide to use static/shared objects since it seems to be faster than to create a new object for any action.

That is neither a good idea in terms of peformance nor in terms of fail-safety.

Don't poach on the Connection-Pool's territory

There's a good reason why ADO.NET internally manages the underlying Connections to the DBMS in the ADO-NET Connection-Pool:

In practice, most applications use only one or a few different configurations for connections. This means that during application execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling.

Connection pooling reduces the number of times that new connections must be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.

So obviously there's no reason to avoid creating,opening or closing connections since actually they aren't created,opened and closed at all. This is "only" a flag for the connection pool to know when a connection can be reused or not. But it's a very important flag, because if a connection is "in use"(the connection pool assumes), a new physical connection must be openend to the DBMS what is very expensive.

So you're gaining no performance improvement but the opposite. If the maximum pool size specified (100 is the default) is reached, you would even get exceptions(too many open connections ...). So this will not only impact the performance tremendously but also be a source for nasty errors and (without using Transactions) a data-dumping-area.

If you're even using static connections you're creating a lock for every thread trying to access this object. ASP.NET is a multithreading environment by nature. So theres a great chance for these locks which causes performance issues at best. Actually sooner or later you'll get many different exceptions(like your ExecuteReader requires an open and available Connection).

Conclusion:

  • Don't reuse connections or any ADO.NET objects at all.
  • Don't make them static/shared(in VB.NET)
  • Always create, open(in case of Connections), use, close and dispose them where you need them(f.e. in a method)
  • use the using-statement to dispose and close(in case of Connections) implicitely

That's true not only for Connections(although most noticable). Every object implementing IDisposable should be disposed(simplest by using-statement), all the more in the System.Data.SqlClient namespace.

All the above speaks against a custom DB-Class which encapsulates and reuse all objects. That's the reason why i commented to trash it. That's only a problem source.


Edit: Here's a possible implementation of your retrievePromotion-method:

public Promotion retrievePromotion(int promotionID)
{
    Promotion promo = null;
    var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        var queryString = "SELECT PromotionID, PromotionTitle, PromotionURL FROM Promotion WHERE PromotionID=@PromotionID";
        using (var da = new SqlDataAdapter(queryString, connection))
        {
            // you could also use a SqlDataReader instead
            // note that a DataTable does not need to be disposed since it does not implement IDisposable
            var tblPromotion = new DataTable();
            // avoid SQL-Injection
            da.SelectCommand.Parameters.Add("@PromotionID", SqlDbType.Int);
            da.SelectCommand.Parameters["@PromotionID"].Value = promotionID;
            try
            {
                connection.Open(); // not necessarily needed in this case because DataAdapter.Fill does it otherwise 
                da.Fill(tblPromotion);
                if (tblPromotion.Rows.Count != 0)
                {
                    var promoRow = tblPromotion.Rows[0];
                    promo = new Promotion()
                    {
                        promotionID    = promotionID,
                        promotionTitle = promoRow.Field<String>("PromotionTitle"),
                        promotionUrl   = promoRow.Field<String>("PromotionURL")
                    };
                }
            }
            catch (Exception ex)
            {
                // log this exception or throw it up the StackTrace
                // we do not need a finally-block to close the connection since it will be closed implicitely in an using-statement
                throw;
            }
        }
    }
    return promo;
}

Is it possible to get only the first character of a String?

Answering for C++ 14,

Yes, you can get the first character of a string simply by the following code snippet.

string s = "Happynewyear";
cout << s[0];

if you want to store the first character in a separate string,

string s = "Happynewyear";
string c = "";
c.push_back(s[0]);
cout << c;

Permission denied (publickey,keyboard-interactive)

You need to change the sshd_config file in the remote server (probably in /etc/ssh/sshd_config).

Change

PasswordAuthentication no

to

PasswordAuthentication yes

And then restart the sshd daemon.

Detect if a NumPy array contains at least one non-numeric value?

(np.where(np.isnan(A)))[0].shape[0] will be greater than 0 if A contains at least one element of nan, A could be an n x m matrix.

Example:

import numpy as np

A = np.array([1,2,4,np.nan])

if (np.where(np.isnan(A)))[0].shape[0]: 
    print "A contains nan"
else:
    print "A does not contain nan"

What's the u prefix in a Python string?

I came here because I had funny-char-syndrome on my requests output. I thought response.text would give me a properly decoded string, but in the output I found funny double-chars where German umlauts should have been.

Turns out response.encoding was empty somehow and so response did not know how to properly decode the content and just treated it as ASCII (I guess).

My solution was to get the raw bytes with 'response.content' and manually apply decode('utf_8') to it. The result was schöne Umlaute.

The correctly decoded

für

vs. the improperly decoded

fAzr

Get characters after last / in url

Two one liners - I suspect the first one is faster but second one is prettier and unlike end() and array_pop(), you can pass the result of a function directly to current() without generating any notice or warning since it doesn't move the pointer or alter the array.

$var = 'http://www.vimeo.com/1234567';

// VERSION 1 - one liner simmilar to DisgruntledGoat's answer above
echo substr($a,(strrpos($var,'/') !== false ? strrpos($var,'/') + 1 : 0));

// VERSION 2 - explode, reverse the array, get the first index.
echo current(array_reverse(explode('/',$var)));

Using NotNull Annotation in method argument

SO @NotNull just is a tag...If you want to validate it, then you must use something like hibernate validator jsr 303

ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();
 Set<ConstraintViolation<List<Searching>> violations = validator.validate(searchingList);

Can't import javax.servlet.annotation.WebServlet

Add library 'Server Runtime' to your java build path, and it shall resolve the issue.

Insert null/empty value in sql datetime column by default

if there is no value inserted, the default value should be null,empty

In the table definition, make this datetime column allows null, be not defining NOT NULL:

...
DateTimeColumn DateTime,
...

I HAVE ALLOWED NULL VARIABLES THOUGH.

Then , just insert NULL in this column:

INSERT INTO Table(name, datetimeColumn, ...)
VALUES('foo bar', NULL, ..);

Or, you can make use of the DEFAULT constaints:

...
DateTimeColumn DateTime DEFAULT NULL,
...

Then you can ignore it completely in the INSERT statement and it will be inserted withe the NULL value:

INSERT INTO Table(name, ...)
VALUES('foo bar', ..);

RESTful Authentication

I think restful authentication involves the passing of an authentication token as a parameter in the request. Examples are the use of apikeys by api's. I don't believe the use of cookies or http auth qualifies.

How to Configure SSL for Amazon S3 bucket

You can access your files via SSL like this:

https://s3.amazonaws.com/bucket_name/images/logo.gif

If you use a custom domain for your bucket, you can use S3 and CloudFront together with your own SSL certificate (or generate a free one via Amazon Certificate Manager): http://aws.amazon.com/cloudfront/custom-ssl-domains/

LaTeX Optional Arguments

Here's my attempt, it doesn't follow your specs exactly though. Not fully tested, so be cautious.

\newcount\seccount

\def\sec{%
    \seccount0%
    \let\go\secnext\go
}

\def\secnext#1{%
    \def\last{#1}%
    \futurelet\next\secparse
}

\def\secparse{%
    \ifx\next\bgroup
        \let\go\secparseii
    \else
        \let\go\seclast
    \fi
    \go
}

\def\secparseii#1{%
    \ifnum\seccount>0, \fi
    \advance\seccount1\relax
    \last
    \def\last{#1}%
    \futurelet\next\secparse
}

\def\seclast{\ifnum\seccount>0{} and \fi\last}%

\sec{a}{b}{c}{d}{e}
% outputs "a, b, c, d and e"

\sec{a}
% outputs "a"

\sec{a}{b}
% outputs "a and b"

Can we create an instance of an interface in Java?

No in my opinion , you can create a reference variable of an interface but you can not create an instance of an interface just like an abstract class.

Can't create project on Netbeans 8.2

Yes it s working: remove the path of jdk 9.0 and uninstall this from Cantroll panel instead install jdk 8version and set it's path, it is working easily with netbean 8.2.

NULL values inside NOT IN clause

also this might be of use to know the logical difference between join, exists and in http://weblogs.sqlteam.com/mladenp/archive/2007/05/18/60210.aspx

MySQL SELECT LIKE or REGEXP to match multiple words in one record

you need to do something like this,

SELECT * FROM buckets WHERE bucketname RLIKE 'Stylus.*2100';

or

SELECT * FROM buckets WHERE bucketname RLIKE '(Stylus)+.*(2100)+';

React Native Change Default iOS Simulator Device

There is a project setting if you hunt down:

{project}/node_modules/react-native/local-cli/runIOS/runIOS.js

Within there are some options under module.exports including:

options: [{ command: '--simulator [string]', description: 'Explicitly set simulator to use', default: 'iPhone 7', }

Mine was line 231, simply set that to a valid installed simulator and run react-native run-ios it will run to that simulator by default.

JavaScript inside an <img title="<a href='#' onClick='alert('Hello World!')>The Link</a>" /> possible?

<img title="<a href="javascript:alert('hello world')">The Link</a>" /> 

Javascript one line If...else...else if statement

This is use mostly for assigning variable, and it uses binomial conditioning eg.

var time = Date().getHours(); // or something

var clockTime = time > 12 ? 'PM' : 'AM' ;

There is no ElseIf, for the sake of development don't use chaining, you can use switch which is much faster if you have multiple conditioning in .js

How to make java delay for a few seconds?

A couple problems, you aren't delaying by much (.sleep is milliseconds, not seconds), and you're attempting to print in your catch statement. Your code should look more like:

if (i==1) {
    try {
        System.out.println("Scanning...");
        Thread.sleep(1000); // 1 second
    } catch (InterruptedException ex) {
        // handle error
    }
}

How do you close/hide the Android soft keyboard using Java?

Works like magic touch every time

private void closeKeyboard() {
    InputMethodManager inputManager = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

}

private void openKeyboard() {
    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    if(imm != null){
        imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
    }
}

When to use references vs. pointers

For pointers, you need them to point to something, so pointers cost memory space.

For example a function that takes an integer pointer will not take the integer variable. So you will need to create a pointer for that first to pass on to the function.

As for a reference, it will not cost memory. You have an integer variable, and you can pass it as a reference variable. That's it. You don't need to create a reference variable specially for it.

Android: How to turn screen on and off programmatically?

This is worked on Marshmallow

private final String TAG = "OnOffScreen";
private PowerManager _powerManager;
private PowerManager.WakeLock _screenOffWakeLock;

public void turnOnScreen() {
    if (_screenOffWakeLock != null) {
        _screenOffWakeLock.release();
    }
}

public void turnOffScreen() {
    try {
        _powerManager = (PowerManager) this.getSystemService(POWER_SERVICE);
        if (_powerManager != null) {
            _screenOffWakeLock = _powerManager.newWakeLock(PROXIMITY_SCREEN_OFF_WAKE_LOCK, TAG);
            if (_screenOffWakeLock != null) {
                _screenOffWakeLock.acquire();
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

Easiest way to open a download window without navigating away from the page

I know the question was asked 7 years and 9 months ago but many posted solutions doesn't seem to work, for example using an <iframe> works only with FireFox and doesn't work with Chrome.

Best solution:

The best working solution to open a file download pop-up in JavaScript is to use a HTML link element, with no need to append the link element to the document.body as stated in other answers.

You can use the following function:

function downloadFile(filePath){
    var link=document.createElement('a');
    link.href = filePath;
    link.download = filePath.substr(filePath.lastIndexOf('/') + 1);
    link.click();
}

In my application, I am using it this way:

downloadFile('report/xls/myCustomReport.xlsx');

Working Demo:

_x000D_
_x000D_
function downloadFile(filePath) {_x000D_
  var link = document.createElement('a');_x000D_
  link.href = filePath;_x000D_
  link.download = filePath.substr(filePath.lastIndexOf('/') + 1);_x000D_
  link.click();_x000D_
}_x000D_
_x000D_
downloadFile("http://www.adobe.com/content/dam/Adobe/en/accessibility/pdfs/accessing-pdf-sr.pdf");
_x000D_
_x000D_
_x000D_

Note:

  • You have to use the link.download attribute so the browser doesn't open the file in a new tab and fires the download pop-up.
  • This was tested with several file types (docx, xlsx, png, pdf, ...).

How to add a "open git-bash here..." context menu to the windows explorer?

Had a similar issue in adding "Start Command Prompt with Ruby" to context menu as it involves passing parameters along with the patch of cmd. Followed a similar procedure as the solution above

Windows Registry Editor Version 5.00 

[HKEY_CLASSES_ROOT\*\shell\Cmd With Ruby]  
@="Cmd With Ruby"  
"Icon"="C:\\Windows\\System32\\cmd.exe"

[HKEY_CLASSES_ROOT\*\shell\Cmd With Ruby\command]
@="\"C:\\Windows\\System32\\cmd.exe\" \"/E:ON /K
\"C:\\Ruby25-x64\\bin\\setrbvars.cmd\"\" \"--cd=%1\"\""


[HKEY_CLASSES_ROOT\Directory\shell\bash]  
@="Cmd With Ruby"  
"Icon"="C:\\Windows\\System32\\cmd.exe"


[HKEY_CLASSES_ROOT\Directory\shell\bash\command]
@="\"C:\\Windows\\System32\\cmd.exe\" \"/E:ON /K
\"C:\\Ruby25-x64\\bin\\setrbvars.cmd\"\" \"--cd=%1\"\"" 

[HKEY_CLASSES_ROOT\Directory\Background\shell\bash]  
@="Cmd With Ruby"  
"Icon"="C:\\Windows\\System32\\cmd.exe"


[HKEY_CLASSES_ROOT\Directory\Background\shell\bash\command]
@="\"C:\\Windows\\System32\\cmd.exe\" \"/E:ON /K
\"C:\\Ruby25-x64\\bin\\setrbvars.cmd\"\" \"--cd=%v.\"\""

Page scroll when soft keyboard popped up

For me the only thing that works is put in the activity in the manifest this atribute:

android:windowSoftInputMode="stateHidden|adjustPan"

To not show the keyboard when opening the activity and don't overlap the bottom of the view.

What should I use to open a url instead of urlopen in urllib3

With gazpacho you could pipeline the page straight into a parse-able soup object:

from gazpacho import Soup
url = "http://www.thefamouspeople.com/singers.php"
soup = Soup.get(url)

And run finds on top of it:

soup.find("div")

How to update-alternatives to Python 3 without breaking apt?

replace

[bash:~] $ sudo update-alternatives --install /usr/bin/python python \
/usr/bin/python2.7 2

[bash:~] $ sudo update-alternatives --install /usr/bin/python python \
/usr/bin/python3.5 3

with

[bash:~] $ sudo update-alternatives --install /usr/local/bin/python python \
/usr/bin/python2.7 2

[bash:~] $ sudo update-alternatives --install /usr/local/bin/python python \
/usr/bin/python3.5 3

e.g. installing into /usr/local/bin instead of /usr/bin.

and ensure the /usr/local/bin is before /usr/bin in PATH.

i.e.

[bash:~] $ echo $PATH
/usr/local/bin:/usr/bin:/bin

Ensure this always is the case by adding

export PATH=/usr/local/bin:$PATH

to the end of your ~/.bashrc file. Prefixing the PATH environment variable with custom bin folder such as /usr/local/bin or /opt/<some install>/bin is generally recommended to ensure that customizations are found before the default system ones.

Convert Current date to integer

tl;dr

Instant.now().getEpochSecond()  // The number of seconds from the Java epoch of 1970-01-01T00:00:00Z.

Details

As others stated, a 32-bit integer cannot hold a number big enough for the number of seconds from the epoch (beginning of 1970 in UTC) and now. You need 64-bit integer (a long primitive or Long object).

java.time

The other answers are using old legacy date-time classes. They have been supplanted by the java.time classes.

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.

Instant now = instant.now() ;

You can interrogate for the number of milliseconds since the epoch. Beware this means a loss of data, truncating nanoseconds to milliseconds.

long millisecondsSinceEpoch = now.toEpochMilli() ;

If you want a count of nanoseconds since epoch, you will need to do a bit of math as the class oddly lacks a toEpochNano method. Note the L appended to the billion to provoke the calculation as 64-bit long integers.

long nanosecondsSinceEpoch = ( instant.getEpochSecond() * 1_000_000_000L ) + instant.getNano() ;

Whole seconds since epoch

But the end of the Question asks for a 10-digit number. I suspect that means a count of whole seconds since the epoch of 1970-01-01T00:00:00. This is commonly referred to as Unix Time or Posix Time.

We can interrogate the Instant for this number. Again, this means a loss of data with the truncation of any fraction-of-second this object may hold.

long secondsSinceEpoch = now.getEpochSecond() ;  // The number of seconds from the Java epoch of 1970-01-01T00:00:00Z.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

In angular 7.x I used angular-elements for this.

  1. Install @angular-elements npm i @angular/elements -s

  2. Create accessory service.

import { Injectable, Injector } from '@angular/core';
import { createCustomElement } from '@angular/elements';
import { IStringAnyMap } from 'src/app/core/models';
import { AppUserIconComponent } from 'src/app/shared';

const COMPONENTS = {
  'user-icon': AppUserIconComponent
};

@Injectable({
  providedIn: 'root'
})
export class DynamicComponentsService {
  constructor(private injector: Injector) {

  }

  public register(): void {
    Object.entries(COMPONENTS).forEach(([key, component]: [string, any]) => {
      const CustomElement = createCustomElement(component, { injector: this.injector });
      customElements.define(key, CustomElement);
    });
  }

  public create(tagName: string, data: IStringAnyMap = {}): HTMLElement {
    const customEl = document.createElement(tagName);

    Object.entries(data).forEach(([key, value]: [string, any]) => {
      customEl[key] = value;
    });

    return customEl;
  }
}

Note that you custom element tag must be different with angular component selector. in AppUserIconComponent:

...
selector: app-user-icon
...

and in this case custom tag name I used "user-icon".

  1. Then you must call register in AppComponent:
@Component({
  selector: 'app-root',
  template: '<router-outlet></router-outlet>'
})
export class AppComponent {
  constructor(   
    dynamicComponents: DynamicComponentsService,
  ) {
    dynamicComponents.register();
  }

}
  1. And now in any place of your code you can use it like this:
dynamicComponents.create('user-icon', {user:{...}});

or like this:

const html = `<div class="wrapper"><user-icon class="user-icon" user='${JSON.stringify(rec.user)}'></user-icon></div>`;

this.content = this.domSanitizer.bypassSecurityTrustHtml(html);

(in template):

<div class="comment-item d-flex" [innerHTML]="content"></div>

Note that in second case you must pass objects with JSON.stringify and after that parse it again. I can't find better solution.

How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

You're talking about histograms, but this doesn't quite make sense. Histograms and bar charts are different things. An histogram would be a bar chart representing the sum of values per year, for example. Here, you just seem to be after bars.

Here is a complete example from your data that shows a bar of for each required value at each date:

import pylab as pl
import datetime

data = """0 14-11-2003
1 15-03-1999
12 04-12-2012
33 09-05-2007
44 16-08-1998
55 25-07-2001
76 31-12-2011
87 25-06-1993
118 16-02-1995
119 10-02-1981
145 03-05-2014"""

values = []
dates = []

for line in data.split("\n"):
    x, y = line.split()
    values.append(int(x))
    dates.append(datetime.datetime.strptime(y, "%d-%m-%Y").date())

fig = pl.figure()
ax = pl.subplot(111)
ax.bar(dates, values, width=100)
ax.xaxis_date()

You need to parse the date with strptime and set the x-axis to use dates (as described in this answer).

If you're not interested in having the x-axis show a linear time scale, but just want bars with labels, you can do this instead:

fig = pl.figure()
ax = pl.subplot(111)
ax.bar(range(len(dates)), values)

EDIT: Following comments, for all the ticks, and for them to be centred, pass the range to set_ticks (and move them by half the bar width):

fig = pl.figure()
ax = pl.subplot(111)
width=0.8
ax.bar(range(len(dates)), values, width=width)
ax.set_xticks(np.arange(len(dates)) + width/2)
ax.set_xticklabels(dates, rotation=90)

How to reset the state of a Redux store?

I'd like to point out that the accepted comment by Dan Abramov is correct except we experienced a strange issue when using the react-router-redux package along with this approach. Our fix was to not set state to undefined but rather still use the current routing reducer. So I would suggest implementing the solution below if you are using this package

const rootReducer = (state, action) => {
  if (action.type === 'USER_LOGOUT') {
    const { routing } = state
    state = { routing } 
  }
  return appReducer(state, action)
}

smtp configuration for php mail

But now it is not working and I contacted our hosting team then they told me to use smtp

Newsflash - it was using SMTP before. They've not provided you with the information you need to solve the problem - or you've not relayed it accurately here.

Its possible that they've disabled the local MTA on the webserver, in which case you'll need to connect the SMTP port on a remote machine. There are lots of toolkits which will do the heavy lifting for you. Personally I like phpmailer because it adds other functionality.

Certainly if they've taken away a facility which was there before and your paying for a service then your provider should be giving you better support than that (there are also lots of programs to drop in in place of a full MTA which would do the job).

C.

android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

In case someone gets similar issues, I had such an issue while inflating the view:

View.inflate(getApplicationContext(), R.layout.my_layout, null)

fixed by replacing getApplicationContext() with this

How can I list all commits that changed a specific file?

It should be as simple as git log <somepath>; check the manpage (git-log(1)).

Personally I like to use git log --stat <path> so I can see the impact of each commit on the file.

Vim delete blank lines

This worked for me:

:%s/^[^a-zA-Z0-9]$\n//ig

It basically deletes all the lines that don't have a number or letter. Since all the items in my list had letters, it deleted all the blank lines.

Accessing a class' member variables in Python?

The answer, in a few words

In your example, itsProblem is a local variable.

Your must use self to set and get instance variables. You can set it in the __init__ method. Then your code would be:

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

But if you want a true class variable, then use the class name directly:

class Example(object):
    itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)
print (Example.itsProblem)

But be careful with this one, as theExample.itsProblem is automatically set to be equal to Example.itsProblem, but is not the same variable at all and can be changed independently.

Some explanations

In Python, variables can be created dynamically. Therefore, you can do the following:

class Example(object):
    pass

Example.itsProblem = "problem"

e = Example()
e.itsSecondProblem = "problem"

print Example.itsProblem == e.itsSecondProblem 

prints

True

Therefore, that's exactly what you do with the previous examples.

Indeed, in Python we use self as this, but it's a bit more than that. self is the the first argument to any object method because the first argument is always the object reference. This is automatic, whether you call it self or not.

Which means you can do:

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

or:

class Example(object):
    def __init__(my_super_self):
        my_super_self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

It's exactly the same. The first argument of ANY object method is the current object, we only call it self as a convention. And you add just a variable to this object, the same way you would do it from outside.

Now, about the class variables.

When you do:

class Example(object):
    itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

You'll notice we first set a class variable, then we access an object (instance) variable. We never set this object variable but it works, how is that possible?

Well, Python tries to get first the object variable, but if it can't find it, will give you the class variable. Warning: the class variable is shared among instances, and the object variable is not.

As a conclusion, never use class variables to set default values to object variables. Use __init__ for that.

Eventually, you will learn that Python classes are instances and therefore objects themselves, which gives new insight to understanding the above. Come back and read this again later, once you realize that.

Check if string ends with one of the strings from a list

There is two ways: regular expressions and string (str) methods.

String methods are usually faster ( ~2x ).

import re, timeit
p = re.compile('.*(.mp3|.avi)$', re.IGNORECASE)
file_name = 'test.mp3'
print(bool(t.match(file_name))
%timeit bool(t.match(file_name)

792 ns ± 1.83 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

file_name = 'test.mp3'
extensions = ('.mp3','.avi')
print(file_name.lower().endswith(extensions))
%timeit file_name.lower().endswith(extensions)

274 ns ± 4.22 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

How to use MapView in android using google map V2?

yes you can use MapView in v2... for further details you can get help from this

https://gist.github.com/joshdholtz/4522551


SomeFragment.java

public class SomeFragment extends Fragment implements OnMapReadyCallback{
 
    MapView mapView;
    GoogleMap map;
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.some_layout, container, false);
 
        // Gets the MapView from the XML layout and creates it
        mapView = (MapView) v.findViewById(R.id.mapview);
        mapView.onCreate(savedInstanceState);
 
    
        mapView.getMapAsync(this);
        
 
        return v;
    }
 
   @Override
   public void onMapReady(GoogleMap googleMap) {
       map = googleMap;
       map.getUiSettings().setMyLocationButtonEnabled(false);
       map.setMyLocationEnabled(true);
       /*
       //in old Api Needs to call MapsInitializer before doing any CameraUpdateFactory call
        try {
            MapsInitializer.initialize(this.getActivity());
        } catch (GooglePlayServicesNotAvailableException e) {
            e.printStackTrace();
        } 
       */
        
        // Updates the location and zoom of the MapView
        /*CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
        map.animateCamera(cameraUpdate);*/
        map.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(43.1, -87.9)));

    }

    @Override
    public void onResume() {
        mapView.onResume();
        super.onResume();
    }


    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }
 
    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }
 
    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }
 
}

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example"
    android:versionCode="1"
    android:versionName="1.0" >
    
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>
    
    <permission
        android:name="com.example.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>
    <uses-permission android:name="com.example.permission.MAPS_RECEIVE"/>
    
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="your_key"/>
        
        <activity
            android:name=".HomeActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    
    </application>
 
</manifest>

some_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    
    <com.google.android.gms.maps.MapView android:id="@+id/mapview"
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" />
 
</LinearLayout>

CSS Div width percentage and padding without breaking layout

Try removing the position from header and add overflow to container:

#container {
    position:relative;
    width:80%;
    height:auto;
    overflow:auto;
}
#header {
    width:80%;
    height:50px;
    padding:10px;
}

How to give spacing between buttons using bootstrap

The original code is mostly there, but you need btn-groups around each button. In Bootstrap 3 you can use a btn-toolbar and a btn-group to get the job done; I haven't done BS4 but it has similar constructs.

<div class="btn-toolbar" role="toolbar">
  <div class="btn-group" role="group">
    <button class="btn btn-default">Button 1</button>
  </div>
  <div class="btn-group" role="group">
    <button class="btn btn-default">Button 2</button>
  </div>
</div>

When is "java.io.IOException:Connection reset by peer" thrown?

To expand on BalusC's answer, any scenario where the sender continues to write after the peer has stopped reading and closed its socket will produce this exception, as will the peer closing while it still had unread data in its own socket receive buffer. In other words, an application protocol error. For example, if you write something to the peer that the peer doesn't understand, and then it closes its socket in protest, and you then continue to write, the peer's TCP stack will issue an RST, which results in this exception and message at the sender.

Difference between classification and clustering in data mining?

+Classification: you are given some new data, you have to set new label for them.

For example, a company wants to classify their prospect customers. When a new customer comes, they have to determine if this is a customer who is going to buy their products or not.

+Clustering: you're given a set of history transactions which recorded who bought what.

By using clustering techniques, you can tell the segmentation of your customers.

onclick="javascript:history.go(-1)" not working in Chrome

Try this:

<a href="www.mypage.com" onclick="history.go(-1); return false;"> Link </a>

Which is the preferred way to concatenate a string in Python?

The recommended method is still to use append and join.

Editable 'Select' element

Based on the other answers, here is a first draft for usage with knockout:

Usage

      <div data-bind="editableSelect: {options: optionsObservable, value: nameObservable}"></div>

Knockout data binding

composition.addBindingHandler('editableSelect',
  {
    init: function(hostElement, valueAccessor) {

      var optionsObservable = getOptionsObservable();
      var valueObservable = getValueObservable();

      var $editableSelect = $(hostElement);
      $editableSelect.addClass('select-editable');

      var editableSelect = $editableSelect[0];

      var viewModel = new editableSelectViewModel(optionsObservable, valueObservable);
      ko.applyBindingsToNode(editableSelect, { compose: viewModel });

      //tell knockout to not apply bindings twice
      return { controlsDescendantBindings: true };

      function getOptionsObservable() {
        var accessor = valueAccessor();
        return getAttribute(accessor, 'options');
      }

      function getValueObservable() {
        var accessor = valueAccessor();
        return getAttribute(accessor, 'value');
      }
    }
  });

View

<select
  data-bind="options: options, event:{ focus: resetComboBoxValue, change: setTextFieldValue} "
  id="comboBox"
  ></select>
<input
  data-bind="value: value, , event:{ focus: textFieldGotFocus, focusout: textFieldLostFocus}"
  id="textField"
  type="text"/>

ViewModel

define([
  'lodash',
  'services/errorHandler'
], function(
  _,
  errorhandler
) {

  var viewModel = function(optionsObservable, valueObservable) {

    var self = this;
    self.options = optionsObservable();
    self.value = valueObservable;
    self.resetComboBoxValue = resetComboBoxValue;
    self.setTextFieldValue = setTextFieldValue;
    self.textFieldGotFocus = textFieldGotFocus;
    self.textFieldLostFocus = textFieldLostFocus;

    function resetComboBoxValue() {
      $('#comboBox').val(null);
    }

    function setTextFieldValue() {
      var selection = $('#comboBox').val();
      self.value(selection);
    }

    function textFieldGotFocus() {
      $('#comboBox').addClass('select-editable-input-focus');

    }

    function textFieldLostFocus() {
      $('#comboBox').removeClass('select-editable-input-focus');
    }

  };
  errorhandler.includeIn(viewModel);

  return viewModel;
});

CSS

.select-editable {

  display: block;
  width: 100%;
  height: 31px;
  padding: 6px 12px;
  font-size: 12px;
  line-height: 1.42857143;
  color: #555555;
  background-color: #ffffff;
  background-image: none;
  border: 1px solid #cccccc;
  border-radius: 0px;
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
  -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
  transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;padding: 0;
}


.select-editable select {
  outline:0;
  padding-left: 10px;
  border:none;
  width:100%;
  height: 29px;
}


.select-editable input {
  outline:0;
  position: relative;
  top: -27px;
  margin-left: 10px;
  width:90%;
  height: 25px;
  border:none;
}

.select-editable select:focus {
  outline:0;
  border: 1px solid #66afe9;
  -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
  box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
}




.select-editable input:focus {
  outline:0;
}

.select-editable-input-focus {
outline:0;
  border: 1px solid #66afe9 !important;
  -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
  box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
}

Computed / calculated / virtual / derived columns in PostgreSQL

Well, not sure if this is what You mean but Posgres normally support "dummy" ETL syntax. I created one empty column in table and then needed to fill it by calculated records depending on values in row.

UPDATE table01
SET column03 = column01*column02; /*e.g. for multiplication of 2 values*/
  1. It is so dummy I suspect it is not what You are looking for.
  2. Obviously it is not dynamic, you run it once. But no obstacle to get it into trigger.

How to change dataframe column names in pyspark?

In case you would like to apply a simple transformation on all column names, this code does the trick: (I am replacing all spaces with underscore)

new_column_name_list= list(map(lambda x: x.replace(" ", "_"), df.columns))

df = df.toDF(*new_column_name_list)

Thanks to @user8117731 for toDf trick.

What is the proper way to re-attach detached objects in Hibernate?

Property hibernate.allow_refresh_detached_entity did the trick for me. But it is a general rule, so it is not very suitable if you want to do it only in some cases. I hope it helps.

Tested on Hibernate 5.4.9

SessionFactoryOptionsBuilder

How to sum all values in a column in Jaspersoft iReport Designer?

It is quite easy to solve your task. You should create and use a new variable for summing values of the "Doctor Payment" column.

In your case the variable can be declared like this:

<variable name="total" class="java.lang.Integer" calculation="Sum">
    <variableExpression><![CDATA[$F{payment}]]></variableExpression>
</variable>
  • the Calculation type is Sum;
  • the Reset type is Report;
  • the Variable expression is $F{payment}, where $F{payment} is the name of a field contains sum (Doctor Payment).

The working example.

CSV datasource:

doctor_id,payment
A1,123
B1,223
C2,234
D3,678
D1,343

The template:

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport ...>
    <queryString>
        <![CDATA[]]>
    </queryString>
    <field name="doctor_id" class="java.lang.String"/>
    <field name="payment" class="java.lang.Integer"/>
    <variable name="total" class="java.lang.Integer" calculation="Sum">
        <variableExpression><![CDATA[$F{payment}]]></variableExpression>
    </variable>
    <columnHeader>
        <band height="20" splitType="Stretch">
            <staticText>
                <reportElement x="0" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font size="10" isBold="true" isItalic="true"/>
                </textElement>
                <text><![CDATA[Doctor ID]]></text>
            </staticText>
            <staticText>
                <reportElement x="100" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font size="10" isBold="true" isItalic="true"/>
                </textElement>
                <text><![CDATA[Doctor Payment]]></text>
            </staticText>
        </band>
    </columnHeader>
    <detail>
        <band height="20" splitType="Stretch">
            <textField>
                <reportElement x="0" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement/>
                <textFieldExpression><![CDATA[$F{doctor_id}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="100" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement/>
                <textFieldExpression><![CDATA[$F{payment}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
    <summary>
        <band height="20">
            <staticText>
                <reportElement x="0" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement>
                    <font isBold="true"/>
                </textElement>
                <text><![CDATA[Total]]></text>
            </staticText>
            <textField>
                <reportElement x="100" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement>
                    <font isBold="true" isItalic="true"/>
                </textElement>
                <textFieldExpression><![CDATA[$V{total}]]></textFieldExpression>
            </textField>
        </band>
    </summary>
</jasperReport>

The result will be:

Generated report via iReport's preview


You can find a lot of info in the JasperReports Ultimate Guide.

Why use @PostConstruct?

If your class performs all of its initialization in the constructor, then @PostConstruct is indeed redundant.

However, if your class has its dependencies injected using setter methods, then the class's constructor cannot fully initialize the object, and sometimes some initialization needs to be performed after all the setter methods have been called, hence the use case of @PostConstruct.

How to show code but hide output in RMarkdown?

To hide warnings, you can also do {r, warning=FALSE}

Form/JavaScript not working on IE 11 with error DOM7011

I run into this when click on a html , it is fixed by adding type = "button" attribute.

How to indent HTML tags in Notepad++

I have a solution for you.

Just you need to install a plugin named Indent By Fold.

You can install this by going through Plugins -> Plugin Manager -> Show Plugin Manager. OR Plugins -> Plugins Admin -> chekmark Indent By Fold from list than install

Then just select the list item and all you need is to type the first word then you got it.

you can use this plugin from a plugin in the menu bar.


'Microsoft.ACE.OLEDB.16.0' provider is not registered on the local machine. (System.Data)

After having both installed the Microsoft Access Database Engine 2016 Redistributable and found the x64 bit import export wizard as instructed in the answers above, I had one last hoop to jump through. I got this error 'Executing the query "CREATE TABLE ...." failed with the following error: "Culture is not supported ... 3072 (0x0c00) is an invalid culture identifier."'

The fix was to go to Control Panel -> Clock and Region -> change my "English (Finland)" region to pure Finnish (Finland). Other more traditional cultures such as en-US will work too. I think I first saw this solution here: Fix culture is not supported: 3072 by changing Region Formats

How to include js and CSS in JSP with spring MVC

you need declare resources in dispatcher servelet file.below is two declarations

<mvc:annotation-driven />
<mvc:resources location="/resources/" mapping="/resources/**" />

Closing Applications

What role do they play when exiting an application in C#?

The same as every other application. Basically they get returned to the caller. Irrelvant if ythe start was an iicon double click. Relevant is the call is a batch file that decides whether the app worked on the return code. SO, unless you write a program that needs this, the return dcode IS irrelevant.

But what is the difference?

One comes from environment one from the System.Windows.Forms?.Application. Functionall there should not bbe a lot of difference.

py2exe - generate single executable file

No, it's doesn't give you a single executable in the sense that you only have one file afterwards - but you have a directory which contains everything you need for running your program, including an exe file.

I just wrote this setup.py today. You only need to invoke python setup.py py2exe.

What's the difference between abstraction and encapsulation?

Encapsulation : Suppose I have some confidential documents, now I hide these documents inside a locker so no one can gain access to them, this is encapsulation.

Abstraction : A huge incident took place which was summarised in the newspaper. Now the newspaper only listed the more important details of the actual incident, this is abstraction. Further the headline of the incident highlights on even more specific details in a single line, hence providing higher level of abstraction on the incident. Also highlights of a football/cricket match can be considered as abstraction of the entire match.

Hence encapsulation is hiding of data to protect its integrity and abstraction is highlighting more important details.

In programming terms we can see that a variable may be enclosed is the scope of a class as private hence preventing it from being accessed directly from outside, this is encapsulation. Whereas a a function may be written in a class to swap two numbers. Now the numbers may be swapped in either by either using a temporary variable or through bit manipulation or using arithmetic operation, but the goal of the user is to receive the numbers swapped irrespective of the method used for swapping, this is abstraction.

How to get the unix timestamp in C#

The simple code that I am using:

public static long CurrentTimestamp()
{
   return (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds * 1000);
}

This code is giving unix timestamp, total milliseconds from 1970-01-01 to now.

Multiple file extensions in OpenFileDialog

Based on First answer here is the complete image selection options:

Filter = @"|All Image Files|*.BMP;*.bmp;*.JPG;*.JPEG*.jpg;*.jpeg;*.PNG;*.png;*.GIF;*.gif;*.tif;*.tiff;*.ico;*.ICO
           |PNG|*.PNG;*.png
           |JPEG|*.JPG;*.JPEG*.jpg;*.jpeg
           |Bitmap(.BMP,.bmp)|*.BMP;*.bmp                                    
           |GIF|*.GIF;*.gif
           |TIF|*.tif;*.tiff
           |ICO|*.ico;*.ICO";

Change an image with onclick()

This script helps to change the image on click the text:

<script>
    $(document).ready(function(){
    $('li').click(function(){
    var imgpath = $(this).attr('dir');
    $('#image').html('<img src='+imgpath+'>');
    });
    $('.btn').click(function(){
    $('#thumbs').fadeIn(500);
    $('#image').animate({marginTop:'10px'},200);
    $(this).hide();
    $('#hide').fadeIn('slow');
    });
    $('#hide').click(function(){
    $('#thumbs').fadeOut(500,function (){
    $('#image').animate({marginTop:'50px'},200);
    });
    $(this).hide();
    $('#show').fadeIn('slow');
    });
    });
    </script>


<div class="sandiv">
<h1 style="text-align:center;">The  Human  Body  Parts :</h1>
<div id="thumbs">
<div class="sanl">
<ul>
<li dir="5.png">Human-body-organ-diag-1</li>
<li dir="4.png">Human-body-organ-diag-2</li>
<li dir="3.png">Human-body-organ-diag-3</li>
<li dir="2.png">Human-body-organ-diag-4</li>
<li dir="1.png">Human-body-organ-diag-5</li>
</ul>
</div>
</div>
<div class="man">
<div id="image">
<img src="2.png" width="348" height="375"></div>
</div>
<div id="thumbs">
<div class="sanr" >
<ul>
<li dir="5.png">Human-body-organ-diag-6</li>
<li dir="4.png">Human-body-organ-diag-7</li>
<li dir="3.png">Human-body-organ-diag-8</li>
<li dir="2.png">Human-body-organ-diag-9</li>
<li dir="1.png">Human-body-organ-diag-10</li>
</ul>
</div>
</div>
<h2><a style="color:#333;" href="http://www.sanwebcorner.com/">sanwebcorner.com</a></h2>
</div>

see the demo here