Programs & Examples On #Domain driven design

Domain-driven design (DDD) is an approach to developing software for complex needs by deeply connecting the implementation to an evolving model of the core business concepts. Note that conceptual DDD questions are better to be asked at

Where do I find some good examples for DDD?

ddd-cqrs-sample is also a good resource. Written with Java, Spring and JPA.

Updated link:

What is the difference between DAO and Repository patterns?

The key difference is that a repository handles the access to the aggregate roots in a an aggregate, while DAO handles the access to entities. Therefore, it's common that a repository delegates the actual persistence of the aggregate roots to a DAO. Additionally, as the aggregate root must handle the access of the other entities, then it may need to delegate this access to other DAOs.

What is Domain Driven Design?

Here is another good article that you may check out on Domain Driven Design. if your application is anything serious than college assignment. The basic premise is structure everything around your entities and have a strong domain model. Differentiate between services that provide infrastructure related things (like sending email, persisting data) and services that actually do things that are your core business requirments.

Hope that helps.

Checking if a variable is defined?

As many other examples show you don't actually need a boolean from a method to make logical choices in ruby. It would be a poor form to coerce everything to a boolean unless you actually need a boolean.

But if you absolutely need a boolean. Use !! (bang bang) or "falsy falsy reveals the truth".

› irb
>> a = nil
=> nil
>> defined?(a)
=> "local-variable"
>> defined?(b)
=> nil
>> !!defined?(a)
=> true
>> !!defined?(b)
=> false

Why it doesn't usually pay to coerce:

>> (!!defined?(a) ? "var is defined".colorize(:green) : "var is not defined".colorize(:red)) == (defined?(a) ? "var is defined".colorize(:green) : "var is not defined".colorize(:red))
=> true

Here's an example where it matters because it relies on the implicit coercion of the boolean value to its string representation.

>> puts "var is defined? #{!!defined?(a)} vs #{defined?(a)}"
var is defined? true vs local-variable
=> nil

Get selected value in dropdown list using JavaScript

Plain JavaScript:

var e = document.getElementById("elementId");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;


$("#elementId :selected").text(); // The text content of the selected option
$("#elementId :selected").val(); // The value of the selected option

AngularJS: (

<select ng-model="selectItem" ng-options="item as item.text for item in items">
<p>Text: {{selectItem.text}}</p>
<p>Value: {{selectItem.value}}</p>

// JavaScript
$scope.items = [{
  value: 'item_1_id',
  text: 'Item 1'
}, {
  value: 'item_2_id',
  text: 'Item 2'

Type definition in object literal in TypeScript

In your code:

var obj = {
  myProp: string;

You are actually creating a object literal and assigning the variable string to the property myProp. Although very bad practice this would actually be valid TS code (don't use this!):

var string = 'A string';

var obj = {
  property: string

However, what you want is that the object literal is typed. This can be achieved in various ways:


interface myObj {
    property: string;

var obj: myObj = { property: "My string" };

Type alias:

type myObjType = {
    property: string

var obj: myObjType = { property: "My string" };

Object type literal:

var obj: { property: string; } = { property: "Mystring" };

Merge PDF files with PHP

I created an abstraction layer over FPDI (might accommodate other engines). I published it as a Symfony2 bundle depending on a library, and as the library itself.

The bundle

The Library


public function handlePdfChanges(Document $document, array $formRawData)
    $oldPath = $document->getUploadRootDir($this->kernel) . $document->getOldPath();
    $newTmpPath = $document->getFile()->getRealPath();

    switch ($formRawData['insertOptions']['insertPosition']) {
        case PdfInsertType::POSITION_BEGINNING:
            // prepend 
            $newPdf = $this->pdfManager->insert($oldPath, $newTmpPath);
        case PdfInsertType::POSITION_END: 
            // Append
            $newPdf = $this->pdfManager->append($oldPath, $newTmpPath);
        case PdfInsertType::POSITION_PAGE: 
            // insert at page n: PdfA={p1; p2; p3}, PdfB={pA; pB; pC} 
            // insert(PdfA, PdfB, 2) will render {p1; pA; pB; pC; p2; p3} 
            $newPdf = $this->pdfManager->insert(
                    $oldPath, $newTmpPath, $formRawData['insertOptions']['pageNumber']
        case PdfInsertType::POSITION_REPLACE: 
            // does nothing. overrides old file.
    $pageCount = $newPdf->getPageCount();
    $newPdf->renderFile($mergedPdfPath = "$newTmpPath.merged");
    $document->setFile(new File($mergedPdfPath, true));
    return $pageCount;

Unicode character in PHP string

function unicode_to_textstring($str){

    $rawstr = pack('H*', $str);

    $newstr =  iconv('UTF-16BE', 'UTF-8', $rawstr);
    return $newstr;

$msg = '67714eac99c500200054006f006b0079006f002000530074006100740069006f006e003a0020';

echo unicode_to_textstring($str);

Attach (open) mdf file database with SQL Server Management Studio

Copy the files to the default directory for your other database files. To find out what that is, you can use the sp_helpfile procedure in SSMS. On my machine it is: C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA. By copying the files to this directory, they automatically get permissions applied that will allow the attach to succeed.

Here is a very good explanation :

How to open MDF files .

input[type='text'] CSS selector does not apply to default-type text inputs?

To be compliant with all browsers you should always declare the input type.

Some browsers will assume default type as 'text', but this isn't a good practice.

Displaying a Table in Django from Database

If you want to table do following steps:-

def view_info(request):
    return render(request,'template_name',{'objs':obj})

.html page

 {% for item in objs %}
         <td>{{ item.field1 }}</td>
         <td>{{ item.field2 }}</td>
         <td>{{ item.field3 }}</td>
         <td>{{ item.field4 }}</td>
       {% endfor %}

How can you have SharePoint Link Lists default to opening in a new window?

It is not possible with the default Link List web part, but there are resources describing how to extend Sharepoint server-side to add this functionality.

Share Point Links Open in New Window
Changing Link Lists in Sharepoint 2007

How to hide first section header in UITableView (grouped style)

The following worked for me in with iOS 13.6 and Xcode 11.6 with a UITableViewController that was embedded in a UINavigationController:

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {

No other trickery needed. The override keywords aren't needed when not using a UITableViewController (i.e. when just implemented the UITableViewDelegate methods). Of course if the goal was to hide just the first section's header, then this logic could be wrapped in a conditional as such:

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if section == 0 {
        return nil
    } else {
        // Return some other view...

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    if section == 0 {
        return .zero
    } else {
        // Return some other height...

How does "304 Not Modified" work exactly?

When the browser puts something in its cache, it also stores the Last-Modified or ETag header from the server.

The browser then sends a request with the If-Modified-Since or If-None-Match header, telling the server to send a 304 if the content still has that date or ETag.

The server needs some way of calculating a date-modified or ETag for each version of each resource; this typically comes from the filesystem or a separate database column.

Change navbar color in Twitter Bootstrap

Just add an id to the HTML navbar, such as:

<nav id="navbar-yellow" class="navbar navbar-default navbar-fixed-top" role="navigation">

With this id you can style the navbar color, but also the links and dropdowns

Examples applied to different types of navbars




Red (Cherry)


Here is the CSS

 * Black navbar style
#navbar-black.navbar-default { /* #3C3C3C - #222222 */
    font-size: 14px;
    background-color: rgba(34, 34, 34, 1);
    background: -webkit-linear-gradient(top, rgba(60, 60, 60, 1) 0%, rgba(34, 34, 34, 1) 100%);
    background: linear-gradient(to bottom, rgba(60, 60, 60, 1) 0%, rgba(34, 34, 34, 1) 100%);
    border: 0px;
    border-radius: 0;
#navbar-black.navbar-default .navbar-nav>li>a:hover,
#navbar-black.navbar-default .navbar-nav>li>a:focus,
#navbar-black.navbar-default .navbar-nav>li>ul>li>a:hover,
#navbar-black.navbar-default .navbar-nav>li>ul>li>a:focus,
#navbar-black.navbar-default .navbar-nav>.active>a,
#navbar-black.navbar-default .navbar-nav>.active>a:hover,
#navbar-black.navbar-default .navbar-nav>.active>a:focus {
    color: rgba(255, 255, 255, 1);
    background-color: rgba(0, 0, 0, 1);
    background: -webkit-linear-gradient(top, rgba(0, 0, 0, 1) 0%, rgba(0, 0, 0, 1) 100%);
    background: linear-gradient(to bottom, rgba(0, 0, 0, 1) 0%, rgba(0, 0, 0, 1) 100%);
#sidebar-black, #column-black {
      background-color: #222222;
#navbar-black.navbar-default .navbar-toggle {
    border-color: #222222;
#navbar-black.navbar-default .navbar-toggle:hover,
#navbar-black.navbar-default .navbar-toggle:focus {
    background-color: #3C3C3C;
#navbar-black.navbar-default .navbar-nav>li>a,
#navbar-black.navbar-default .navbar-nav>li>ul>li>a,
#navbar-black.navbar-default .navbar-brand {
    color: #999999;
#navbar-black.navbar-default .navbar-toggle .icon-bar,
#navbar-black.navbar-default .navbar-toggle:hover .icon-bar,
#navbar-black.navbar-default .navbar-toggle:focus .icon-bar {
    background-color: #ffffff;

 * Red navbar style
#navbar-red.navbar-default { /* #990033 - #cc0033 */
    font-size: 14px;
    background-color: rgba(153, 0, 51, 1);
    background: -webkit-linear-gradient(top, rgba(204, 0, 51, 1) 0%, rgba(153, 0, 51, 1) 100%);
    background: linear-gradient(to bottom, rgba(204, 0, 51, 1) 0%, rgba(153, 0, 51, 1) 100%);
    border: 0px;
    border-radius: 0;
#navbar-red.navbar-default .navbar-nav>li>a:hover,
#navbar-red.navbar-default .navbar-nav>li>a:focus,
#navbar-red.navbar-default .navbar-nav>li>ul>li>a:hover,
#navbar-red.navbar-default .navbar-nav>li>ul>li>a:focus,
#navbar-red.navbar-default .navbar-nav>.active>a,
#navbar-red.navbar-default .navbar-nav>.active>a:hover,
#navbar-red.navbar-default .navbar-nav>.active>a:focus {
    color: rgba(51, 51, 51, 1);
    background-color: rgba(255, 255, 255, 1);
    background: -webkit-linear-gradient(top, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 100%);
    background: linear-gradient(to bottom, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 100%);
#sidebar-red, #column-red {
      background-color: #990033;
#navbar-red.navbar-default .navbar-toggle {
    border-color: #990033;
#navbar-red.navbar-default .navbar-toggle:hover,
#navbar-red.navbar-default .navbar-toggle:focus {
    background-color: #cc0033;
#navbar-red.navbar-default .navbar-nav>li>a,
#navbar-red.navbar-default .navbar-nav>li>ul>li>a,
#navbar-red.navbar-default .navbar-brand {
    color: #999999;
#navbar-red.navbar-default .navbar-toggle .icon-bar,
#navbar-red.navbar-default .navbar-toggle:hover .icon-bar,
#navbar-red.navbar-default .navbar-toggle:focus .icon-bar {
    background-color: #ffffff;

 * Darkblue navbar style
#navbar-darkblue.navbar-default { /* #003399 - #0033cc */
    font-size: 14px;
    background-color: rgba(51, 51, 153, 1);
    background: -webkit-linear-gradient(top, rgba(51, 51, 204, 1) 0%, rgba(51, 51, 153, 1) 100%);
    background: linear-gradient(to bottom, rgba(51, 51, 204, 1) 0%, rgba(51, 51, 153, 1) 100%);
    border: 0px;
    border-radius: 0;
#navbar-darkblue.navbar-default .navbar-nav>li>a:hover,
#navbar-darkblue.navbar-default .navbar-nav>li>a:focus,
#navbar-darkblue.navbar-default .navbar-nav>li>ul>li>a:hover,
#navbar-darkblue.navbar-default .navbar-nav>li>ul>li>a:focus,
#navbar-darkblue.navbar-default .navbar-nav>.active>a,
#navbar-darkblue.navbar-default .navbar-nav>.active>a:hover,
#navbar-darkblue.navbar-default .navbar-nav>.active>a:focus {
    color: rgba(51, 51, 51, 1);
    background-color: rgba(255, 255, 255, 1);
    background: -webkit-linear-gradient(top, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 100%);
    background: linear-gradient(to bottom, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 100%);
#sidebar-darkblue, #column-darkblue {
    background-color: #333399;
#navbar-darkblue.navbar-default .navbar-toggle {
    border-color: #333399;
#navbar-darkblue.navbar-default .navbar-toggle:hover,
#navbar-darkblue.navbar-default .navbar-toggle:focus {
    background-color: #3333cc;
#navbar-darkblue.navbar-default .navbar-nav>li>a,
#navbar-darkblue.navbar-default .navbar-nav>li>ul>li>a,
#navbar-darkblue.navbar-default .navbar-brand {
    color: #999999;
#navbar-darkblue.navbar-default .navbar-toggle .icon-bar,
#navbar-darkblue.navbar-default .navbar-toggle:hover .icon-bar,
#navbar-darkblue.navbar-default .navbar-toggle:focus .icon-bar {
    background-color: #ffffff;

 * Darkgreen navbar style
#navbar-darkgreen.navbar-default { /* #006633 - #009933 */
    font-size: 14px;
    background-color: rgba(0, 102, 51, 1);
    background: -webkit-linear-gradient(top, rgba(0, 153, 51, 1) 0%, rgba(0, 102, 51, 1) 100%);
    background: linear-gradient(to bottom, rgba(0, 153, 51, 1) 0%, rgba(0, 102, 51, 1) 100%);
    border: 0px;
    border-radius: 0;
#navbar-darkgreen.navbar-default .navbar-nav>li>a:hover,
#navbar-darkgreen.navbar-default .navbar-nav>li>a:focus,
#navbar-darkgreen.navbar-default .navbar-nav>li>ul>li>a:hover,
#navbar-darkgreen.navbar-default .navbar-nav>li>ul>li>a:focus,
#navbar-darkgreen.navbar-default .navbar-nav>.active>a,
#navbar-darkgreen.navbar-default .navbar-nav>.active>a:hover,
#navbar-darkgreen.navbar-default .navbar-nav>.active>a:focus {
    color: rgba(51, 51, 51, 1);
    background-color: rgba(255, 255, 255, 1);
    background: -webkit-linear-gradient(top, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 100%);
    background: linear-gradient(to bottom, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 100%);
#sidebar-darkgreen, #column-darkgreen {
    background-color: #006633;
#navbar-darkgreen.navbar-default .navbar-toggle {
    border-color: #006633;
#navbar-darkgreen.navbar-default .navbar-toggle:hover,
#navbar-darkgreen.navbar-default .navbar-toggle:focus {
    background-color: #009933;
#navbar-darkgreen.navbar-default .navbar-nav>li>a,
#navbar-darkgreen.navbar-default .navbar-nav>li>ul>li>a,
#navbar-darkgreen.navbar-default .navbar-brand {
    color: #999999;
#navbar-darkgreen.navbar-default .navbar-toggle .icon-bar,
#navbar-darkgreen.navbar-default .navbar-toggle:hover .icon-bar,
#navbar-darkgreen.navbar-default .navbar-toggle:focus .icon-bar {
    background-color: #ffffff;

 * Yellow navbar style
#navbar-yellow.navbar-default { /* #99ff00 - #ccff00 */
    font-size: 14px;
    background-color: rgba(153, 255, 0, 1);
    background: -webkit-linear-gradient(top, rgba(204, 255, 0, 1) 0%, rgba(153, 255, 0, 1) 100%);
    background: linear-gradient(to bottom, rgba(204, 255, 0, 1) 0%, rgba(153, 255, 0, 1) 100%);
    border: 0px;
    border-radius: 0;
#navbar-yellow.navbar-default .navbar-nav>li>a:hover,
#navbar-yellow.navbar-default .navbar-nav>li>a:focus,
#navbar-yellow.navbar-default .navbar-nav>li>ul>li>a:hover,
#navbar-yellow.navbar-default .navbar-nav>li>ul>li>a:focus,
#navbar-yellow.navbar-default .navbar-nav>.active>a,
#navbar-yellow.navbar-default .navbar-nav>.active>a:hover,
#navbar-yellow.navbar-default .navbar-nav>.active>a:focus {
    color: rgba(51, 51, 51, 1);
    background-color: rgba(255, 255, 255, 1);
    background: -webkit-linear-gradient(top, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 100%);
    background: linear-gradient(to bottom, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 100%);
#sidebar-yellow, #column-yellow {
    background-color: #99ff00;
#navbar-yellow.navbar-default .navbar-toggle {
    border-color: #99ff00;
#navbar-yellow.navbar-default .navbar-toggle:hover,
#navbar-yellow.navbar-default .navbar-toggle:focus {
    background-color: #ccff00;
#navbar-yellow.navbar-default .navbar-nav>li>a,
#navbar-yellow.navbar-default .navbar-nav>li>ul>li>a,
#navbar-yellow.navbar-default .navbar-brand {
    color: #999999;
#navbar-yellow.navbar-default .navbar-toggle .icon-bar,
#navbar-yellow.navbar-default .navbar-toggle:hover .icon-bar,
#navbar-yellow.navbar-default .navbar-toggle:focus .icon-bar {
    background-color: #ffffff;

Java Web Service client basic authentication

for Axis2 client this may be helpful

serviceStub = new TestBeanServiceStub("<WEB SERVICE URL>"); // Set your value
HttpTransportProperties.Authenticator basicAuthenticator = new HttpTransportProperties.Authenticator();
List<String> authSchemes = new ArrayList<String>();
basicAuthenticator.setUsername("<UserName>"); // Set your value
basicAuthenticator.setPassword("<Password>"); // Set your value
serviceStub._getServiceClient().getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, basicAuthenticator);
serviceStub._getServiceClient().getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.CHUNKED, "false");

Please explain about insertable=false and updatable=false in reference to the JPA @Column annotation

According to Javax's persistence documentation:

Whether the column is included in SQL UPDATE statements generated by the persistence provider.

It would be best to understand from the official documentation here.

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path

The first part of your question is a duplicate of Why do I get a JsonReaderException with this code?, but the most relevant part from that (my) answer is this:

[A] JObject isn't the elementary base type of everything in, but JToken is. So even though you could say,

object i = new int[0];

in C#, you can't say,

JObject i = JObject.Parse("[0, 0, 0]");


What you want is JArray.Parse, which will accept the array you're passing it (denoted by the opening [ in your API response). This is what the "StartArray" in the error message is telling you.

As for what happened when you used JArray, you're using arr instead of obj:

var rcvdData = JsonConvert.DeserializeObject<LocationData>(arr /* <-- Here */.ToString(), settings);

Swap that, and I believe it should work.

Although I'd be tempted to deserialize arr directly as an IEnumerable<LocationData>, which would save some code and effort of looping through the array. If you aren't going to use the parsed version separately, it's best to avoid it.

Increase heap size in Java

You can increase the Heap Size by passing JVM parameters -Xms and -Xmx like below:

For Jar Files:

java -jar -Xms4096M -Xmx6144M jarFilePath.jar

For Java Files:

 java -Xms4096M -Xmx6144M ClassName

The above parameters increase the InitialHeapSize (-Xms) to 4GB (4096 MB) and MaxHeapSize(-Xmx) to 6GB (6144 MB).

But, the Young Generation Heap Size will remain same and the additional HeapSize will be added to the Old Generation Heap Size. To equalize the size of Young Gen Heap and Old Gen Heap, use -XX:NewRatio=1 -XX:-UseAdaptiveSizePolicy params.

java -jar -Xms4096M -Xmx6144M -XX:NewRatio=1 -XX:-UseAdaptiveSizePolicy pathToJarFile.jar

-XX:NewRatio = Old Gen Heap Size : Young Gen HeapSize (You can play with this ratio to get your desired ratio).

Download files in laravel using Response::download

While using laravel 5 use this code as you don`t need headers.

return response()->download($pathToFile); .

If you are using Fileentry you can use below function for downloading.

// download file
public function download($fileId){  
    $entry = Fileentry::where('file_id', '=', $fileId)->firstOrFail();
    return response()->download($pathToFile);           

Converting a SimpleXML Object to an Array

Just (array) is missing in your code before the simplexml object:


$xml   = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);

$array = json_decode(json_encode((array)$xml), TRUE);

How to get rid of punctuation using NLTK tokenizer?

Just adding to the solution by @rmalouf, this will not include any numbers because \w+ is equivalent to [a-zA-Z0-9_]

from nltk.tokenize import RegexpTokenizer
tokenizer = RegexpTokenizer(r'[a-zA-Z]')
tokenizer.tokenize('Eighty-seven miles to go, yet.  Onward!')

jQuery change method on input type="file"

is the ajax uploader refreshing your input element? if so you should consider using .live() method.

 $('#imageFile').live('change', function(){ uploadFile(); });


from jQuery 1.7+ you should use now .on()

 $(parent_element_selector_here or document ).on('change','#imageFile' , function(){ uploadFile(); });

Python float to int conversion

2.51 * 100 = 250.999999999997

The int() function simply truncates the number at the decimal point, giving 250. Use


to get 251 as an integer. In general, floating point numbers cannot be represented exactly. One should therefore be careful of round-off errors. As mentioned, this is not a Python-specific problem. It's a recurring problem in all computer languages.

Find unused npm packages in package.json

As other answer mentioned depcheck is good for check unused dependecies in your porject. Use npm outdated command to check the outdated library.

enter image description here

How can I get current date in Android?

You can use the SimpleDateFormat class for formatting date in your desired format.

Just check this link where you get an idea for your example.

For example:

String dateStr = "04/05/2010"; 
SimpleDateFormat curFormater = new SimpleDateFormat("dd/MM/yyyy"); 
Date dateObj = curFormater.parse(dateStr); 
SimpleDateFormat postFormater = new SimpleDateFormat("MMMM dd, yyyy"); 
String newDateStr = postFormater.format(dateObj); 


The detailed example is here, I would suggest you go through this example and understand the concept of SimpleDateFormat class.

Final Solution:

Date c = Calendar.getInstance().getTime();
System.out.println("Current time => " + c);

SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault());
String formattedDate = df.format(c);

Merging arrays with the same keys

Try this:

$array_one = ['ratio_type'];
$array_two = ['ratio_type', 'ratio_type'];
$array_three = ['ratio_type'];
$array_four = ['ratio_type'];
$array_five = ['ratio_type', 'ratio_type', 'ratio_type'];
$array_six = ['ratio_type'];
$array_seven = ['ratio_type'];
$array_eight = ['ratio_type'];

$all_array_elements = array_merge_recursive(

foreach ($all_array_elements as $key => $value) {
    echo "[$key]" . ' - ' . $value . PHP_EOL;

// OR

Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view

This is the way it worked for me:

$.post("/Controller/Action", $("#form").serialize(), function(json) {       
        // handle response
}, "json");

public ActionResult TV(MyModel id)
    return Json(new { success = true });

How to make an introduction page with Doxygen

I tried all the above with v 1.8.13 to no avail. What worked for me (on macOS) was to use the doxywizard->Expert tag to fill the USE_MD_FILE_AS_MAINPAGE setting.

It made the following changes to my Doxyfile:

INPUT                  = ../ \
                         ../sdk/include \

Note the line termination for INPUT, I had just been using space as a separator as specified in the documentation. AFAICT this is the only change between the not-working and working version of the Doxyfile.

List of installed gems?

Here's a really nice one-liner to print all the Gems along with their version, homepage, and description:

Gem::Specification.sort{|a,b| <=>}.map {|a| puts "#{} (#{a.version})"; puts "-" * 50; puts a.homepage; puts a.description; puts "\n\n"};nil

How do I get and set Environment variables in C#?

I could be able to update the environment variable by using the following

string EnvPath = System.Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine) ?? string.Empty;
if (!string.IsNullOrEmpty(EnvPath) && !EnvPath .EndsWith(";"))
    EnvPath = EnvPath + ';';
EnvPath = EnvPath + @"C:\Test";
Environment.SetEnvironmentVariable("PATH", EnvPath , EnvironmentVariableTarget.Machine);

How to throw a C++ exception

Though this question is rather old and has already been answered, I just want to add a note on how to do proper exception handling in C++11:

Use std::nested_exception and std::throw_with_nested

It is described on StackOverflow here and here, how you can get a backtrace on your exceptions inside your code without need for a debugger or cumbersome logging, by simply writing a proper exception handler which will rethrow nested exceptions.

Since you can do this with any derived exception class, you can add a lot of information to such a backtrace! You may also take a look at my MWE on GitHub, where a backtrace would look something like this:

Library API: Exception caught in function 'api_function'
~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"

Hibernate Criteria Restrictions AND / OR combination

think works

Criteria criteria = getSession().createCriteria(clazz); 
Criterion rest1= Restrictions.and(Restrictions.eq(A, "X"), 
 "B", Arrays.asList("X",Y)));
Criterion rest2= Restrictions.and(Restrictions.eq(A, "Y"), 
           Restrictions.eq(B, "Z"));
criteria.add(Restrictions.or(rest1, rest2));

How does one parse XML files?

Use XmlTextReader, XmlReader, XmlNodeReader and the System.Xml.XPath namespace. And (XPathNavigator, XPathDocument, XPathExpression, XPathnodeIterator).

Usually XPath makes reading XML easier, which is what you might be looking for.

Shell Script — Get all files modified after <date>

This should show all files modified within the last 7 days.

find . -type f -mtime -7 -print

Pipe that into tar/zip, and you should be good.

Client on Node.js: Uncaught ReferenceError: require is not defined

ES6: In HTML, include the main JavaScript file using attribute type="module" (browser support):

<script type="module" src="script.js"></script>

And in the script.js file, include another file like this:

import { hello } from './module.js';
// alert(hello());

Inside the included file (module.js), you must export the function/class that you will import:

export function hello() {
    return "Hello World";

A working example is here. More information is here.

How can I get date in application run by node.js?

To create a new Date object in node.js, or JavaScript in general, just call it’s initializer

var d = new Date();

var d = new Date(dateString);

var d = new Date(jsonDate);

var d = new Date(year, month, day);

var d = new Date(year, month, day, hour, minute, second, millisecond);

Remember that Date objects can only be instantiated by calling Date or using it as a constructor; unlike other JavaScript object types, Date objects have no literal syntax

Not connecting to SQL Server over VPN

When connecting to VPN every message goes through VPN server and it could not be forwarding your messages to that port SQL server is working on.


disable VPN settings->Properties->TCP/IP properties->Advanced->Use default gateway on remote network.

This way you will first try to connect local IP of SQL server and only then use VPN server to forward you

httpd-xampp.conf: How to allow access to an external IP besides localhost?

Add below code in to file d:\xampp\apache\conf\extra\httpd-xampp.conf:

<IfModule alias_module>
    Alias / "d:/xampp/my/folder/"
    <Directory "d:/xampp/my/folder">
        AllowOverride AuthConfig Limit
        Order allow,deny
        Allow from all
        Require all granted

Above config can access from

Note: someone suggest that replace from Require local to Require all granted but not work for me

<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
    # Require local
    Require all granted
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var

Bootstrap - Removing padding or margin when screen size is smaller

Heres what I do for Bootstrap 3/4

Use container-fluid instead of container.

Add this to my CSS

@media (min-width: 1400px) {
        max-width: 1400px;

This removes margins below 1400px width screen

top nav bar blocking top content of the page

a much more handy solution for your reference, it works perfect in all of my projects:

change your first 'div' from

<div class='navbar navbar-fixed-top'>


<div class="navbar navbar-default navbar-static-top">

IOError: [Errno 13] Permission denied

I had a similar problem. I was attempting to have a file written every time a user visits a website.

The problem ended up being twofold.

1: the permissions were not set correctly

2: I attempted to use
f = open(r"newfile.txt","w+") (Wrong)

After changing the file to 777 (all users can read/write)
chmod 777 /var/www/path/to/file
and changing the path to an absolute path, my problem was solved
f = open(r"/var/www/path/to/file/newfile.txt","w+") (Right)

How to access random item in list?

Why not:

public static T GetRandom<T>(this IEnumerable<T> list)
   return list.ElementAt(new Random(DateTime.Now.Millisecond).Next(list.Count()));

How do I negate a condition in PowerShell?

You almost had it with Not. It should be:

if (-Not (Test-Path C:\Code)) {
    write "it doesn't exist!"

You can also use !: if (!(Test-Path C:\Code)){}

Just for fun, you could also use bitwise exclusive or, though it's not the most readable/understandable method.

if ((test-path C:\code) -bxor 1) {write "it doesn't exist!"}

Python conversion between coordinates

If your coordinates are stored as complex numbers you can use cmath

How to output an Excel *.xls file from classic ASP

MS made a COM library called Office Web Components to do this. MSOWC.dll needs to be registered on the server. It can create and manipulate office document files.

How To Use the Spreadsheet Web Component with Visual Basic

Working with the Office Web Components

How to access local files of the filesystem in the Android emulator?

In Android Studio 3.5.3, the Device File Explorer can be found in View -> Tool Windows.

It can also be opened using the vertical tabs on the right-hand side of the main window.

PHP cURL, extract an XML response

$sXML = download_page('');
// Comment This    
// $oXML = new SimpleXMLElement($sXML);
// foreach($oXML->entry as $oEntry){
//  echo $oEntry->title . "\n";
// }
// Use json encode
$xml = simplexml_load_string($sXML);
$json = json_encode($xml);
$arr = json_decode($json,true);

How can I use xargs to copy files that have spaces and quotes in their names?

If you are using Bash, you can convert stdout to an array of lines by mapfile:

find . | grep "FooBar" | (mapfile -t; cp "${MAPFILE[@]}" ~/foobar)

The benefits are:

  • It's built-in, so it's faster.
  • Execute the command with all file names in one time, so it's faster.
  • You can append other arguments to the file names. For cp, you can also:

    find . -name '*FooBar*' -exec cp -t ~/foobar -- {} +

    however, some commands don't have such feature.

The disadvantages:

  • Maybe not scale well if there are too many file names. (The limit? I don't know, but I had tested with 10 MB list file which includes 10000+ file names with no problem, under Debian)

Well... who knows if Bash is available on OS X?

Two div blocks on same line

You can use a HTML table:

<div id="bloc1">your content</div>
<div id="bloc2">your content</div>

How To Remove Outline Border From Input Button

It's also good note that outline: none can be applied to both <button> tags and input[type=button] to remove the browser-applied border on click.

Exiting from python Command Line

This message is the __str__ attribute of exit

look at these examples :


>>> print exit
Use exit() or Ctrl-D (i.e. EOF) to exit


>>> exit.__str__()
'Use exit() or Ctrl-D (i.e. EOF) to exit'


>>> getattr(exit, '__str__')()
'Use exit() or Ctrl-D (i.e. EOF) to exit'

convert a list of objects from one type to another using lambda expression

for similar type class.

List<targetlist> targetlst= JsonConvert.DeserializeObject<List<targetlist>>(JsonConvert.SerializeObject(<List<baselist>));

Why can't a text column have a default value in MySQL?

As the main question:

Anybody know why this is not allowed?

is still not answered, I did a quick search and found a relatively new addition from a MySQL developer at MySQL Bugs:

[17 Mar 2017 15:11] Ståle Deraas

Posted by developer:

This is indeed a valid feature request, and at first glance it might seem trivial to add. But TEXT/BLOBS values are not stored directly in the record buffer used for reading/updating tables. So it is a bit more complex to assign default values for them.

This is no definite answer, but at least a starting point for the why question.

In the mean time, I'll just code around it and either make the column nullable or explicitly assign a (default '') value for each insert from the application code...

Xcode Objective-C | iOS: delay function / NSTimer help?

int64_t delayInSeconds = 0.6;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
     do something to the button(s)

How to concatenate two strings in C++?

First of all, don't use char* or char[N]. Use std::string, then everything else becomes so easy!


std::string s = "Hello";
std::string greet = s + " World"; //concatenation easy!

Easy, isn't it?

Now if you need char const * for some reason, such as when you want to pass to some function, then you can do this:

some_c_api(s.c_str(), s.size()); 

assuming this function is declared as:

some_c_api(char const *input, size_t length);

Explore std::string yourself starting from here:

Hope that helps.

How to programmatically set the layout_align_parent_right attribute of a Button in Relative Layout?

  1. you need to create and id for the buttons you need to refference: btn1.setId(1);
  2. you can use the params variable to add parameters to your layout, i think the method is addRule(), check out the android java docs for this LayoutParams object.

php codeigniter count rows

This is what is did that solved the same problem. I solved it by creating a function that returns the query result thus:

function getUsers(){
$query = $this->db->get('users');
return $query->result();

//The above code can go in the user_model or whatever your model is.

This allows me to use one function for the result and number of returned rows.

Use this code below in your contoller where you need the count as well as the result array().

//This gives you the user count using the count function which returns and integer of the exact rows returned from the query.
$this->data['user_count'] = count($this->user_model->getUsers());

//This gives you the returned result array.
$this->data['users'] = $this->user_model->getUsers();

I hope this helps.

SQL- Ignore case while searching for a string

Use something like this -




Android: java.lang.SecurityException: Permission Denial: start Intent

You have to add android:exported="true" in the manifest file in the activity you are trying to start.

From the android:exported documentation:

Whether or not the activity can be launched by components of other applications — "true" if it can be, and "false" if not. If "false", the activity can be launched only by components of the same application or applications with the same user ID.

The default value depends on whether the activity contains intent filters. The absence of any filters means that the activity can be invoked only by specifying its exact class name. This implies that the activity is intended only for application-internal use (since others would not know the class name). So in this case, the default value is "false". On the other hand, the presence of at least one filter implies that the activity is intended for external use, so the default value is "true".

This attribute is not the only way to limit an activity's exposure to other applications. You can also use a permission to limit the external entities that can invoke the activity (see the permission attribute).

String, StringBuffer, and StringBuilder

Difference between String and the other two classes is that String is immutable and the other two are mutable classes.

But why we have two classes for same purpose?

Reason is that StringBuffer is Thread safe and StringBuilder is not. StringBuilder is a new class on StringBuffer Api and it was introduced in JDK5 and is always recommended if you are working in a Single threaded environment as it is much Faster

For complete Details you can read

Pandas get the most frequent values of a column

Simply use this..


The functions for frequencies largest and smallest are:

  • nlargest() for mostfrequent 'n' values
  • nsmallest() for least frequent 'n' values

Display a decimal in scientific notation

My decimals are too big for %E so I had to improvize:

def format_decimal(x, prec=2):
    tup = x.as_tuple()
    digits = list(tup.digits[:prec + 1])
    sign = '-' if tup.sign else ''
    dec = ''.join(str(i) for i in digits[1:])
    exp = x.adjusted()
    return '{sign}{int}.{dec}e{exp}'.format(sign=sign, int=digits[0], dec=dec, exp=exp)

Here's an example usage:

>>> n = decimal.Decimal(4.3) ** 12314
>>> print format_decimal(n)
>>> print '%e' % n

Return Max Value of range that is determined by an Index & Match lookup

You can easily change the match-type to 1 when you are looking for the greatest value or to -1 when looking for the smallest value.

Store boolean value in SQLite

SQLite Boolean Datatype:
SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true).

You can convert boolean to int in this way:

int flag = (boolValue)? 1 : 0;

You can convert int back to boolean as follows:

 // Select COLUMN_NAME  values from db. 
 // This will be integer value, you can convert this int value back to Boolean as follows
Boolean flag2 = (intValue == 1)? true : false;

If you want to explore sqlite, here is a tutorial.
I have given one answer here. It is working for them.

Get the new record primary key ID from MySQL insert query?

BEWARE !! of LAST_INSERT_ID() if trying to return this primary key value within PHP.

I know this thread is not tagged PHP, but for anybody who came across this answer looking to return a MySQL insert id from a PHP scripted insert using standard mysql_query calls - it wont work and is not obvious without capturing SQL errors.

The newer mysqli supports multiple queries - which LAST_INSERT_ID() actually is a second query from the original.

IMO a separate SELECT to identify the last primary key is safer than the optional mysql_insert_id() function returning the AUTO_INCREMENT ID generated from the previous INSERT operation.

How do you round a double in Dart to a given degree of precision AFTER the decimal point?

num.toStringAsFixed() rounds. This one turns you num (n) into a string with the number of decimals you want (2), and then parses it back to your num in one sweet line of code:

n = num.parse(n.toStringAsFixed(2));

How to resolve Error : Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation

You also encounter this if you run an Application on a Scheduled Task in Non-Interactive mode.

As soon as you show a Dialog it throws the error:

Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application.

You can see its a MessageBox causing the problem in the stack trace:

at System.Windows.Forms.MessageBox.ShowCore(IWin32Window owner, String text, String caption, MessageBoxButtons buttons, MessageBoxIcon icon,  MessageBoxDefaultButton defaultButton, MessageBoxOptions options, Boolean showHelp)  


If you're running your app on a Scheduled Task send an email instead of showing a Dialog.

DOS: find a string, if found then run another script

As the answer is marked correct then it's a Windows Dos prompt script and this will work too:

find "string" status.txt >nul && call "my batch file.bat"

Carriage return in C?

From 5.2.2/2 (character display semantics) :

\b (backspace) Moves the active position to the previous position on the current line. If the active position is at the initial position of a line, the behavior of the display device is unspecified.

\n (new line) Moves the active position to the initial position of the next line.

\r (carriage return) Moves the active position to the initial position of the current line.

Here, your code produces :

  • <new_line>ab
  • \b : back one character
  • write si : overrides the b with s (producing asi on the second line)
  • \r : back at the beginning of the current line
  • write ha : overrides the first two characters (producing hai on the second line)

In the end, the output is :


How do I escape special characters in MySQL?

For testing how to insert the double quotes in MySQL using the terminal, you can use the following way:

TableName(Name,DString) - > Schema
insert into TableName values("Name","My QQDoubleQuotedStringQQ")

After inserting the value you can update the value in the database with double quotes or single quotes:

update table TableName replace(Dstring, "QQ", "\"")

PHP cURL vs file_get_contents

This is old topic but on my last test on one my API, cURL is faster and more stable. Sometimes file_get_contents on larger request need over 5 seconds when cURL need only from 1.4 to 1.9 seconds what is double faster.

I need to add one note on this that I just send GET and recive JSON content. If you setup cURL properly, you will have a great response. Just "tell" to cURL what you need to send and what you need to recive and that's it.

On your exampe I would like to do this setup:

$ch =  curl_init('');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_TIMEOUT, 3);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
$result = curl_exec($ch);

This request will return data in 0.10 second max

Daylight saving time and time zone best practices

Make clear architectural separation of concerns - to know exactly which tier interacts with users, and has to change date-time for/from canonical representation (UTC). Non-UTC date-time is presentation (follows users local timezone), UTC time is model (remains unique for back-end and mid tiers).

Also, decide what's your actual audience, what you don't have to serve and where do you draw the line. Don't touch exotic calendars unless you actually have important customers there and then consider separate user-facing server(s) just for that region.

If you can acquire and maintain user's location, use location for systematic date-time conversion (say .NET culture or a SQL table) but provide a way for end-user to choose overrides if date-time is critical for your users.

If there are historical audit obligations involved (like telling exactly when Jo in AZ paid a bill 2 yrs ago in September) then keep both UTC and local time for the record (your conversion tables will change in a course of time).

Define the time referential time zone for data that comes in bulk - like files, web services etc. Say East Coast company has data center in CA - you need to ask and know what they use as a standard instead of assuming one or the other.

Don't trust time-zone offsets embedded in textual representation of the date-time and don't accept to parse and follow them. Instead always request that time zone and/or reference zone have to be explicitly defined. You can easily receive time with PST offset but the time is actually EST since that's the client's reference time and records were just exported at a server which is in PST.

The I/O operation has been aborted because of either a thread exit or an application request

I had this problem. I think that it was caused by the socket getting opened and no data arriving within a short time after the open. I was reading from a serial to ethernet box called a Devicemaster. I changed the Devicemaster port setting from "connect always" to "connect on data" and the problem disappeared. I have great respect for Hans Passant but I do not agree that this is an error code that you can easily solve by scrutinizing code.

What is a Python egg?

Note: Egg packaging has been superseded by Wheel packaging.

Same concept as a .jar file in Java, it is a .zip file with some metadata files renamed .egg, for distributing code as bundles.

Specifically: The Internal Structure of Python Eggs

A "Python egg" is a logical structure embodying the release of a specific version of a Python project, comprising its code, resources, and metadata. There are multiple formats that can be used to physically encode a Python egg, and others can be developed. However, a key principle of Python eggs is that they should be discoverable and importable. That is, it should be possible for a Python application to easily and efficiently find out what eggs are present on a system, and to ensure that the desired eggs' contents are importable.

The .egg format is well-suited to distribution and the easy uninstallation or upgrades of code, since the project is essentially self-contained within a single directory or file, unmingled with any other projects' code or resources. It also makes it possible to have multiple versions of a project simultaneously installed, such that individual programs can select the versions they wish to use.

Convert string to number field

Within Crystal, you can do it by creating a formula that uses the ToNumber function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:

If NumericText ({field}) then ToNumber ({field}) else 0

Alternatively, you might find it easier to convert the field's datatype within the query used in the report.

parsing a tab-separated file in Python

You can use the csv module to parse tab seperated value files easily.

import csv

with open("tab-separated-values") as tsv:
    for line in csv.reader(tsv, dialect="excel-tab"): #You can also use delimiter="\t" rather than giving a dialect.

Where line is a list of the values on the current row for each iteration.

Edit: As suggested below, if you want to read by column, and not by row, then the best thing to do is use the zip() builtin:

with open("tab-separated-values") as tsv:
    for column in zip(*[line for line in csv.reader(tsv, dialect="excel-tab")]):

Check Whether a User Exists

I like this nice one line solution

getent passwd username > /dev/null 2&>1 && echo yes || echo no

and in script:


if [ "$1" != "" ]; then
        getent passwd $1 > /dev/null 2&>1 && (echo yes; exit 0) || (echo no; exit 2)
        echo "missing username"
        exit -1


[mrfish@yoda ~]$ ./ root
[mrfish@yoda ~]$ echo $?

[mrfish@yoda ~]$ ./
missing username
[mrfish@yoda ~]$ echo $?

[mrfish@yoda ~]$ ./ aaa
[mrfish@indegy ~]$ echo $?

error CS0234: The type or namespace name 'Script' does not exist in the namespace 'System.Web'

Since JsonSerializer is deprecated in .Net 4.0+ I used to solve this issue.

NuGet- > Install-Package Newtonsoft.Json

How to test if a string contains one of the substrings in a list, in pandas?

You can use str.contains alone with a regex pattern using OR (|):


Or you could add the series to a dataframe then use str.contains:

df = pd.DataFrame(s)


0 cat
1 hat
2 dog
3 fog 

Maven: add a dependency to a jar by relative path

One small addition to the solution posted by Pascal

When I followed this route, I got an error in maven while installing ojdbc jar.

[INFO] --- maven-install-plugin:2.5.1:install-file (default-cli) @ validator ---
[INFO] pom.xml not found in ojdbc14.jar

After adding -DpomFile, the problem was resolved.

$ mvn install:install-file -Dfile=./lib/ojdbc14.jar -DgroupId=ojdbc \
   -DartifactId=ojdbc -Dversion=14 -Dpackaging=jar -DlocalRepositoryPath=./repo \

How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?

Another approach is to use @ExceptionHandler with @ControllerAdvice to centralize all your handlers in the same class, if not you must put the handler methods in every controller you want to manage an exception.

Your handler class:

public class MyExceptionHandler extends ResponseEntityExceptionHandler {

  public ResponseEntity<MyError> handleException(MyBadRequestException e) {
    return ResponseEntity
        .body(new MyError(HttpStatus.BAD_REQUEST, e.getDescription()));

Your custom exception:

public class MyBadRequestException extends RuntimeException {

  private String description;

  public MyBadRequestException(String description) {
    this.description = description;

  public String getDescription() {
    return this.description;

Now you can throw exceptions from any of your controllers, and you can define other handlers inside you advice class.

Internal vs. Private Access Modifiers

private - encapsulations in class/scope/struct ect'.

internal - encapsulation in assemblies.

base_url() function not working in codeigniter

I encountered with this issue spending couple of hours, however solved it in different ways. You can see, I have just created an assets folder outside application folder. Finally I linked my style sheet in the page header section. Folder structure are below images.

enter image description here enter image description here

Before action this you should include url helper file either in your controller class method/__constructor files or by in autoload.php file. Also change $config['base_url'] = 'http://yoursiteurl'; in the following file application/config/config.php

If you include it in controller class method/__constructor then it look like

public function __construct()

or If you load in autoload file then it would looks like

$autoload['helper'] = array('url'); 

Finally, add your stylesheet file. You can link a style sheet by different ways, include it in your inside section

-><link rel="stylesheet" href="<?php echo base_url();?>assets/css/style.css" type="text/css" />

-> or


    $main = array(
    'href'       => 'assets/css/style.css',
    'rel'        => 'stylesheet',
    'type'       => 'text/css',
    'title'      => 'main stylesheet',
    'media'      => 'all',
    'index_page' => true

echo link_tag($main); ?>

-> or

finally I get more reliable code cleaner concept. Just create a config file, named styles.php in you application/config/styles.php folder. Then add some links in styles.php file looks like below

 $config['style'] = array(
    'main' => array(
        'href'       => 'assets/css/style.css',
        'rel'        => 'stylesheet',
        'type'       => 'text/css',
        'title'      => 'main stylesheet',
        'media'      => 'all',
        'index_page' => true


call/add this config to your controller class method looks like below

$data['style'] = $this->config->config['style'];

Pass this data in your header template looks like below.

$this->load->view('templates/header', $data);

And finally add or link your css file looks like below.

<?php echo link_tag($style['main']); ?>

Convert an array to string

You probably want something like this overload of String.Join:

String.Join<T> Method (String, IEnumerable<T>)


In your example, you'd use

String.Join("", Client);

Check if string ends with certain pattern

You can test if a string ends with work followed by one character like this:


If the trailing character is optional you can use this:


To make sure the last character is a period . or a slash / you can use this:


To test for work followed by an optional period or slash you can use this:


To test for work surrounded by periods or slashes, you could do this:


If the tokens before and after work must match each other, you could do this:


Your exact requirement isn't precisely defined, but I think it would be something like this:


In other words:

  • zero or more characters
  • followed by work
  • followed by zero or one , . OR /
  • followed by the end of the input

Explanation of various regex items:

.               --  any character
*               --  zero or more of the preceeding expression
$               --  the end of the line/input
?               --  zero or one of the preceeding expression
[./,]           --  either a period or a slash or a comma
[abc]           --  matches a, b, or c
[abc]*          --  zero or more of (a, b, or c)
[abc]?          --  zero or one of (a, b, or c)

enclosing a pattern in parentheses is called "grouping"

([abc])blah\\1  --  a, b, or c followed by blah followed by "the first group"

Here's a test harness to play with:

class TestStuff {

    public static void main (String[] args) {

        String[] testStrings = { 

        for (String t : testStrings) {
            print("word: " + t + "  --->  " + matchesIt(t));

    public static boolean matchesIt(String s) {
        return s.matches(".*([./,])work\\1?$");

    public static void print(Object o) {
        String s = (o == null) ? "null" : o.toString();


How to change font of UIButton with Swift

Dot-notation is awesome (swift 4.2)

btn.titleLabel?.font = .systemFont(ofSize: 12)

Change language for bootstrap DateTimePicker

If you use moment.js the you need to load moment-with-locales.min.js not moment.min.js. Otherwise, your locale: 'ru' will not work.

How to bind Dataset to DataGridView in windows application

following will show one table of dataset

DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = ds; // dataset
DataGridView1.DataMember = "TableName"; // table name you need to show

if you want to show multiple tables, you need to create one datatable or custom object collection out of all tables.

if two tables with same table schema

dtAll = dtOne.Copy(); // dtOne = ds.Tables[0]
dtAll.Merge(dtTwo); // dtTwo = dtOne = ds.Tables[1]

DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = dtAll ; // datatable

sample code to mode all tables

DataTable dtAll = ds.Tables[0].Copy();
for (var i = 1; i < ds.Tables.Count; i++)
DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = dtAll ;

Where can I read the Console output in Visual Studio 2015

What may be happening is that your console is closing before you get a chance to see the output. I would add Console.ReadLine(); after your Console.WriteLine("Hello World"); so your code would look something like this:

static void Main(string[] args)
        Console.WriteLine("Hello World");


This way, the console will display "Hello World" and a blinking cursor underneath. The Console.ReadLine(); is the key here, the program waits for the users input before closing the console window.

Ruby: Easiest Way to Filter Hash Keys?

This is a one line to solve the complete original question: { |k,_| k[/choice/]}.values.join('\t')

But most the solutions above are solving a case where you need to know the keys ahead of time, using slice or simple regexp.

Here is another approach that works for simple and more complex use cases, that is swappable at runtime

data = {}
matcher = ->(key,value) { COMPLEX LOGIC HERE }

Now not only this allows for more complex logic on matching the keys or the values, but it is also easier to test, and you can swap the matching logic at runtime.

Ex to solve the original issue:

def some_method(hash, matcher)'\t')

params = { :irrelevant => "A String",
           :choice1 => "Oh look, another one",
           :choice2 => "Even more strings",
           :choice3 => "But wait",
           :irrelevant2 => "The last string" }

some_method(params, ->(k,_) { k[/choice/]}) # => "Oh look, another one\\tEven more strings\\tBut wait"
some_method(params, ->(_,v) { v[/string/]}) # => "Even more strings\\tThe last string"

Get Country of IP Address with PHP

You can try the services of They provide a JSON or JSONP-callback solution.


    $json = file_get_contents("");
    $data = json_decode($json);

    print $data->country_code . "<br>";
    print $data->country_name . "<br>";
    print $data->state . "<br>";
    print $data->city . "<br>";
    print $data->postal . "<br>";
    print $data->latitude . "<br>";
    print $data->longitude . "<br>";
    print $data->IPv4 . "<br>";


how to git commit a whole folder?

You don't "commit the folder" - you add the folder, as you have done, and then simply commit all changes. The command should be:

git add foldername
git commit -m "commit operation"

Not Equal to This OR That in Lua

x ~= 0 or 1 is the same as ((x ~= 0) or 1)

x ~=(0 or 1) is the same as (x ~= 0).

try something like this instead.

function isNot0Or1(x)
    return (x ~= 0 and x ~= 1)

print( isNot0Or1(-1) == true )
print( isNot0Or1(0) == false )
print( isNot0Or1(1) == false )

What does 'foo' really mean?

See: RFC 3092: Etymology of "Foo", D. Eastlake 3rd et al.

Quoting only the relevant definitions from that RFC for brevity:

  1. Used very generally as a sample name for absolutely anything, esp. programs and files (esp. scratch files).

  2. First on the standard list of metasyntactic variables used in syntax examples (bar, baz, qux, quux, corge, grault, garply, waldo, fred, plugh, xyzzy, thud). [JARGON]

package javax.servlet.http does not exist


javac -cp .;"C:\Users\User Name\Tomcat\apache-tomcat-7.0.108\lib\servlet-api.jar"

using windows if there are spaces in your class path.

Can I do Model->where('id', ARRAY) multiple where conditions?

You could use one of the below solutions:

$items = Item::whereIn('id', [1,2,..])->get();


$items = DB::table('items')->whereIn('id',[1,2,..])->get();

How to get file name when user select a file via <input type="file" />?

You can get the file name, but you cannot get the full client file-system path.

Try to access to the value attribute of your file input on the change event.

Most browsers will give you only the file name, but there are exceptions like IE8 which will give you a fake path like: "C:\fakepath\myfile.ext" and older versions (IE <= 6) which actually will give you the full client file-system path (due its lack of security).

document.getElementById('fileInput').onchange = function () {
  alert('Selected file: ' + this.value);

HTML5: Slider with two inputs possible?

Coming late, but noUiSlider avoids having a jQuery-ui dependency, which the accepted answer does not. Its only "caveat" is IE support is for IE9 and newer, if legacy IE is a deal breaker for you.

It's also free, open source and can be used in commercial projects without restrictions.

Installation: Download noUiSlider, extract the CSS and JS file somewhere in your site file system, and then link to the CSS from head and to JS from body:

<!-- In <head> -->
<link href="nouislider.min.css" rel="stylesheet">

<!-- In <body> -->
<script src="nouislider.min.js"></script>

Example usage: Creates a slider which goes from 0 to 100, and starts set to 20-80.


<div id="slider">


var slider = document.getElementById('slider');

noUiSlider.create(slider, {
    start: [20, 80],
    connect: true,
    range: {
        'min': 0,
        'max': 100

Convert ndarray from float64 to integer

There's also a really useful discussion about converting the array in place, In-place type conversion of a NumPy array. If you're concerned about copying your array (which is whatastype() does) definitely check out the link.

React.js, wait for setState to finish before triggering a function?

setState takes new state and optional callback function which is called after the state has been updated.

  {newState: 'whatever'},
  () => {/*do something after the state has been updated*/}

How does EL empty operator work in JSF?

From EL 2.2 specification (get the one below "Click here to download the spec for evaluation"):

1.10 Empty Operator - empty A

The empty operator is a prefix operator that can be used to determine if a value is null or empty.

To evaluate empty A

  • If A is null, return true
  • Otherwise, if A is the empty string, then return true
  • Otherwise, if A is an empty array, then return true
  • Otherwise, if A is an empty Map, return true
  • Otherwise, if A is an empty Collection, return true
  • Otherwise return false

So, considering the interfaces, it works on Collection and Map only. In your case, I think Collection is the best option. Or, if it's a Javabean-like object, then Map. Either way, under the covers, the isEmpty() method is used for the actual check. On interface methods which you can't or don't want to implement, you could throw UnsupportedOperationException.

Multiple maven repositories in one gradle file

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

allprojects {
    repositories {
        maven { url "" }
        maven { url "" }

How to select an element by classname using jqLite?

If elem.find() is not working for you, check that you are including JQuery script before angular script....

Attaching click to anchor tag in angular

You can use routerLink (which is an alternative of href for angular 2+) with click event as below to prevent from page reloading

<a [routerLink]="" (click)="onGoToPage2()">Go to page</a>

How to check for file lock?

When I faced with a similar problem, I finished with the following code:

public bool IsFileLocked(string filePath)
        using (File.Open(filePath, FileMode.Open)){}
    catch (IOException e)
        var errorCode = Marshal.GetHRForException(e) & ((1 << 16) - 1);

        return errorCode == 32 || errorCode == 33;

    return false;

Issue in installing php7.2-mcrypt

Mcrypt PECL extenstion

 sudo apt-get -y install gcc make autoconf libc-dev pkg-config
 sudo apt-get -y install libmcrypt-dev
 sudo pecl install mcrypt-1.0.1

When you are shown the prompt

 libmcrypt prefix? [autodetect] :

Press [Enter] to autodetect.

After success installing mcrypt trought pecl, you should add extension to php.ini.

The output will look like this:

Build process completed successfully
Installing '/usr/lib/php/20170718/'    ---->   this is our path to mcrypt extension lib
install ok: channel://
configuration option "php_ini" is not set to php.ini location
You should add "" to php.ini

Grab installing path and add to cli and apache2 php.ini configuration.

sudo bash -c "echo extension=/usr/lib/php/20170718/ > /etc/php/7.2/cli/conf.d/mcrypt.ini"
sudo bash -c "echo extension=/usr/lib/php/20170718/ > /etc/php/7.2/apache2/conf.d/mcrypt.ini"

Verify that the extension was installed

Run command:

php -i | grep "mcrypt"

The output will look like this:

Registered Stream Filters => zlib.*, string.rot13, string.toupper, string.tolower, string.strip_tags, convert.*, consumed, dechunk, convert.iconv.*, mcrypt.*, mdecrypt.*
mcrypt support => enabled
mcrypt_filter support => enabled
mcrypt.algorithms_dir => no value => no value
mcrypt.modes_dir => no value => no value

How to validate a date?

This solution does not address obvious date validations such as making sure date parts are integers or that date parts comply with obvious validation checks such as the day being greater than 0 and less than 32. This solution assumes that you already have all three date parts (year, month, day) and that each already passes obvious validations. Given these assumptions this method should work for simply checking if the date exists.

For example February 29, 2009 is not a real date but February 29, 2008 is. When you create a new Date object such as February 29, 2009 look what happens (Remember that months start at zero in JavaScript):

console.log(new Date(2009, 1, 29));

The above line outputs: Sun Mar 01 2009 00:00:00 GMT-0800 (PST)

Notice how the date simply gets rolled to the first day of the next month. Assuming you have the other, obvious validations in place, this information can be used to determine if a date is real with the following function (This function allows for non-zero based months for a more convenient input):

var isActualDate = function (month, day, year) {
    var tempDate = new Date(year, --month, day);
    return month === tempDate.getMonth();

This isn't a complete solution and doesn't take i18n into account but it could be made more robust.

Modifying location.hash without page scrolling

Adding this here because the more relevant questions have all been marked as duplicates pointing here…

My situation is simpler:

  • user clicks the link (a[href='#something'])
  • click handler does: e.preventDefault()
  • smoothscroll function: $("html,body").stop(true,true).animate({ "scrollTop": }, scrollspeed, "swing" );
  • then window.location = link;

This way, the scroll occurs, and there's no jump when the location is updated.

Unable to load DLL 'SQLite.Interop.dll'

If you download correct binary for SQLite then copy SQLite.Interop.dll into your Release or Debug folder according to your project build option.

Keep the order of the JSON keys during JSON conversion to CSV

instead of using jsonObject try using CsvSchema its way easier and directly converts object to csv

CsvSchema schema = csvMapper.schemaFor(MyClass.class).withHeader();

and it mentains the order id your pojo has @JsonPropertyOrder in it

"element.dispatchEvent is not a function" js error caught in firebug of FF3.0

check for this by calling the library jquery after the noconflict.js or that this calling more than once jquery library after the noconflict.js

What is the difference between an interface and abstract class?

Interfaces are generally the classes without logic just a signature. Whereas abstract classes are those having logic. Both support contract as interface all method should be implemented in the child class but in abstract only the abstract method should be implemented. When to use interface and when to abstract? Why use Interface?

class Circle {

protected $radius;

public function __construct($radius)

    $this->radius = $radius

public function area()
    return 3.14159 * pow(2,$this->radius); // simply pie.r2 (square);


//Our area calculator class would look like

class Areacalculator {

$protected $circle;

public function __construct(Circle $circle)
    $this->circle = $circle;

public function areaCalculate()
    return $circle->area(); //returns the circle area now


We would simply do

$areacalculator = new Areacalculator(new Circle(7)); 

Few days later we would need the area of rectangle, Square, Quadrilateral and so on. If so do we have to change the code every time and check if the instance is of square or circle or rectangle? Now what OCP says is CODE TO AN INTERFACE NOT AN IMPLEMENTATION. Solution would be:

Interface Shape {

public function area(); //Defining contract for the classes


Class Square implements Shape {

$protected length;

public function __construct($length) {
    //settter for length like we did on circle class

public function area()
    //return l square for area of square

Class Rectangle implements Shape {

$protected length;
$protected breath;

public function __construct($length,$breath) {
    //settter for length, breath like we did on circle,square class

public function area()
    //return l*b for area of rectangle


Now for area calculator

class Areacalculator {

$protected $shape;

public function __construct(Shape $shape)
    $this->shape = $shape;

public function areaCalculate()
    return $shape->area(); //returns the circle area now


$areacalculator = new Areacalculator(new Square(1));

$areacalculator = new Areacalculator(new Rectangle(1,2));

Isn't that more flexible? If we would code without interface we would check the instance for each shape redundant code.

Now when to use abstract?

Abstract Animal {

public function breathe(){

//all animals breathe inhaling o2 and exhaling co2


public function hungry() {

//every animals do feel hungry 


abstract function communicate(); 
// different communication style some bark, some meow, human talks etc


Now abstract should be used when one doesn't need instance of that class, having similar logic, having need for the contract.

Calculate date/time difference in java

Here is my code.

import java.util.Date;

// to calculate difference between two days
public class DateDifference {

// to calculate difference between two dates in milliseconds
public long getDateDiffInMsec(Date da, Date db) {
    long diffMSec = 0;
    diffMSec = db.getTime() - da.getTime();
    return diffMSec;

// to convert Milliseconds into DD HH:MM:SS format.
public String getDateFromMsec(long diffMSec) {
    int left = 0;
    int ss = 0;
    int mm = 0;
    int hh = 0;
    int dd = 0;
    left = (int) (diffMSec / 1000);
    ss = left % 60;
    left = (int) left / 60;
    if (left > 0) {
        mm = left % 60;
        left = (int) left / 60;
        if (left > 0) {
            hh = left % 24;
            left = (int) left / 24;
            if (left > 0) {
                dd = left;
    String diff = Integer.toString(dd) + " " + Integer.toString(hh) + ":"
            + Integer.toString(mm) + ":" + Integer.toString(ss);
    return diff;


Android - get children inside a View?

I'm just going to provide this answer as an alternative @IHeartAndroid's recursive algorithm for discovering all child Views in a view hierarchy. Note that at the time of this writing, the recursive solution is flawed in that it will contains duplicates in its result.

For those who have trouble wrapping their head around recursion, here's a non-recursive alternative. You get bonus points for realizing this is also a breadth-first search alternative to the depth-first approach of the recursive solution.

private List<View> getAllChildrenBFS(View v) {
    List<View> visited = new ArrayList<View>();
    List<View> unvisited = new ArrayList<View>();

    while (!unvisited.isEmpty()) {
        View child = unvisited.remove(0);
        if (!(child instanceof ViewGroup)) continue;
        ViewGroup group = (ViewGroup) child;
        final int childCount = group.getChildCount();
        for (int i=0; i<childCount; i++) unvisited.add(group.getChildAt(i));

    return visited;

A couple of quick tests (nothing formal) suggest this alternative is also faster, although that has most likely to do with the number of new ArrayList instances the other answer creates. Also, results may vary based on how vertical/horizontal the view hierarchy is.

Cross-posted from: Android | Get all children elements of a ViewGroup

Android simple alert dialog

You can easily make your own 'AlertView' and use it everywhere.

alertView("You really want this?");

Implement it once:

private void alertView( String message ) {
 AlertDialog.Builder dialog = new AlertDialog.Builder(context);
 dialog.setTitle( "Hello" )
//     .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
//      public void onClick(DialogInterface dialoginterface, int i) {
//          dialoginterface.cancel();   
//          }})
      .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialoginterface, int i) {   

resize font to fit in a div (on one line)

@Clovis Six thank for your answer. It prove very usefull to me. A pity I cannot thanks you more than just a vote up.

Note: I have to change the "$J(" for "$(" for it to work on my config.

evendo, this out of the scope of this question and not in the use of SO, I extended your code to make it work for multi-line box with max-height.

   * Adjust the font-size of the text so it fits the container
   * support multi-line, based on css 'max-height'.
   * @param minSize     Minimum font size?
   * @param maxSize     Maximum font size?
  $.fn.autoTextSize_UseMaxHeight = function(minSize, maxSize) {
    var _self = this,
        _width = _self.innerWidth(),
        _boxHeight = parseInt(_self.css('max-height')),
        _textHeight = parseInt(_self.getTextHeight(_width)),
        _fontSize = parseInt(_self.css('font-size'));

    while (_boxHeight < _textHeight || (maxSize && _fontSize > parseInt(maxSize))) {
      if (minSize && _fontSize <= parseInt(minSize)) break;

      _self.css('font-size', _fontSize + 'px');

      _textHeight = parseInt(_self.getTextHeight(_width));

PS: I know this should be a comment, but comments don't let me post code properly.

Facebook Graph API error code list

I have also found some more error subcodes, in case of OAuth exception. Copied from the facebook bugtracker, without any garantee (maybe contain deprecated, wrong and discontinued ones):

  * (Date: 30.01.2013)
  * case 1: - "An error occured while creating the share (publishing to wall)"
  *         - "An unknown error has occurred."
  * case 2:    "An unexpected error has occurred. Please retry your request later."
  * case 3:    App must be on whitelist        
  * case 4:    Application request limit reached
  * case 5:    Unauthorized source IP address        
  * case 200:  Requires extended permissions
  * case 240:  Requires a valid user is specified (either via the session or via the API parameter for specifying the user."
  * case 1500: The url you supplied is invalid
  * case 200:
  * case 210:  - Subject must be a page
  *            - User not visible

  * Error Code 100 several issus:
  * - "Specifying multiple ids with a post method is not supported" (http status 400)
  * - "Error finding the requested story" but it is available via GET
  * - "Invalid post_id"
  * - "Code was invalid or expired. Session is invalid."
  * Error Code 2: 
  * - Service temporarily unavailable

$(document).ready not Working

This will happen if the host page is HTTPS and the included javascript source path is HTTP. The two protocols must be the same, HTTPS. The tell tail sign would be to check under Firebug and notice that the JS is "denied access".

Access files stored on Amazon S3 through web browser

I had the same problem and I fixed it by using the

  1. new context menu "Make Public".
  2. Go to,
  3. select the bucket and then for each Folder or File (or multiple selects) right click and
  4. "make public"

How to format dateTime in django template?

I suspect wpis.entry.lastChangeDate has been somehow transformed into a string in the view, before arriving to the template.

In order to verify this hypothesis, you may just check in the view if it has some property/method that only strings have - like for instance wpis.entry.lastChangeDate.upper, and then see if the template crashes.

You could also create your own custom filter, and use it for debugging purposes, letting it inspect the object, and writing the results of the inspection on the page, or simply on the console. It would be able to inspect the object, and check if it is really a DateTimeField.

On an unrelated notice, why don't you use models.DateTimeField(auto_now_add=True) to set the datetime on creation?

How to access a dictionary key value present inside a list?

If you know which dict in the list has the key you're looking for, then you already have the solution (as presented by Matt and Ignacio). However, if you don't know which dict has this key, then you could do this:

def getValueOf(k, L):
    for d in L:
        if k in d:
            return d[k]

Is the Scala 2.8 collections library a case of "the longest suicide note in history"?

Scala has a lot of crazy features (particularly where implicit parameters are concerned) that look very complicated and academic, but are designed to make things easy to use. The most useful ones get syntactic sugar (like [A <% B] which means that an object of type A has an implicit conversion to an object of type B) and a well-documented explanation of what they do. But most of the time, as a client of these libraries you can ignore the implicit parameters and trust them to do the right thing.

PHP sessions that have already been started

If you want a new one, then do session_destroy() before starting it. To check if its set before starting it, call session_status() :

$status = session_status();
if($status == PHP_SESSION_NONE){
    //There is no active session
if($status == PHP_SESSION_DISABLED){
    //Sessions are not available
if($status == PHP_SESSION_ACTIVE){
    //Destroy current and start new one

I would avoid checking the global $_SESSION instead of I am calling the session_status() method since PHP implemented this function explicitly to:

Expose session status via new function, session_status This is for (PHP >=5.4.0)

angularjs ng-style: background-image isn't working

If we have a dynamic value that needs to go in a css background or background-image attribute, it can be just a bit more tricky to specify.

Let’s say we have a getImage() function in our controller. This function returns a string formatted similar to this: url(icons/pen.png). If we do, the ngStyle declaration is specified the exact same way as before:

ng-style="{ 'background-image': getImage() }"

Make sure to put quotes around the background-image key name. Remember, this must be formatted as a valid Javascript object key.

How to find the Git commit that introduced a string in any branch?

git log -S"string_to_search" # options like --source --reverse --all etc

Pay attention not to use spaces between S and "string_to_search". In some setups (git 1.7.1), you'll get an error like:

fatal: ambiguous argument 'string_to_search': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions

Remove all git files from a directory?

The .git folder is only stored in the root directory of the repo, not all the sub-directories like subversion. You should be able to just delete that one folder, unless you are using Submodules...then they will have one too.

Which TensorFlow and CUDA version combinations are compatible?

The compatibility table given in the tensorflow site does not contain specific minor versions for cuda and cuDNN. However, if the specific versions are not met, there will be an error when you try to use tensorflow.

For tensorflow-gpu==1.12.0 and cuda==9.0, the compatible cuDNN version is 7.1.4, which can be downloaded from here after registration.

You can check your cuda version using
nvcc --version

cuDNN version using
cat /usr/include/cudnn.h | grep CUDNN_MAJOR -A 2

tensorflow-gpu version using
pip freeze | grep tensorflow-gpu

UPDATE: Since tensorflow 2.0, has been released, I will share the compatible cuda and cuDNN versions for it as well (for Ubuntu 18.04).

  • tensorflow-gpu = 2.0.0
  • cuda = 10.0
  • cuDNN = 7.6.0

TypeError : Unhashable type

... and so you should do something like this:

set(tuple ((a,b) for a in range(3)) for b in range(3))

... and if needed convert back to list

How does one Display a Hyperlink in React Native App?

If you want to do links and other types of rich text, a more comprehensive solution is to use React Native HTMLView.

Install IPA with iTunes 12

Since iTunes 12.7 doesn't have "Application" section so it can't be done. As a workaround I've found this answer.

I simply installed "Apple Configurator 2". Than:

  1. Run application
  2. Connect device
  3. Unlock device
  4. Drag IPA file to visualisation of device in "Apple Configurator 2"
  5. Confirm action

I didn't had to "sign in" as described in on linked question answers

Checkbox angular material checked by default

// in component.ts
checked: boolean = true;
indeterminate:boolean = false;
disabled:boolean = false;

onCheck() {
    this.label = this.checked?'ON':'OFF';

// in component.html`enter code here`
<mat-checkbox class="example-margin" [color]="primary" [(ngModel)]="checked" [(indeterminate)]="indeterminate" [labelPosition]="after" [disabled]="disabled" (change)="onCheck()">

The above code should work fine. Mat checkbox allows you to make it checked/unchecked, disabled, set indeterminate state, do some operation onChange of the state etc. Refer API for more details.

How to pass a view's onClick event to its parent on Android?

I think you need to use one of those methods in order to be able to intercept the event before it gets sent to the appropriate components:

Activity.dispatchTouchEvent(MotionEvent) - This allows your Activity to intercept all touch events before they are dispatched to the window.

ViewGroup.onInterceptTouchEvent(MotionEvent) - This allows a ViewGroup to watch events as they are dispatched to child Views.

ViewParent.requestDisallowInterceptTouchEvent(boolean) - Call this upon a parent View to indicate that it should not intercept touch events with onInterceptTouchEvent(MotionEvent).

More information here.

Hope that helps.

PreparedStatement IN clause alternatives?

You can use Collections.nCopies to generate a collection of placeholders and join them using String.join:

List<String> params = getParams();
String placeHolders = String.join(",", Collections.nCopies(params.size(), "?"));
String sql = "select * from your_table where some_column in (" + placeHolders + ")";
try (   Connection connection = getConnection();
        PreparedStatement ps = connection.prepareStatement(sql)) {
    int i = 1;
    for (String param : params) {
        ps.setString(i++, param);
     * Execute query/do stuff

How to round a number to n decimal places in Java

here is my answer:

double num = 4.898979485566356;
DecimalFormat df = new DecimalFormat("#.##");      
time = Double.valueOf(df.format(num));

System.out.println(num); // 4.89

How can I get a web site's favicon?

You can get the favicon URL from the website's HTML.

Here is the favicon element:

<link rel="icon" type="image/png" href="/someimage.png" />

You should use a regular expression here. If no tag found, look for favicon.ico in the site root directory. If nothing found, the site does not have a favicon.

Function not defined javascript

I just went through the same problem. And found out once you have a syntax or any type of error in you javascript, the whole file don't get loaded so you cannot use any of the other functions at all.

Where does Anaconda Python install on Windows?

You can search for "Anaconda prompt" in installed programs and run it.
When it opens, it shows the directory anaconda is working from.
enter image description here

As you can see c:\programdata\anaconda2 is my installed directory.
*side note: programdata folder is hidden in windows so you'll have to enter its path in the folder explorer to access it.

The listener supports no services

You need to add your ORACLE_HOME definition in your listener.ora file. Right now its not registered with any ORACLE_HOME.

Sample listener.ora

abc =
      (ADDRESS = (PROTOCOL = TCP)(HOST = = 1521))

SID_LIST_abc =
    (SID_DESC =
      (ORACLE_HOME= /abc/DbTier/11.2.0)
      (SID_NAME = abc)

How do I check if an object has a specific property in JavaScript?

Note: the following is nowadays largely obsolete thanks to strict mode, and hasOwnProperty. The correct solution is to use strict mode and to check for the presence of a property using obj.hasOwnProperty. This answer predates both these things, at least as widely implemented (yes, it is that old). Take the following as a historical note.

Bear in mind that undefined is (unfortunately) not a reserved word in JavaScript if you’re not using strict mode. Therefore, someone (someone else, obviously) could have the grand idea of redefining it, breaking your code.

A more robust method is therefore the following:

if (typeof(x.attribute) !== 'undefined')

On the flip side, this method is much more verbose and also slower. :-/

A common alternative is to ensure that undefined is actually undefined, e.g. by putting the code into a function which accepts an additional parameter, called undefined, that isn’t passed a value. To ensure that it’s not passed a value, you could just call it yourself immediately, e.g.:

(function (undefined) {
    … your code …
    if (x.attribute !== undefined)
        … mode code …

An efficient way to transpose a file in Bash

Pure BASH, no additional process. A nice exercise:

declare -a array=( )                      # we build a 1-D-array

read -a line < "$1"                       # read the headline

COLS=${#line[@]}                          # save number of columns

while read -a line ; do
    for (( COUNTER=0; COUNTER<${#line[@]}; COUNTER++ )); do
done < "$1"

for (( ROW = 0; ROW < COLS; ROW++ )); do
  for (( COUNTER = ROW; COUNTER < ${#array[@]}; COUNTER += COLS )); do
    printf "%s\t" ${array[$COUNTER]}
  printf "\n" 

Copy files from one directory into an existing directory

cp dir1/* dir2

Or if you have directories inside dir1 that you'd want to copy as well

cp -r dir1/* dir2

Swing/Java: How to use the getText and setText string properly

the getText method returns a String, while the setText receives a String, so you can write it like label1.setText(nameField.getText()); in your listener.

ASP.NET document.getElementById('<%=Control.ClientID%>'); returns null


You have to use RegisterStartupScript instead of RegisterClientScriptBlock

Here My Example.


<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs"
    Inherits="prueba.MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">

    <script type="text/javascript">

        function confirmCallBack() {
            var a = document.getElementById('<%= Page.Master.FindControl("ContentPlaceHolder1").FindControl("Button1").ClientID %>');




    <asp:ContentPlaceHolder ID="head" runat="server">
    <form id="form1" runat="server">
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">


<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true"
    CodeBehind="WebForm1.aspx.cs" Inherits="prueba.WebForm1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">


<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace prueba
    public partial class WebForm1 : System.Web.UI.Page
        protected void Page_Load(object sender, EventArgs e)
            ClientScript.RegisterStartupScript(this.GetType(), "js", "confirmCallBack();", true);


How to set the part of the text view is clickable

To add a linked text in a text view, you can use the "footer_text" string resource example below and also edit your onCreate method for your activity, you can use the example below


<?xml version="1.0" charset="utf-8"?>
     <string name="app_name">Name of My Application</string>

    <string name="footer_text">
        <a href="">Terms of Service</a>
        <a href="">Contact</a>
        <a href="">Privacy Policy</a>


public void onCreate(Bundle savedInstance) {

    TextView textView = findViewById(;


Loop through all the files with a specific extension

I found this solution to be quite handy. It uses the -or option in find:

find . -name \*.tex -or -name "*.png" -or -name "*.pdf"

It will find the files with extension tex, png, and pdf.

Joining Multiple Tables - Oracle

I recommend that you get in the habit, right now, of using ANSI-style joins, meaning you should use the INNER JOIN, LEFT OUTER JOIN, RIGHT OUTER JOIN, FULL OUTER JOIN, and CROSS JOIN elements in your SQL statements rather than using the "old-style" joins where all the tables are named together in the FROM clause and all the join conditions are put in the the WHERE clause. ANSI-style joins are easier to understand and less likely to be miswritten and/or misinterpreted than "old-style" joins.

I'd rewrite your query as:

SELECT bc.firstname,
       TO_CHAR(bo.orderdate, 'MM/DD/YYYY') "Order Date",
INNER JOIN books b
INNER JOIN  book_order bo
INNER JOIN publisher p
WHERE p.publishername = 'PRINTING IS US';

Share and enjoy.

Spring Boot JPA - configuring auto reconnect

whoami's answer is the correct one. Using the properties as suggested I was unable to get this to work (using Spring Boot 1.5.3.RELEASE)

I'm adding my answer since it's a complete configuration class so it might help someone using Spring Boot:

public class SwatDataBaseConfig {

    private String fileLocation;

    private String dbURL;

    private String driverName;

    private String userName;

    private String hashedPassword;

    public DataSource primaryDataSource() {
        PoolProperties poolProperties = new PoolProperties();
        poolProperties.setValidationQuery("SELECT 1");
        DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource(poolProperties);
        return ds;

Controlling Spacing Between Table Cells

Use border-collapse and border-spacing to get spaces between the table cells. I would not recommend using floating cells as suggested by QQping.


Tensorflow installation error: not a supported wheel on this platform

For Windows 10 64bit:

I have tried all the suggestions here, but finally got it running as follows:

  1. Uninstall all current versions of Python
  2. Remove all Python references in the PATH system and user Environment variables
  3. Download the latest 64bit version of Python 3.8: Python 3.8.7 currently, NOT the latest 3.9.x version which is the one I was using, and NOT 32bit.
  4. Install with all options selected, including pip, and including PATH Environment variable
  5. pip install tensorflow (in Admin CMD prompt)
  6. Upgrade pip if prompted (optional)

How to list all databases in the mongo shell?

Listing all the databases in mongoDB console is using the command show dbs.

For more information on this, refer the Mongo Shell Command Helpers that can be used in the mongo shell.

How do I install a JRE or JDK to run the Android Developer Tools on Windows 7?

download jre1.7.0_45 and then extract it into the Eclipse folder and rename folder of jre1.7.0_45 to jre and Eclipse will run

Does IE9 support console.log, and is it a real function?

After reading the article from Marc Cliament's comment above, I've now changed my all-purpose cross-browser console.log function to look like this:

function log()
    "use strict";

    if (typeof(console) !== "undefined" && console.log !== undefined)
            console.log.apply(console, arguments);
        catch (e)
            var log =, console);
            log.apply(console, arguments);

Tomcat is not deploying my web project from Eclipse

I had the same problem. I fixed it by makinbg the following entry in org.eclipse.wst.common.project.facet.core.xml

<runtime name="Apache Tomcat v7.0" />

Now this complete file looks like -

<?xml version="1.0" encoding="UTF-8"?>
    <runtime name="Apache Tomcat v7.0" />
    <fixed facet="wst.jsdt.web" />
    <installed facet="java" version="1.5" />
    <installed facet="jst.web" version="2.3" />
    <installed facet="wst.jsdt.web" version="1.0" />

WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser

I use chromium but I have created a shell script called chrome just to be easy for me to open the browser from dmenu.



Chrome driver looking for chrome in PATH and executes that. In result I got the same error.

org.openqa.selenium.WebDriverException: unknown error: Chrome failed to start: exited normally.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /home/s1n7ax/.local/share/s1n7ax/bin/chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 's1n7ax', ip: '', 'Linux', os.arch: 'amd64', os.version: '5.4.70-1-lts', java.version: '11.0.8'
Driver info: driver.version: ChromeDriver
remote stacktrace: #0 0x56030c96dd99 <unknown>

I just removed the shell script and added a soft link to chromium. Everything working now.

Passing Multiple route params in Angular2

Two Methods for Passing Multiple route params in Angular


In app.module.ts

Set path as component2.

imports: [
 [ {path: 'component2/:id1/:id2', component: MyComp2}])

Call router to naviagte to MyComp2 with multiple params id1 and id2.

export class MyComp1 {
    this._router.navigate( ['component2', "id1","id2"]);


In app.module.ts

Set path as component2.

imports: [
 [ {path: 'component2', component: MyComp2}])

Call router to naviagte to MyComp2 with multiple params id1 and id2.

export class MyComp1 {
    this._router.navigate( ['component2', {id1: "id1 Value", id2: 
    "id2  Value"}]);

CSS selector - element with a given child

I agree that it is not possible in general.

The only thing CSS3 can do (which helped in my case) is to select elements that have no children:

table td:empty
   background-color: white;

Or have any children (including text):

table td:not(:empty)
   background-color: white;

ASP.NET Identity reset password

Best way to Reset Password in Asp.Net Core Identity use for Web API.

Note* : Error() and Result() are created for internal use. You can return you want.

        public async Task<IActionResult> ResetPassword(ResetPasswordModel model)
            if (!ModelState.IsValid)
                return BadRequest(ModelState);
                if (model is null)
                    return Error("No data found!");

                var user = await _userManager.FindByIdAsync(AppCommon.ToString(GetUserId()));
                if (user == null)
                    return Error("No user found!");

                Microsoft.AspNetCore.Identity.SignInResult checkOldPassword =
                    await _signInManager.PasswordSignInAsync(user.UserName, model.OldPassword, false, false);

                if (!checkOldPassword.Succeeded)
                    return Error("Old password does not matched.");

                string resetToken = await _userManager.GeneratePasswordResetTokenAsync(user);
                if (string.IsNullOrEmpty(resetToken))
                    return Error("Error while generating reset token.");

                var result = await _userManager.ResetPasswordAsync(user, resetToken, model.Password);

                if (result.Succeeded)
                    return Result();
                    return Error();
            catch (Exception ex)
                return Error(ex);

How do you run a command for each line of a file?


while read in; do chmod 755 "$in"; done < file.txt

This way you can avoid a cat process.

cat is almost always bad for a purpose such as this. You can read more about Useless Use of Cat.

How do I get the file extension of a file in Java?

Just a regular-expression based alternative. Not that fast, not that good.

Pattern pattern = Pattern.compile("\\.([^.]*)$");
Matcher matcher = pattern.matcher(fileName);

if (matcher.find()) {
    String ext =;

CharSequence VS String in Java?


A CharSequence is an interface, not an actual class. An interface is just a set of rules (methods) that a class must contain if it implements the interface. In Android a CharSequence is an umbrella for various types of text strings. Here are some of the common ones:

(You can read more about the differences between these here.)

If you have a CharSequence object, then it is actually an object of one of the classes that implement CharSequence. For example:

CharSequence myString = "hello";
CharSequence mySpannableStringBuilder = new SpannableStringBuilder();

The benefit of having a general umbrella type like CharSequence is that you can handle multiple types with a single method. For example, if I have a method that takes a CharSequence as a parameter, I could pass in a String or a SpannableStringBuilder and it would handle either one.

public int getLength(CharSequence text) {
    return text.length();


You could say that a String is just one kind of CharSequence. However, unlike CharSequence, it is an actual class, so you can make objects from it. So you could do this:

String myString = new String();

but you can't do this:

CharSequence myCharSequence = new CharSequence(); // error: 'CharSequence is abstract; cannot be instantiated

Since CharSequence is just a list of rules that String conforms to, you could do this:

CharSequence myString = new String();

That means that any time a method asks for a CharSequence, it is fine to give it a String.

String myString = "hello";
getLength(myString); // OK

// ...

public int getLength(CharSequence text) {
    return text.length();

However, the opposite is not true. If the method takes a String parameter, you can't pass it something that is only generally known to be a CharSequence, because it might actually be a SpannableString or some other kind of CharSequence.

CharSequence myString = "hello";
getLength(myString); // error

// ...

public int getLength(String text) {
    return text.length();

Setting equal heights for div's with jQuery

function equalHeight(group) {
   tallest = 0;
   group.each(function() {
      thisHeight = $(this).height();
      if(thisHeight > tallest) {
         tallest = thisHeight;
$(document).ready(function() {

Does a VPN Hide my Location on Android?

Your question can be conveniently divided into several parts:

Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.

How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.

You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):

  1. Download and install a trusted VPN.

  2. Install the VPN on your Android device.

  3. Open the application and connect to a server in a different country.

  4. Your Android location will now be successfully changed!

Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.

Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.

How to find the users list in oracle 11g db?

You can try the following: (This may be duplicate of the answers posted but I have added description)

Display all users that can be seen by the current user:

SELECT * FROM all_users;

Display all users in the Database:

SELECT * FROM dba_users;

Display the information of the current user:

SELECT * FROM user_users;

Lastly, this will display all users that can be seen by current users based on creation date:

SELECT * FROM all_users
ORDER BY created;

href="tel:" and mobile numbers

I know the OP is asking about international country codes but for North America, you could use the following:

<a href="tel:+1-847-555-5555">1-847-555-5555</a>

<a href="tel:+18475555555">Click Here To Call Support 1-847-555-5555</a>

This might help you.

Getting the current date in SQL Server?


Returns the current date with the time part removed.

DATETIMEs are not "stored in the following format". They are stored in a binary format.


The display format in the question is independent of storage.

Formatting into a particular display format should be done by your application.

push multiple elements to array

When using most functions of objects with apply or call, the context parameter MUST be the object you are working on.

In this case, you need a.push.apply(a, [1,2]) (or more correctly Array.prototype.push.apply(a, [1,2]))

Refresh (reload) a page once using jQuery?

Use this:

    <script type="text/javascript">

            // Check if the current URL contains '#'
                // Set the URL to whatever it was plus "#".
                url = document.URL+"#";
                location = "#";

                //Reload the page

Due to the if condition, the page will reload only once.

Temporarily disable all foreign key constraints

Truncating the table wont be possible even if you disable the foreign you can use delete command to remove all the records from the table,but be aware if you are using delete command for a table which consists of millions of records then your package will be slow and your transaction log size will increase and it may fill up your valuable disk space.

If you drop the constraints it may happen that you will fill up your table with unclean data and when you try to recreate the constraints it may not allow you to as it will give errors. so make sure that if you drop the constraints,you are loading data which are correctly related to each other and satisfy the constraint relations which you are going to recreate.

so please carefully think the pros and cons of each method and use it according to your requirements

Error: "The sandbox is not in sync with the Podfile.lock..." after installing RestKit with cocoapods

Try to set up the correct target in Podfile and then run pod update or pod install

ios platform target

Get connection status on client

@robertklep's answer to check socket.connected is correct except for reconnect event, As the document said it is "Fired upon a successful reconnection." but when you check socket.connected then it is false.

Not sure it is a bug or intentional.

Converting File to MultiPartFile

File file = new File("src/test/resources/validation.txt");
DiskFileItem fileItem = new DiskFileItem("file", "text/plain", false, file.getName(), (int) file.length() , file.getParentFile());
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);

You need the


because it will throw NPE otherwise.

HTTP Status 405 - Request method 'POST' not supported (Spring MVC)

I am not sure if this helps but I had the same problem.

You are using springSecurityFilterChain with CSRF protection. That means you have to send a token when you send a form via POST request. Try to add the next input to your form:

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

Use this to force IE to hide that annoying browser compatibility button in the address bar:

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

How to install easy_install in Python 2.7.1 on Windows 7

That tool is part of the setuptools (now called Distribute) package. Install Distribute. Of course you'll have to fetch that one manually.

MySQL: Cloning a MySQL database on the same MySql instance

If you have triggers in your original database, you can avoid the "Trigger already exists" error by piping a replacement before the import:

mysqldump -u olddbuser -p -d olddbname | sed "s/`olddbname`./`newdbname`./" | mysql -u newdbuser -p -D newdbname

Get Folder Size from Windows Command Line


powershell -command "$fso = new-object -com Scripting.FileSystemObject; gci -Directory | select @{l='Size'; e={$fso.GetFolder($_.FullName).Size}},FullName | sort Size -Descending | ft @{l='Size [MB]'; e={'{0:N2}    ' -f ($_.Size / 1MB)}},FullName"

Same but Powershell only:

$fso = new-object -com Scripting.FileSystemObject
gci -Directory `
  | select @{l='Size'; e={$fso.GetFolder($_.FullName).Size}},FullName `
  | sort Size -Descending `
  | ft @{l='Size [MB]'; e={'{0:N2}    ' -f ($_.Size / 1MB)}},FullName

This should produce the following result:

Size [MB]  FullName
---------  --------
580,08     C:\my\Tools\mongo
434,65     C:\my\Tools\Cmder
421,64     C:\my\Tools\mingw64
247,10     C:\my\Tools\dotnet-rc4
218,12     C:\my\Tools\ResharperCLT
200,44     C:\my\Tools\git
156,07     C:\my\Tools\dotnet
140,67     C:\my\Tools\vscode
97,33      C:\my\Tools\apache-jmeter-3.1
54,39      C:\my\Tools\mongoadmin
47,89      C:\my\Tools\Python27
35,22      C:\my\Tools\robomongo

Arraylist swap elements

Use like this. Here is the online compilation of the code. Take a look

public static void swap(List list,
                        int i,
                        int j)

Swaps the elements at the specified positions in the specified list. (If the specified positions are equal, invoking this method leaves the list unchanged.)

Parameters: list - The list in which to swap elements. i - the index of one element to be swapped. j - the index of the other element to be swapped.

Read The official Docs of collection,%20int,%20int%29

import java.util.*;
import java.lang.*;

class Main {
    public static void main(String[] args) throws java.lang.Exception       
        //create an ArrayList object
        ArrayList words = new ArrayList();

        //Add elements to Arraylist

        System.out.println("Before swaping, ArrayList contains : " + words);

      To swap elements of Java ArrayList use,
      static void swap(List list, int firstElement, int secondElement)
      method of Collections class. Where firstElement is the index of first
      element to be swapped and secondElement is the index of the second element
      to be swapped.

      If the specified positions are equal, list remains unchanged.

      Please note that, this method can throw IndexOutOfBoundsException if
      any of the index values is not in range.        */

        Collections.swap(words, 0, words.size() - 1);

        System.out.println("After swaping, ArrayList contains : " + words);    


Oneline compilation example

How to style child components from parent component's CSS file?

You should NOT use ::ng-deep, it is deprecated. In Angular, the proper way to change the style of children's component from the parent is to use encapsulation (read the warning below to understand the implications):

import { ViewEncapsulation } from '@angular/core';

    encapsulation: ViewEncapsulation.None

And then, you will be able to modify the css form your component without a need from ::ng-deep

.mat-sort-header-container {
  display: flex;
  justify-content: center;

WARNING: Doing this will make all css rules you write for this component to be global.

In order to limit the scope of your css to this component and his child only, add a css class to the top tag of your component and put your css "inside" this tag:

    <div class='my-component'>
      <child-component class="first">First</child>

Scss file:

.my-component {
  // All your css goes in there in order not to be global

Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style)

The cleanest and simplest solution is to use your own listener interface so that when the user clicks on the ok button your listener is called with the return value. This method does nothing fancy or complicated and respects android principles.

Define your listener interface as follows:

public interface EditListener
/* Used to get an integer return value from a dialog
 void returnValue(int value); 

For my application I created an EditValue class which uses AlertDialog and which I call whenever I want to edit an integer value. Note how the EditListener interface is passed as an argument to this code. When the user clicks on the OK button the value will be returned to your calling code via the EditListener method:

public final class EditValue
/* Used to edit a value using an alert dialog
 * The edited value is returned via the returnValue method of the supplied EditListener             interface
 * Could be modified with different constructors to edit double/float etc
 public EditValue(final Activity parent, int value, String title, String message,
                  final EditListener editListener)
 {AlertDialog.Builder alert= new AlertDialog.Builder(parent);
  if(title==null) title= message;
  else if(message==null) message= title;
  if(title!=null) alert.setTitle(title);
  if(message!=null) alert.setMessage(message);

  // Set an EditText view to get user input 
  final EditText input = new EditText(parent);

  alert.setPositiveButton("OK",new DialogInterface.OnClickListener()
  {public void onClick(DialogInterface dialog, int which)
    {int newValue= Integer.valueOf(input.getText().toString());
    }catch(NumberFormatException err) { }

  alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
  {public void onClick(DialogInterface dialog, int which)

Finally when you use EditValue you need to declare your EditListener and you can now access the return value and do what you want to do:

 new EditValue(main,AnchorManager.anchorageLimit,
               new EditListener()
 {public void returnValue(int value) {AnchorManager.anchorageLimit= value;}

Session variables in ASP.NET MVC

If you are using mvc, here is a simple way to access the session.

From a Controller:


From a View:

<%=Session["{name}"] %>

This is definitely not the best way to access your session variables, but it is a direct route. So use it with caution (preferably during rapid prototyping), and use a Wrapper/Container and OnSessionStart when it becomes appropriate.


403 - Forbidden: Access is denied. ASP.Net MVC

I just had this issue, it was because the IIS site was pointing at the wrong Application Pool.

Pro JavaScript programmer interview questions (with answers)

(I'm assuming you mean browser-side JavaScript)

Ask him why, despite his infinite knowledge of JavaScript, it is still a good idea to use existing frameworks such as jQuery, Mootools, Prototype, etc.

Answer: Good coders code, great coders reuse. Thousands of man hours have been poured into these libraries to abstract DOM capabilities away from browser specific implementations. There's no reason to go through all of the different browser DOM headaches yourself just to reinvent the fixes.

Invalid application path

I still haven’t find a solution, but find a workaround.

You can manually change IIS configuration, in system32\intsrv\config\applicationHost.config. Just manually create (copy-paste) section in <sites> and <location>.

How do I call paint event?

use Control.InvokePaint you can also use it for manual double buffering

Order by in Inner Join

SQL doesn't return any ordering by default because it's faster this way. It doesn't have to go through your data first and then decide what to do.

You need to add an order by clause, and probably order by which ever ID you expect. (There's a duplicate of names, thus I'd assume you want One.ID)

select * From one
inner join two
ON one.one_name = two.one_name

How to get IP address of running docker container

while read ctr;do
    sudo docker inspect --format "$ctr "'{{.Name}}{{ .NetworkSettings.IPAddress }}' $ctr
done < <(docker ps -a --filter status=running --format '{{.ID}}')

Write to UTF-8 file in Python

I believe the problem is that codecs.BOM_UTF8 is a byte string, not a Unicode string. I suspect the file handler is trying to guess what you really mean based on "I'm meant to be writing Unicode as UTF-8-encoded text, but you've given me a byte string!"

Try writing the Unicode string for the byte order mark (i.e. Unicode U+FEFF) directly, so that the file just encodes that as UTF-8:

import codecs

file ="lol", "w", "utf-8")

(That seems to give the right answer - a file with bytes EF BB BF.)

EDIT: S. Lott's suggestion of using "utf-8-sig" as the encoding is a better one than explicitly writing the BOM yourself, but I'll leave this answer here as it explains what was going wrong before.

Finding second occurrence of a substring in a string in Java

Use overloaded version of indexOf(), which takes the starting index (fromIndex) as 2nd parameter:

str.indexOf("is", str.indexOf("is") + 1);

How do I check what version of Python is running my script?

Put something like:

import sys
if sys.version_info<(2,6,0):
  sys.stderr.write("You need python 2.6 or later to run this script\n")

at the top of your script.

Note that depending on what else is in your script, older versions of python than the target may not be able to even load the script, so won't get far enough to report this error. As a workaround, you can run the above in a script that imports the script with the more modern code.

Run a mySQL query as a cron job?

Try creating a shell script like the one below:


mysql --user=[username] --password=[password] --database=[db name] --execute="DELETE FROM tbl_message WHERE DATEDIFF( NOW( ) ,  timestamp ) >=7"

You can then add this to the cron

Java Wait for thread to finish

Thread has a method that does that for you join which will block until the thread has finished executing.

dyld: Library not loaded: @rpath/libswiftCore.dylib

If you're getting an error like this:

The bundle "YourFrameworkTests" couldn't be loaded because it is damaged or missing necessary resources. Try reinstalling the bundle. (dlopen_preflight(/some/path/.../YourFrameworkTests.xctest/YourFrameworkTests): Library not loaded: @rpath/SomeOther.framework/SomeOther Referenced from: /some/path/...)

and use CocoaPods in your framework, then try to edit the Podfile and remove inherit! :search_paths from the Test target, and run pod install again.

For more details, see

Windows equivalent of OS X Keychain?

If you are on windows got to control pannel -> windows Credentials

Why is my toFixed() function not working?

document.getElementById("EDTVALOR").addEventListener("change", function() {
  this.value = this.value.replace(",", ".");
  this.value = parseFloat(this.value).toFixed(2);
  if (this.value < 0) {
    this.value = 0;
  this.value = this.value.replace(".", ",");
  this.value = this.value.replace("NaN", "0");

How to prevent the "Confirm Form Resubmission" dialog?

I was having this problem and added this JavaScript to the bottom of my page (read it at and it seemed to work. It seems much simpler a solution. Any drawbacks?

if ( window.history.replaceState ) {
  window.history.replaceState( null, null, window.location.href );



C: Run a System Command and Get Output?

You want the "popen" function. Here's an example of running the command "ls /etc" and outputing to the console.

#include <stdio.h>
#include <stdlib.h>

int main( int argc, char *argv[] )

  FILE *fp;
  char path[1035];

  /* Open the command for reading. */
  fp = popen("/bin/ls /etc/", "r");
  if (fp == NULL) {
    printf("Failed to run command\n" );

  /* Read the output a line at a time - output it. */
  while (fgets(path, sizeof(path), fp) != NULL) {
    printf("%s", path);

  /* close */

  return 0;

How to replicate background-attachment fixed on iOS

It looks to me like the background images aren't actually background images...the site has the background images and the quotes in sibling divs with the children of the div containing the images having been assigned position: fixed; The quotes div is also given a transparent background.

wrapper div{
   image wrapper div{
       div for individual image{ <--- Fixed position
          image <--- relative position
   quote wrapper div{
       div for individual quote{

Defining a variable with or without export

export will make the variable available to all shells forked from the current shell.

How do I run a class in a WAR from the command line?

The rules of locating classes in an archive file is that the location of the file's package declaration and the location of the file within the archive have to match. Since your class is located in WEB-INF/classes, it thinks the class is not valid to run in the current context.

The only way you can do what you're asking is to repackage the war so the .class file resides in the mypackage directory in the root of the archive rather than the WEB-INF/classes directory. However, if you do that you won't be able to access the file from any of your web classes anymore.

If you want to reuse this class in both the war and outside from the java command line, consider building an executable jar you can run from the command line, then putting that jar in the war file's WEB-INF/lib directory.

Convert dictionary to list collection in C#

If you want convert Keys:

List<string> listNumber = dicNumber.Keys.ToList();

else if you want convert Values:

List<string> listNumber = dicNumber.Values.ToList();