Programs & Examples On #Mongorestore

How to restore the dump into your running mongodb

Dump DB by mongodump

mongodump --host <database-host> -d <database-name> --port <database-port> --out directory

Restore DB by mongorestore

With Index Restore

mongorestore --host <database-host> -d <database-name> --port <database-port> foldername

Without Index Restore

mongorestore --noIndexRestore --host <database-host> -d <database-name> --port <database-port> foldername

Import Single Collection from CSV [1st Column will be treat as Col/Key Name]

mongoimport --db <database-name> --port <database-port> --collection <collection-name> --type csv --headerline --file /path/to/myfile.csv

Import Single Collection from JSON

mongoimport --db <database-name> --port <database-port> --collection <collection-name> --file input.json

Is there a Max function in SQL Server that takes two values like Math.Max in .NET?

SQL Server 2012 introduced IIF:

SELECT 
    o.OrderId, 
    IIF( ISNULL( o.NegotiatedPrice, 0 ) > ISNULL( o.SuggestedPrice, 0 ),
         o.NegotiatedPrice, 
         o.SuggestedPrice 
    )
FROM 
    Order o

Handling NULLs is recommended when using IIF, because a NULL on either side of your boolean_expression will cause IIF to return the false_value (as opposed to NULL).

convert HTML ( having Javascript ) to PDF using JavaScript

I'm surprised no one mentioned the possibility to use an API to do the work.

Granted, if you want to stay secure, converting HTML to PDF directly from within the browser using javascript is not a good idea.

But here's what you can do:

When your user hit the "Print" (for example) button, you:

  1. Send a request to your server at a specific endpoint with details about what to convert (URL of the page for instance).
  2. This endpoint will then send the data to convert to an API, and will receive the PDF in response
  3. which it will return to your user.

For a user point of view, they will receive a PDF by clicking on a button.

There are many available API that does the job, some better than others (that's not why I'm here) and a Google search will give you a lot of answers.

Depending on what is written your backend, you might be interested in PDFShift (Truth: I work there).

They offer ready to work packages for PHP, Python and Node.js. All you have to do is install the package, create an account, indicate your API key and you are all set!

The advantage of the API is that they work well in all languages. All you have to do is a request (generally POST) containing the data you want to be converted and get a PDF back. And depending on your usage, it's generally free, except if you are a heavy user.

Add class to <html> with Javascript?

Like this:

var root = document.getElementsByTagName( 'html' )[0]; // '0' to assign the first (and only `HTML` tag)

root.setAttribute( 'class', 'myCssClass' );

Or use this as your 'setter' line to preserve any previously applied classes: (thanks @ama2)

root.className += ' myCssClass';

Or, depending on the required browser support, you can use the classList.add() method:

root.classList.add('myCssClass');

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList http://caniuse.com/#feat=classlist

UPDATE:

A more elegant solution for referencing the HTML element might be this:

var root = document.documentElement;
root.className += ' myCssClass';
// ... or:
//  root.classList.add('myCssClass');
//

Bypass popup blocker on window.open when JQuery event.preventDefault() is set

var url = window.open("", "_blank");
url.location = "url";

this worked for me.

Does VBScript have a substring() function?

Yes, Mid.

Dim sub_str
sub_str = Mid(source_str, 10, 5)

The first parameter is the source string, the second is the start index, and the third is the length.

@bobobobo: Note that VBScript strings are 1-based, not 0-based. Passing 0 as an argument to Mid results in "invalid procedure call or argument Mid".

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

doThrow : Basically used when you want to throw an exception when a method is being called within a mock object.

public void validateEntity(final Object object){}
Mockito.doThrow(IllegalArgumentException.class)
.when(validationService).validateEntity(Matchers.any(AnyObjectClass.class));

doReturn : Used when you want to send back a return value when a method is executed.

public Socket getCosmosSocket() throws IOException {}
Mockito.doReturn(cosmosSocket).when(cosmosServiceImpl).getCosmosSocket();

doAnswer: Sometimes you need to do some actions with the arguments that are passed to the method, for example, add some values, make some calculations or even modify them doAnswer gives you the Answer interface that being executed in the moment that method is called, this interface allows you to interact with the parameters via the InvocationOnMock argument. Also, the return value of answer method will be the return value of the mocked method.

public ReturnValueObject quickChange(Object1 object);
Mockito.doAnswer(new Answer<ReturnValueObject>() {

        @Override
        public ReturnValueObject answer(final InvocationOnMock invocation) throws Throwable {

            final Object1 originalArgument = (invocation.getArguments())[0];
            final ReturnValueObject returnedValue = new ReturnValueObject();
            returnedValue.setCost(new Cost());

            return returnedValue ;
        }
}).when(priceChangeRequestService).quickCharge(Matchers.any(Object1.class));

doNothing: Is the easiest of the list, basically it tells Mockito to do nothing when a method in a mock object is called. Sometimes used in void return methods or method that does not have side effects, or are not related to the unit testing you are doing.

public void updateRequestActionAndApproval(final List<Object1> cmItems);

Mockito.doNothing().when(pagLogService).updateRequestActionAndApproval(
                Matchers.any(Object1.class));

Understanding ibeacon distancing

It's possible, but it depends on the power output of the beacon you're receiving, other rf sources nearby, obstacles and other environmental factors. Best thing to do is try it out in the environment you're interested in.

Can I install Python 3.x and 2.x on the same Windows computer?

As far as I know Python runs off of the commandline using the PATH variable as opposed to a registry setting.

So if you point to the correct version on your PATH you will use that. Remember to restart your command prompt to use the new PATH settings.

How can I use a local image as the base image with a dockerfile?

You can use it without doing anything special. If you have a local image called blah you can do FROM blah. If you do FROM blah in your Dockerfile, but don't have a local image called blah, then Docker will try to pull it from the registry.

In other words, if a Dockerfile does FROM ubuntu, but you have a local image called ubuntu different from the official one, your image will override it.

How to remove all namespaces from XML with C#?

For attributes to work the for loop for adding attribute should go after recursion, also need to check if IsNamespaceDeclaration:

private static XElement RemoveAllNamespaces(XElement xmlDocument)
{
    XElement xElement;

    if (!xmlDocument.HasElements)
    {
        xElement = new XElement(xmlDocument.Name.LocalName) { Value = xmlDocument.Value };
    }
    else
    {
        xElement = new XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(RemoveAllNamespaces));
    }

    foreach (var attribute in xmlDocument.Attributes())
    {
        if (!attribute.IsNamespaceDeclaration)
        {
            xElement.Add(attribute);
        }
    }

    return xElement;
}

How many socket connections can a web server handle?

This question is a fairly difficult one. There is no real software limitation on the number of active connections a machine can have, though some OS's are more limited than others. The problem becomes one of resources. For example, let's say a single machine wants to support 64,000 simultaneous connections. If the server uses 1MB of RAM per connection, it would need 64GB of RAM. If each client needs to read a file, the disk or storage array access load becomes much larger than those devices can handle. If a server needs to fork one process per connection then the OS will spend the majority of its time context switching or starving processes for CPU time.

The C10K problem page has a very good discussion of this issue.

How to round the corners of a button

Pushing to the limits corner radius up to get a circle:

    self.btnFoldButton.layer.cornerRadius = self.btnFoldButton.frame.height/2.0;

enter image description here

If button frame is an square it does not matter frame.height or frame.width. Otherwise use the largest of both ones.

Objective C - Assign, Copy, Retain

  1. assign

    • assign is a default property attribute
    • assign is a property attribute tells the compiler how to synthesize the property’s setter implementation
  2. copy:

    • copy is required when the object is mutable
    • copy returns an object which you must explicitly release (e.g., in dealloc) in non-garbage collected environments
    • you need to release the object when finished with it because you are retaining the copy
  3. retain:

    • specifies the new value should be sent “-retain” on assignment and the old value sent “-release”
    • if you write retain it will auto work like strong
    • Methods like “alloc” include an implicit “retain”

Printing leading 0's in C

The correct solution is to store the ZIP Code in the database as a STRING. Despite the fact that it may look like a number, it isn't. It's a code, where each part has meaning.

A number is a thing you do arithmetic on. A ZIP Code is not that.

SQL Server Service not available in service list after installation of SQL Server Management Studio

You need to start the SQL Server manually. Press

windows + R

type

sqlservermanager12.msc

right click ->Start

Service configuration does not display SQL Server?

Android: alternate layout xml for landscape mode

I will try to explain it shortly.

First, you may notice that now you should use ConstraintLayout as requested by google (see androix library).

In your android studio projet, you can provide screen-specific layouts by creating additional res/layout/ directories. One for each screen configuration that requires a different layout.

This means you have to use the directory qualifier in both cases :

  • Android device support
  • Android landscape or portrait mode

As a result, here is an exemple :

res/layout/main_activity.xml                # For handsets
res/layout-land/main_activity.xml           # For handsets in landscape
res/layout-sw600dp/main_activity.xml        # For 7” tablets
res/layout-sw600dp-land/main_activity.xml   # For 7” tablets in landscape

You can also use qualifier with res ressources files using dimens.xml.

res/values/dimens.xml                # For handsets
res/values-land/dimens.xml           # For handsets in landscape
res/values-sw600dp/dimens.xml        # For 7” tablets

res/values/dimens.xml

<resources>
    <dimen name="grid_view_item_height">70dp</dimen>
</resources>

res/values-land/dimens.xml

<resources>
    <dimen name="grid_view_item_height">150dp</dimen>
</resources>

your_item_grid_or_list_layout.xml

<androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/constraintlayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content

    <ImageView
            android:id="@+id/image"
            android:layout_width="0dp"
            android:layout_height="@dimen/grid_view_item_height"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:background="@drawable/border"
            android:src="@drawable/ic_menu_slideshow">

</androidx.constraintlayout.widget.ConstraintLayout>

Source : https://developer.android.com/training/multiscreen/screensizes

How to control the width of select tag?

USE style="max-width:90%;"

<select name=countries  style="max-width:90%;">
 <option value=af>Afghanistan</option>
 <option value=ax>Åland Islands</option>
 ...
 <option value=gs>South Georgia and the South Sandwich Islands</option>
 ...
</select>  

LIVE DEMO

How do I replicate a \t tab space in HTML?

This simple formula should work. Give the element whose text will contain a tab the following CSS property: white-space:pre. Otherwise your html may not render tabs at all. Then, wherever you want to have a tab in your text, type &#9;.

Since you didn't mention CSS, if you want to do this without a CSS file, just use

<tag-name style="white-space:pre">text in element&#9;more text</tag-name>

in your HTML.

Open page in new window without popup blocking

function openLinkNewTab (url){
    $('body').append('<a id="openLinkNewTab" href="' + url + '" target="_blank"><span></span></a>').find('#openLinkNewTab span').click().remove();
}

Go doing a GET request and building the Querystring

Using NewRequest just to create an URL is an overkill. Use the net/url package:

package main

import (
    "fmt"
    "net/url"
)

func main() {
    base, err := url.Parse("http://www.example.com")
    if err != nil {
        return
    }

    // Path params
    base.Path += "this will get automatically encoded"

    // Query params
    params := url.Values{}
    params.Add("q", "this will get encoded as well")
    base.RawQuery = params.Encode() 

    fmt.Printf("Encoded URL is %q\n", base.String())
}

Playground: https://play.golang.org/p/YCTvdluws-r

How to solve the memory error in Python

Simplest solution: You're probably running out of virtual address space (any other form of error usually means running really slowly for a long time before you finally get a MemoryError). This is because a 32 bit application on Windows (and most OSes) is limited to 2 GB of user mode address space (Windows can be tweaked to make it 3 GB, but that's still a low cap). You've got 8 GB of RAM, but your program can't use (at least) 3/4 of it. Python has a fair amount of per-object overhead (object header, allocation alignment, etc.), odds are the strings alone are using close to a GB of RAM, and that's before you deal with the overhead of the dictionary, the rest of your program, the rest of Python, etc. If memory space fragments enough, and the dictionary needs to grow, it may not have enough contiguous space to reallocate, and you'll get a MemoryError.

Install a 64 bit version of Python (if you can, I'd recommend upgrading to Python 3 for other reasons); it will use more memory, but then, it will have access to a lot more memory space (and more physical RAM as well).

If that's not enough, consider converting to a sqlite3 database (or some other DB), so it naturally spills to disk when the data gets too large for main memory, while still having fairly efficient lookup.

Fancybox doesn't work with jQuery v1.9.0 [ f.browser is undefined / Cannot read property 'msie' ]

Hi this is due to new version of the jQuery => 1.9.0

you can check the update : http://blog.jquery.com/2013/01/15/jquery-1-9-final-jquery-2-0-beta-migrate-final-released/

jQuery.Browser is deprecated. you can keep latest version by adding a migration script : http://code.jquery.com/jquery-migrate-1.0.0.js

replace :

<script src="http://code.jquery.com/jquery-latest.js"></script>

by :

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.0.0.js"></script>

in your page and its working.

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

Timmy Franks had it right for me. We just had the issue today where the client had IE8 company-wide, and it was forcing the site we wrote for their intranet into compatibility mode. Setting "IE-Edge" seemed to fix it.

<httpProtocol>
  <customHeaders>
    <clear />
    <add name="X-UA-Compatible" value="IE=Edge" />
  </customHeaders>
</httpProtocol>

Run "mvn clean install" in Eclipse

Right click on pom.xml, Run As, you should see the list of m2 options if you have Maven installed, you can select Maven Clean from there

Calculate age given the birth date in the format YYYYMMDD

I've checked the examples showed before and they didn't worked in all cases, and because of this i made a script of my own. I tested this, and it works perfectly.

function getAge(birth) {
   var today = new Date();
   var curr_date = today.getDate();
   var curr_month = today.getMonth() + 1;
   var curr_year = today.getFullYear();

   var pieces = birth.split('/');
   var birth_date = pieces[0];
   var birth_month = pieces[1];
   var birth_year = pieces[2];

   if (curr_month == birth_month && curr_date >= birth_date) return parseInt(curr_year-birth_year);
   if (curr_month == birth_month && curr_date < birth_date) return parseInt(curr_year-birth_year-1);
   if (curr_month > birth_month) return parseInt(curr_year-birth_year);
   if (curr_month < birth_month) return parseInt(curr_year-birth_year-1);
}

var age = getAge('18/01/2011');
alert(age);

How to create an HTML button that acts like a link?

Also you can use a button:

For example, in ASP.NET Core syntax:

// Some other tags
 <form method="post">
      <input asp-for="YourModelPropertyOrYourMethodInputName"
      value="@TheValue" type="hidden" />
      <button type="submit" class="link-button" formaction="/TheDestinationController/TheDestinationActionMethod">
      @(TextValue)
      </button>
  </form>
// Other tags...


<style>
       .link-button {
        background: none !important;
        border: none;
        padding: 0 !important;
        color: #20a8d8;
        cursor: pointer;
    }
</style>

using sql count in a case statement

Depending on you flavor of SQL, you can also imply the else statement in your aggregate counts.

For example, here's a simple table Grades:

| Letters |
|---------|
| A       |
| A       |
| B       |
| C       |

We can test out each Aggregate counter syntax like this (Interactive Demo in SQL Fiddle):

SELECT
    COUNT(CASE WHEN Letter = 'A' THEN 1 END)           AS [Count - End],
    COUNT(CASE WHEN Letter = 'A' THEN 1 ELSE NULL END) AS [Count - Else Null],
    COUNT(CASE WHEN Letter = 'A' THEN 1 ELSE 0 END)    AS [Count - Else Zero],
    SUM(CASE WHEN Letter = 'A' THEN 1 END)             AS [Sum - End],
    SUM(CASE WHEN Letter = 'A' THEN 1 ELSE NULL END)   AS [Sum - Else Null],
    SUM(CASE WHEN Letter = 'A' THEN 1 ELSE 0 END)      AS [Sum - Else Zero]
FROM Grades

And here are the results (unpivoted for readability):

|    Description    | Counts |
|-------------------|--------|
| Count - End       |    2   |
| Count - Else Null |    2   |
| Count - Else Zero |    4   | *Note: Will include count of zero values
| Sum - End         |    2   |
| Sum - Else Null   |    2   |
| Sum - Else Zero   |    2   |

Which lines up with the docs for Aggregate Functions in SQL

Docs for COUNT:

COUNT(*) - returns the number of items in a group. This includes NULL values and duplicates.
COUNT(ALL expression) - evaluates expression for each row in a group, and returns the number of nonnull values.
COUNT(DISTINCT expression) - evaluates expression for each row in a group, and returns the number of unique, nonnull values.

Docs for SUM:

ALL - Applies the aggregate function to all values. ALL is the default.
DISTINCT - Specifies that SUM return the sum of unique values.

Binding multiple events to a listener (without JQuery)?

I have a simpler solution for you:

window.onload = window.onresize = (event) => {
    //Your Code Here
}

I've tested this an it works great, on the plus side it's compact and uncomplicated like the other examples here.

Is there a no-duplicate List implementation out there?

Off the top of my head, lists allow duplicates. You could quickly implement a UniqueArrayList and override all the add / insert functions to check for contains() before you call the inherited methods. For personal use, you could only implement the add method you use, and override the others to throw an exception in case future programmers try to use the list in a different manner.

Adding a month to a date in T SQL

select * from Reference where reference_dt = DateAdd(month,1,another_date_reference)

dplyr change many data types

A more general way of achieving column type transformation is as follows:

If you want to transform all your factor columns to character columns, e.g., this can be done using one pipe:

df %>%  mutate_each_( funs(as.character(.)), names( .[,sapply(., is.factor)] ))

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

Definitely use integer types for your money computations.
This cannot be emphasized enough since at first glance it might seem that a floating point type is adequate.

Here an example in python code:

>>> amount = float(100.00) # one hundred dollars
>>> print amount
100.0
>>> new_amount = amount + 1
>>> print new_amount
101.0
>>> print new_amount - amount
>>> 1.0

looks pretty normal.

Now try this again with 10^20 Zimbabwe dollars:

>>> amount = float(1e20)
>>> print amount
1e+20
>>> new_amount = amount + 1
>>> print new_amount
1e+20
>>> print new_amount-amount
0.0

As you can see, the dollar disappeared.

If you use the integer type, it works fine:

>>> amount = int(1e20)
>>> print amount
100000000000000000000
>>> new_amount = amount + 1
>>> print new_amount
100000000000000000001
>>> print new_amount - amount
1

CORS Access-Control-Allow-Headers wildcard being ignored?

I found that Access-Control-Allow-Headers: * should be set ONLY for OPTIONS request. If you return it for POST request then browser cancel the request (at least for chrome)

The following PHP code works for me

// Allow CORS
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');    
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); 
}   
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    header("Access-Control-Allow-Headers: *");
}

I found similar questions with some misleading response:

  • Server thread says that this is 2 years bug of chrome: Access-Control-Allow-Headers does not match with localhost. It's wrong: I can use CORS to my local server with Post normally
  • Access-Control-Allow-Headers does accept wildcards. It's also wrong, wildcard works for me (I tested only with Chrome)

This take me half day to figure out the issue.

Happy coding

Prevent row names to be written to file when using write.csv

write.csv(t, "t.csv", row.names=FALSE)

From ?write.csv:

row.names: either a logical value indicating whether the row names of
          ‘x’ are to be written along with ‘x’, or a character vector
          of row names to be written.

How do I add a custom script to my package.json file that runs a javascript file?

Example:

  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build --prod",
    "build_c": "ng build --prod && del \"../../server/front-end/*.*\" /s /q & xcopy /s dist \"../../server/front-end\"",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },

As you can see, the script "build_c" is building the angular application, then deletes all old files from a directory, then finally copies the result build files.

text-align:center won't work with form <label> tag (?)

label is an inline element so its width is equal to the width of the text it contains. The browser is actually displaying the label with text-align:center but since the label is only as wide as the text you don't notice.

The best thing to do is to apply a specific width to the label that is greater than the width of the content - this will give you the results you want.

How to simulate browsing from various locations?

This is a bit of self promotion, but I built a tool to do just this that you might find useful, called GeoPeeker.

It remotely accesses a site from servers spread around the world, renders the page with webkit and sends back an image. It will also report the IP address and DNS information of the site as it appears from that location.

There are no ads, and it's very stream-lined to serve this one purpose. It's still in development, and feedback is welcome. Here's hoping somebody besides myself finds it useful!

How to write a test which expects an Error to be thrown in Jasmine?

I replace Jasmine's toThrow matcher with the following, which lets you match on the exception's name property or its message property. For me this makes tests easier to write and less brittle, as I can do the following:

throw {
   name: "NoActionProvided",
   message: "Please specify an 'action' property when configuring the action map."
}

and then test with the following:

expect (function () {
   .. do something
}).toThrow ("NoActionProvided");

This lets me tweak the exception message later without breaking tests, when the important thing is that it threw the expected type of exception.

This is the replacement for toThrow that allows this:

jasmine.Matchers.prototype.toThrow = function(expected) {
  var result = false;
  var exception;
  if (typeof this.actual != 'function') {
    throw new Error('Actual is not a function');
  }
  try {
    this.actual();
  } catch (e) {
    exception = e;
  }
  if (exception) {
      result = (expected === jasmine.undefined || this.env.equals_(exception.message || exception, expected.message || expected) || this.env.equals_(exception.name, expected));
  }

  var not = this.isNot ? "not " : "";

  this.message = function() {
    if (exception && (expected === jasmine.undefined || !this.env.equals_(exception.message || exception, expected.message || expected))) {
      return ["Expected function " + not + "to throw", expected ? expected.name || expected.message || expected : " an exception", ", but it threw", exception.name || exception.message || exception].join(' ');
    } else {
      return "Expected function to throw an exception.";
    }
  };

  return result;
};

How do I use spaces in the Command Prompt?

You should try using quotes.

cmd /C "C:\Program Files (x86)\WinRar\Rar.exe" a "D:\Hello 2\File.rar" "D:\Hello 2\*.*"

What is the difference between persist() and merge() in JPA and Hibernate?

This is coming from JPA. In a very simple way:

  • persist(entity) should be used with totally new entities, to add them to DB (if entity already exists in DB there will be EntityExistsException throw).

  • merge(entity) should be used, to put entity back to persistence context if the entity was detached and was changed.

Programmatically open new pages on Tabs

You can, in Firefox it works, add the attribute target="_newtab" to the anchor to force the opening of a new tab.

<a href="some url" target="_newtab">content of the anchor</a>

In javascript you can use

window.open('page.html','_newtab');

Said that, I partially agree with Sam. You shouldn't force user to open new pages or new tab without showing them a hint on what is going to happen before they click on the link.

Let me know if it works on other browser too (I don't have a chance to try it on other browser than Firefox at the moment).

Edit: added reference for ie7 Maybe this link can be useful
http://social.msdn.microsoft.com/forums/en-US/ieextensiondevelopment/thread/951b04e4-db0d-4789-ac51-82599dc60405/

Getting reference to the top-most view/window in iOS application

Usually that will give you the top view, but there's no guarantee that it's visible to the user. It could be off the screen, have an alpha of 0.0, or could be have size of 0x0 for example.

It could also be that the keyWindow has no subviews, so you should probably test for that first. This would be unusual, but it's not impossible.

UIWindow is a subclass of UIView, so if you want to make sure your notification is visible to the user, you can add it directly to the keyWindow using addSubview: and it will instantly be the top most view. I'm not sure if this is what you're looking to do though. (Based on your question, it looks like you already know this.)

What is the most effective way for float and double comparison?

/// testing whether two doubles are almost equal. We consider two doubles
/// equal if the difference is within the range [0, epsilon).
///
/// epsilon: a positive number (supposed to be small)
///
/// if either x or y is 0, then we are comparing the absolute difference to
/// epsilon.
/// if both x and y are non-zero, then we are comparing the relative difference
/// to epsilon.
bool almost_equal(double x, double y, double epsilon)
{
    double diff = x - y;
    if (x != 0 && y != 0){
        diff = diff/y; 
    }

    if (diff < epsilon && -1.0*diff < epsilon){
        return true;
    }
    return false;
}

I used this function for my small project and it works, but note the following:

Double precision error can create a surprise for you. Let's say epsilon = 1.0e-6, then 1.0 and 1.000001 should NOT be considered equal according to the above code, but on my machine the function considers them to be equal, this is because 1.000001 can not be precisely translated to a binary format, it is probably 1.0000009xxx. I test it with 1.0 and 1.0000011 and this time I get the expected result.

How to tell whether a point is to the right or left side of a line

I wanted to provide with a solution inspired by physics.

Imagine a force applied along the line and you are measuring the torque of the force about the point. If the torque is positive (counterclockwise) then the point is to the "left" of the line, but if the torque is negative the point is the "right" of the line.

So if the force vector equals the span of the two points defining the line

fx = x_2 - x_1
fy = y_2 - y_1

you test for the side of a point (px,py) based on the sign of the following test

var torque = fx*(py-y_1)-fy*(px-x_1)
if  torque>0  then
     "point on left side"
else if torque <0 then
     "point on right side"  
else
     "point on line"
end if

Is it fine to have foreign key as primary key?

Yes, a foreign key can be a primary key in the case of one to one relationship between those tables

Express.js - app.listen vs server.listen

The second form (creating an HTTP server yourself, instead of having Express create one for you) is useful if you want to reuse the HTTP server, for example to run socket.io within the same HTTP server instance:

var express = require('express');
var app     = express();
var server  = require('http').createServer(app);
var io      = require('socket.io').listen(server);
...
server.listen(1234);

However, app.listen() also returns the HTTP server instance, so with a bit of rewriting you can achieve something similar without creating an HTTP server yourself:

var express   = require('express');
var app       = express();

// app.use/routes/etc...

var server    = app.listen(3033);
var io        = require('socket.io').listen(server);

io.sockets.on('connection', function (socket) {
  ...
});

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0

TL;DR

  1. npm uninstall node-sass
  2. npm install [email protected]

Or, if using yarn (default in newer CRA versions)

  1. yarn remove node-sass
  2. yarn add [email protected]

Edit2: sass-loader v10.0.5 fixes it. Problem is, you might not be using it as a project dependency, but more as a dependency of your dependencies. CRA uses a fixed version, angular-cli locks to node-sass v4 an so on.
The recommendation for now is: if you're installing just node-sass check below workaround (and the note). If you're working on a blank project and you can manage your webpack configuration (not using CRA or a CLI to scaffold your project) install latest sass-loader.


Edit: this error comes from sass-loader. There is a semver mismatch since node-sass @latest is v5.0.0 and sass-loader expects ^4.0.0.
There is an open issue on their repository with an associated fix that needs to be reviewed. Until then, refer to the solution below.


Workaround: don't install node-sass 5.0.0 yet (major version was just bumped).

Uninstall node-sass

npm uninstall node-sass

Then install the latest version (before 5.0)

npm install [email protected]


Note: LibSass (hence node-sass as well) is deprecated and dart-sass is the recommended implementation. You can use sass instead, which is a node distribution of dart-sass compiled to pure JavaScript. Be warned though:

Be careful using this approach. React-scripts uses sass-loader v8, which prefers node-sass to sass (which has some syntax not supported by node-sass). If both are installed and the user worked with sass, this could lead to errors on css compilation

Update R using RStudio

For completeness, the answer is: you can't do that from within RStudio. @agstudy has it right - you need to install the newer version of R, then restart RStudio and it will automagically use the new version, as @Brandon noted.

It would be great if there was an update.R() function, analogous to the install.packages() function or the update.packages(function).

So, in order to install R,

  1. go to http://www.r-project.org,
  2. click on 'CRAN',
  3. then choose the CRAN site that you like. I like Kansas: http://rweb.quant.ku.edu/cran/.
  4. click on 'Download R for XXX' [where XXX is your operating system]
  5. follow the installation procedure for your operating system
  6. restart RStudio
  7. rejoice

--wait - what about my beloved packages??--

ok, I use a Mac, so I can only provide accurate details for the Mac - perhaps someone else can provide the accurate paths for windows/linux; I believe the process will be the same.

To ensure that your packages work with your shiny new version of R, you need to:

  1. move the packages from the old R installation into the new version; on Mac OSX, this means moving all folders from here:

    /Library/Frameworks/R.framework/Versions/2.15/Resources/library
    

    to here:

    /Library/Frameworks/R.framework/Versions/3.0/Resources/library
    

    [where you'll replace "2.15" and "3.0" with whatever versions you're upgrading from and to. And only copy whatever packages aren't already in the destination directory. i.e. don't overwrite your new 'base' package with your old one - if you did, don't worry, we'll fix it in the next step anyway. If those paths don't work for you, try using installed.packages() to find the proper pathnames.]

  2. now you can update your packages by typing update.packages() in your RStudio console, and answering 'y' to all of the prompts.

    > update.packages(checkBuilt=TRUE)
    class :
     Version 7.3-7 installed in /Library/Frameworks/R.framework/Versions/3.0/Resources/library 
     Version 7.3-8 available at http://cran.rstudio.com
    Update (y/N/c)?  y
    ---etc---
    
  3. finally, to reassure yourself that you have done everything, type these two commands in the RStudio console to see what you have got:

    > version
    > packageStatus()
    

How to convert enum names to string in c

You don't need to rely on the preprocessor to ensure your enums and strings are in sync. To me using macros tend to make the code harder to read.

Using Enum And An Array Of Strings

enum fruit                                                                   
{
    APPLE = 0, 
    ORANGE, 
    GRAPE,
    BANANA,
    /* etc. */
    FRUIT_MAX                                                                                                                
};   

const char * const fruit_str[] =
{
    [BANANA] = "banana",
    [ORANGE] = "orange",
    [GRAPE]  = "grape",
    [APPLE]  = "apple",
    /* etc. */  
};

Note: the strings in the fruit_str array don't have to be declared in the same order as the enum items.

How To Use It

printf("enum apple as a string: %s\n", fruit_str[APPLE]);

Adding A Compile Time Check

If you are afraid to forget one string, you can add the following check:

#define ASSERT_ENUM_TO_STR(sarray, max) \                                       
  typedef char assert_sizeof_##max[(sizeof(sarray)/sizeof(sarray[0]) == (max)) ? 1 : -1]

ASSERT_ENUM_TO_STR(fruit_str, FRUIT_MAX);

An error would be reported at compile time if the amount of enum items does not match the amount of strings in the array.

How to set array length in c# dynamically

Use Array.CreateInstance to create an array dynamically.

    private Update BuildMetaData(MetaData[] nvPairs)
    {
        Update update = new Update();
        InputProperty[] ip = Array.CreateInstance(typeof(InputProperty), nvPairs.Count()) as InputProperty[];
        int i;
        for (i = 0; i < nvPairs.Length; i++)
        {
            if (nvPairs[i] == null) break;
            ip[i] = new InputProperty();
            ip[i].Name = "udf:" + nvPairs[i].Name;
            ip[i].Val = nvPairs[i].Value;
        }
        update.Items = ip;
        return update;
    }

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

With rails >= 3.0, you can simply use the placeholder option.

f.text_field :attr, placeholder: "placeholder text"

Spring @Transactional read-only propagation

Calling readOnly=false from readOnly=true doesn't work since the previous transaction continues.

In your example, the handle() method on your service layer is starting a new read-write transaction. If the handle method in turn calls service methods that annotated read-only, the read-only will take no effect as they will participate in the existing read-write transaction instead.

If it is essential for those methods to be read-only, then you can annotate them with Propagation.REQUIRES_NEW, and they will then start a new read-only transaction rather than participate in the existing read-write transaction.

Here is a worked example, CircuitStateRepository is a spring-data JPA repository.

BeanS calls a transactional=read-only Bean1, which does a lookup and calls transactional=read-write Bean2 which saves a new object.

  • Bean1 starts a read-only tx.

31 09:39:44.199 [pool-1-thread-1] DEBUG o.s.orm.jpa.JpaTransactionManager - Creating new transaction with name [nz.co.vodafone.wcim.business.Bean1.startSomething]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''

  • Bean 2 pariticipates in it.

    31 09:39:44.230 [pool-1-thread-1] DEBUG o.s.orm.jpa.JpaTransactionManager - Participating in existing transaction

    Nothing is committed to the database.

Now change Bean2 @Transactional annotation to add propagation=Propagation.REQUIRES_NEW

  • Bean1 starts a read-only tx.

    31 09:31:36.418 [pool-1-thread-1] DEBUG o.s.orm.jpa.JpaTransactionManager - Creating new transaction with name [nz.co.vodafone.wcim.business.Bean1.startSomething]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''

  • Bean2 starts a new read-write tx

    31 09:31:36.449 [pool-1-thread-1] DEBUG o.s.orm.jpa.JpaTransactionManager - Suspending current transaction, creating new transaction with name [nz.co.vodafone.wcim.business.Bean2.createSomething]

And the changes made by Bean2 are now committed to the database.

Here's the example, tested with spring-data, hibernate and oracle.

@Named
public class BeanS {    
    @Inject
    Bean1 bean1;

    @Scheduled(fixedRate = 20000)
    public void runSomething() {
        bean1.startSomething();
    }
}

@Named
@Transactional(readOnly = true)
public class Bean1 {    
    Logger log = LoggerFactory.getLogger(Bean1.class);

    @Inject
    private CircuitStateRepository csr;

    @Inject
    private Bean2 bean2;

    public void startSomething() {    
        Iterable<CircuitState> s = csr.findAll();
        CircuitState c = s.iterator().next();
        log.info("GOT CIRCUIT {}", c.getCircuitId());
        bean2.createSomething(c.getCircuitId());    
    }
}

@Named
@Transactional(readOnly = false)
public class Bean2 {    
    @Inject
    CircuitStateRepository csr;

    public void createSomething(String circuitId) {
        CircuitState c = new CircuitState(circuitId + "-New-" + new DateTime().toString("hhmmss"), new DateTime());

        csr.save(c);
     }
}

MISCONF Redis is configured to save RDB snapshots

Restart your redis server.

  • macOS (brew): brew services restart redis.
  • Linux: sudo service redis restart / sudo systemctl restart redis
  • Windows: Windows + R -> Type services.msc, Enter -> Search for Redis then click on restart.

I personally had this issue after upgrading redis with Brew (brew upgrade). After rebooting the laptop, it immediately worked.

MySQL: View with Subquery in the FROM Clause Limitation

You can work around this by creating a separate VIEW for any subquery you want to use and then join to that in the VIEW you're creating. Here's an example: http://blog.gruffdavies.com/2015/01/25/a-neat-mysql-hack-to-create-a-view-with-subquery-in-the-from-clause/

This is quite handy as you'll very likely want to reuse it anyway and helps you keep your SQL DRY.

Specific Time Range Query in SQL Server

I'm assuming you want all three of those as part of the selection criteria. You'll need a few statements in your where but they will be similar to the link your question contained.

SELECT *
  FROM MyTable
  WHERE [dateColumn] > '3/1/2009' AND [dateColumn] <= DATEADD(day,1,'3/31/2009') 
        --make it inclusive for a datetime type
    AND DATEPART(hh,[dateColumn]) >= 6 AND DATEPART(hh,[dateColumn]) <= 22 
        -- gets the hour of the day from the datetime
    AND DATEPART(dw,[dateColumn]) >= 3 AND DATEPART(dw,[dateColumn]) <= 5 
        -- gets the day of the week from the datetime

Hope this helps.

Batch Files - Error Handling

A successful ping on your local network can be trapped using ERRORLEVEL.

@ECHO OFF
PING 10.0.0.123
IF ERRORLEVEL 1 GOTO NOT-THERE
ECHO IP ADDRESS EXISTS
PAUSE
EXIT
:NOT-THERE
ECHO IP ADDRESS NOT NOT EXIST
PAUSE
EXIT

How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?

This will work even if you have two or more rows for each home with equal DATETIME's:

SELECT id, home, datetime, player, resource
FROM   (
       SELECT (
              SELECT  id
              FROM    topten ti
              WHERE   ti.home = t1.home
              ORDER BY
                      ti.datetime DESC
              LIMIT 1
              ) lid
       FROM   (
              SELECT  DISTINCT home
              FROM    topten
              ) t1
       ) ro, topten t2
WHERE  t2.id = ro.lid

Cannot catch toolbar home button click event

The easiest approach we could do is change the home icon to a known icon and compare drawables (because android.R.id.home icon can differ to different api versions

so set a toolbar as actionbar SetSupportActionBar(_toolbar);

_toolbar.NavigationIcon = your_known_drawable_here;

   for (int i = 0; i < _toolbar.ChildCount; i++)
            {
                View v = _toolbar.GetChildAt(i);
                if (v is ImageButton)
                {
                    ImageButton imageButton = v as ImageButton;

                    if (imageButton.Drawable.GetConstantState().Equals(_bookMarkIcon.GetConstantState()))
                    {
                       //here v is the widget that contains the home  icon you can add your click events here 
                    }
                }
            }

Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)

Matthew's supremely efficient script updated to use the dm_exec_sessions DMV, replacing the deprecated sysprocesses system table:

USE [master];
GO

DECLARE @Kill VARCHAR(8000) = '';

SELECT
    @Kill = @Kill + 'kill ' + CONVERT(VARCHAR(5), session_id) + ';'
FROM
    sys.dm_exec_sessions
WHERE
    database_id = DB_ID('<YourDB>');

EXEC sys.sp_executesql @Kill;

Alternative using WHILE loop (if you want to process any other operations per execution):

USE [master];
GO

DECLARE @DatabaseID SMALLINT = DB_ID(N'<YourDB>');    
DECLARE @SQL NVARCHAR(10);

WHILE EXISTS ( SELECT
                1
               FROM
                sys.dm_exec_sessions
               WHERE
                database_id = @DatabaseID )    
    BEGIN;
        SET @SQL = (
                    SELECT TOP 1
                        N'kill ' + CAST(session_id AS NVARCHAR(5)) + ';'
                    FROM
                        sys.dm_exec_sessions
                    WHERE
                        database_id = @DatabaseID
                   );
        EXEC sys.sp_executesql @SQL;
    END;

How can I get a first element from a sorted list?

If you just want to get the minimum of a list, instead of sorting it and then getting the first element (O(N log N)), you can use do it in linear time using min:

<T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll)

That looks gnarly at first, but looking at your previous questions, you have a List<String>. In short: min works on it.

For the long answer: all that super and extends stuff in the generic type constraints is what Josh Bloch calls the PECS principle (usually presented next to a picture of Arnold -- I'M NOT KIDDING!)

Producer Extends, Consumer Super

It essentially makes generics more powerful, since the constraints are more flexible while still preserving type safety (see: what is the difference between ‘super’ and ‘extends’ in Java Generics)

"Missing return statement" within if / for / while

This will return the string only if the condition is true.

public String myMethod()
{
    if(condition)
    {
       return x;
    }
    else
       return "";
}

An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module

Add following codesnippet in your cofig file

<startup useLegacyV2RuntimeActivationPolicy="true">
   <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>

Run an Ansible task only when the variable contains a specific string

use this

when: "{{ 'value' in variable1}}"

instead of

when: "'value' in {{variable1}}"

Also for string comparison you can use

when: "{{ variable1 == 'value' }}"

What's the difference between map() and flatMap() methods in Java 8?

Please go through the post fully to get a clear idea,

map vs flatMap:

To return a length of each word from a list, we would do something like below..

Short Version given below

When we collect two lists, given below

Without flat map => [1,2],[1,1] => [[1,2],[1,1]] Here two lists are placed inside a list, so the output will be list containing lists

With flat map => [1,2],[1,1] => [1,2,1,1] Here two lists are flattened and only the values are placed in list, so the output will be list containing only elements

Basically it merges all the objects in to one

## Detailed Version has been given below:-

For example:-
Consider a list [“STACK”, ”OOOVVVER”] and we are trying to return a list like [“STACKOVER”](returning only unique letters from that list) Initially, we would do something like below to return a list [“STACKOVER”] from [“STACK”, ”OOOVVVER”]

public class WordMap {
  public static void main(String[] args) {
    List<String> lst = Arrays.asList("STACK","OOOVER");
    lst.stream().map(w->w.split("")).distinct().collect(Collectors.toList());
  }
}

Here the issue is, Lambda passed to the map method returns a String array for each word, So the stream returned by the map method is actually of type Stream, But what we need is Stream to represent a stream of characters, below image illustrates the problem.

Figure A:

enter image description here

You might think that, We can resolve this problem using flatmap,
OK, let us see how to solve this by using map and Arrays.stream First of all you gonna need a stream of characters instead of a stream of arrays. There is a method called Arrays.stream() that would take an array and produces a stream, for example:

String[] arrayOfWords = {"STACK", "OOOVVVER"};
Stream<String> streamOfWords = Arrays.stream(arrayOfWords);
streamOfWords.map(s->s.split("")) //Converting word in to array of letters
    .map(Arrays::stream).distinct() //Make array in to separate stream
    .collect(Collectors.toList());

The above still does not work, because we now end up with a list of streams (more precisely, Stream>), Instead, we must first convert each word into an array of individual letters and then make each array into a separate stream

By using flatMap we should be able to fix this problem as below:

String[] arrayOfWords = {"STACK", "OOOVVVER"};
Stream<String> streamOfWords = Arrays.stream(arrayOfWords);
streamOfWords.map(s->s.split("")) //Converting word in to array of letters
    .flatMap(Arrays::stream).distinct() //flattens each generated stream in to a single stream
    .collect(Collectors.toList());

flatMap would perform mapping each array not with stream but with the contents of that stream. All of the individual streams that would get generated while using map(Arrays::stream) get merged into a single stream. Figure B illustrates the effect of using the flatMap method. Compare it with what map does in figure A. Figure B enter image description here

The flatMap method lets you replace each value of a stream with another stream and then joins all the generated streams into a single stream.

Adding a right click menu to an item

If you are using Visual Studio, there is a GUI solution as well:

  1. From Toolbox add a ContextMenuStrip
  2. Select the context menu and add the right click items
  3. For each item set the click events to the corresponding functions
  4. Select the form / button / image / etc (any item) that the right click menu will be connected
  5. Set its ContextMenuStrip property to the menu you have created.

Initialise a list to a specific length in Python

If the "default value" you want is immutable, @eduffy's suggestion, e.g. [0]*10, is good enough.

But if you want, say, a list of ten dicts, do not use [{}]*10 -- that would give you a list with the same initially-empty dict ten times, not ten distinct ones. Rather, use [{} for i in range(10)] or similar constructs, to construct ten separate dicts to make up your list.

Understanding string reversal via slicing

It's using extended slicing - a string is a sequence in Python, and shares some methods with other sequences (namely lists and tuples). There are three parts to slicing - start, stop and step. All of them have default values - start defaults to 0, stop defaults to len(sequence), and step defaults to 1. By specifying [::-1] you're saying "all the elements in sequence a, starting from the beginning, to the end going backward one at a time.

This feature was introduced in Python 2.3.5, and you can read more in the What's New docs.

How do I rename a Git repository?

Git itself has no provision to specify the repository name. The root directory's name is the single source of truth pertaining to the repository name.

The .git/description though is used only by some applications, like GitWeb.

Jackson: how to prevent field serialization

One should ask why you would want a public getter method for the password. Hibernate, or any other ORM framework, will do with a private getter method. For checking whether the password is correct, you can use

public boolean checkPassword(String password){
  return this.password.equals(anyHashingMethod(password));
}

Upgrading PHP in XAMPP for Windows?

I have upgraded to php7.2 from php5.6

Steps which I followed.

  1. Download PHP binary from here. I have downloaded VC15 x86 Thread Safe Zip file.
  2. Created a backup of xampp/php folder.
  3. Extract all the contents of zip file to xampp/php folder.
  4. Copied php.ini (as I have modified it before and I want my configuration back, if you were using default one then skip this step.)
  5. Edit below file

C:\xampp\apache\conf\extra\http-xampp.conf

5.1. Replace

LoadFile "C:/xampp/php/php5ts.dll"

LoadFile "C:/xampp/php/libpq.dll"

LoadModule php5_module "C:/xampp/php/php5apache2_4.dll"

to

LoadFile "C:/xampp/php/php7ts.dll"

LoadFile "C:/xampp/php/libpq.dll"

LoadModule php7_module "C:/xampp/php/php7apache2_4.dll"

  1. Restart Apache

href="javascript:" vs. href="javascript:void(0)"

It does not cause problems but it's a trick to do the same as PreventDefault

when you're way down in the page and an anchor as:

<a href="#" onclick="fn()">click here</a>

you will jump to the top and the URL will have the anchor # as well, to avoid this we simply return false; or use javascript:void(0);

regarding your examples

<a onclick="fn()">Does not appear as a link, because there's no href</a>

just do a {text-decoration:underline;} and you will have "link a-like"

<a href="javascript:void(0)" onclick="fn()">fn is called</a>
<a href="javascript:" onclick="fn()">fn is called too!</a>

it's ok, but in your function at the end, just return false; to prevent the default behavior, you don't need to do anything more.

Java - Getting Data from MySQL database

Easy Java method to get data from MySQL table:

/*
 * CREDIT : WWW.CODENIRVANA.IN
*/

String Data(String query){
    String get=null;
    try{

Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = (Connection)DriverManager.getConnection
("jdbc:mysql://localhost:3306/mysql","root","password");
Statement stmt = (Statement) con.createStatement();
ResultSet rs=stmt.executeQuery(query);
if (rs.next())
       {
get = rs.getString("");
        }

}
catch(Exception e){
JOptionPane.showMessageDialog (this, e.getMessage());
}
    return get;
}

How do I check in JavaScript if a value exists at a certain array index?

I ran into this issue using laravel datatables. I was storing a JSON value called properties in an activity log and wanted to show a button based on this value being empty or not.

Well, datatables was interpreting this as an array if it was empty, and an object if it was not, therefore, the following solution worked for me:

render: function (data, type, full) {
    if (full.properties.length !== 0) {
        // do stuff
    }
}

An object does not have a length property.

How to add http:// if it doesn't exist in the URL

Simply check if there is a protocol (delineated by "://") and add "http://" if there isn't.

if (false === strpos($url, '://')) {
    $url = 'http://' . $url;
}

Note: This may be a simple and straightforward solution, but Jack's answer using parse_url is almost as simple and much more robust. You should probably use that one.

Checking for empty or null JToken in a JObject

To check whether a property exists on a JObject, you can use the square bracket syntax and see whether the result is null or not. If the property exists, a JToken will be always be returned (even if it has the value null in the JSON).

JToken token = jObject["param"];
if (token != null)
{
    // the "param" property exists
}

If you have a JToken in hand and you want to see if it is non-empty, well, that depends on what type of JToken it is and how you define "empty". I usually use an extension method like this:

public static class JsonExtensions
{
    public static bool IsNullOrEmpty(this JToken token)
    {
        return (token == null) ||
               (token.Type == JTokenType.Array && !token.HasValues) ||
               (token.Type == JTokenType.Object && !token.HasValues) ||
               (token.Type == JTokenType.String && token.ToString() == String.Empty) ||
               (token.Type == JTokenType.Null);
    }
}

MySQL count occurrences greater than 2

SELECT word, COUNT(*) FROM words GROUP by word HAVING COUNT(*) > 1

Validating an XML against referenced XSD in C#

A simpler way, if you are using .NET 3.5, is to use XDocument and XmlSchemaSet validation.

XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add(schemaNamespace, schemaFileName);

XDocument doc = XDocument.Load(filename);
string msg = "";
doc.Validate(schemas, (o, e) => {
    msg += e.Message + Environment.NewLine;
});
Console.WriteLine(msg == "" ? "Document is valid" : "Document invalid: " + msg);

See the MSDN documentation for more assistance.

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`

Add a prop 'key' to the rendering root component of the list.

<ScrollView>
      <List>
          {this.state.nationalities.map((prop, key) => {
             return (
               <ListItem key={key}>
                  <Text>{prop.name}</Text>
               </ListItem>
             );
          })}
      </List>
</ScrollView>

What should I do if the current ASP.NET session is null?

If your Session instance is null and your in an 'ashx' file, just implement the 'IRequiresSessionState' interface.

This interface doesn't have any members so you just need to add the interface name after the class declaration (C#):

public class MyAshxClass : IHttpHandler, IRequiresSessionState

git pull aborted with error filename too long

Open your.gitconfig file to add the longpaths property. So it will look like the following:

[core]
symlinks = false
autocrlf = true
longpaths = true

In Django, how do I check if a user is in a certain group?

In one line:

'Groupname' in user.groups.values_list('name', flat=True)

This evaluates to either True or False.

Combine two columns of text in pandas dataframe

The method cat() of the .str accessor works really well for this:

>>> import pandas as pd
>>> df = pd.DataFrame([["2014", "q1"], 
...                    ["2015", "q3"]],
...                   columns=('Year', 'Quarter'))
>>> print(df)
   Year Quarter
0  2014      q1
1  2015      q3
>>> df['Period'] = df.Year.str.cat(df.Quarter)
>>> print(df)
   Year Quarter  Period
0  2014      q1  2014q1
1  2015      q3  2015q3

cat() even allows you to add a separator so, for example, suppose you only have integers for year and period, you can do this:

>>> import pandas as pd
>>> df = pd.DataFrame([[2014, 1],
...                    [2015, 3]],
...                   columns=('Year', 'Quarter'))
>>> print(df)
   Year Quarter
0  2014       1
1  2015       3
>>> df['Period'] = df.Year.astype(str).str.cat(df.Quarter.astype(str), sep='q')
>>> print(df)
   Year Quarter  Period
0  2014       1  2014q1
1  2015       3  2015q3

Joining multiple columns is just a matter of passing either a list of series or a dataframe containing all but the first column as a parameter to str.cat() invoked on the first column (Series):

>>> df = pd.DataFrame(
...     [['USA', 'Nevada', 'Las Vegas'],
...      ['Brazil', 'Pernambuco', 'Recife']],
...     columns=['Country', 'State', 'City'],
... )
>>> df['AllTogether'] = df['Country'].str.cat(df[['State', 'City']], sep=' - ')
>>> print(df)
  Country       State       City                   AllTogether
0     USA      Nevada  Las Vegas      USA - Nevada - Las Vegas
1  Brazil  Pernambuco     Recife  Brazil - Pernambuco - Recife

Do note that if your pandas dataframe/series has null values, you need to include the parameter na_rep to replace the NaN values with a string, otherwise the combined column will default to NaN.

conflicting types error when compiling c program using gcc

If you don't declare a function and it only appears after being called, it is automatically assumed to be int, so in your case, you didn't declare

void my_print (char *);
void my_print2 (char *);

before you call it in main, so the compiler assume there are functions which their prototypes are int my_print2 (char *); and int my_print2 (char *); and you can't have two functions with the same prototype except of the return type, so you get the error of conflicting types.

As Brian suggested, declare those two methods before main.

JQuery: dynamic height() with window resize()

I feel like there should be a no javascript solution, but how is this?

http://jsfiddle.net/NfmX3/2/

$(window).resize(function() {
    $('#content').height($(window).height() - 46);
});

$(window).trigger('resize');

SQL set values of one column equal to values of another column in the same table

UPDATE YourTable
SET ColumnB=ColumnA
WHERE
ColumnB IS NULL 
AND ColumnA IS NOT NULL

Filtering lists using LINQ

Many thanks for this guys.

I mangaged to get this down to one line:

  var results = from p in People 
                where !(from e in exclusions 
                        select e.CompositeKey).Contains(p.CompositeKey) 
                select p;

Thanks again everyone.

Should I return EXIT_SUCCESS or 0 from main()?

It does not matter. Both are the same.

C++ Standard Quotes:

If the value of status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned.

What exactly is the meaning of an API?

Conaider this situation:

Mark and Lisa are secretly a couple, and because of age difference they are not allowed to be together. Mark and Lisa meet every night when nobody is watching. They have estabilished their own set of rules how to comunicate when the time comes. He stands in her garden and throws the small rock at her window. Lisa knows that it is time, and responds by waving from the window and opening it afterwards so Mark can climb in. That was example how the API works. The rock is initial request to another end. Another end waves, opens the window which basicaly means "Welcome in!".

API is almost like human language but for computers.

How can I add an item to a SelectList in ASP.net MVC

This is possible.

//Create the select list item you want to add
SelectListItem selListItem = new SelectListItem() { Value = "null", Text = "Select One" };

//Create a list of select list items - this will be returned as your select list
List<SelectListItem> newList = new List<SelectListItem>();

//Add select list item to list of selectlistitems
newList.Add(selListItem);

//Return the list of selectlistitems as a selectlist
return new SelectList(newList, "Value", "Text", null);

How to set String's font size, style in Java using the Font class?

Font myFont = new Font("Serif", Font.BOLD, 12);, then use a setFont method on your components like

JButton b = new JButton("Hello World");
b.setFont(myFont);

How to print a float with 2 decimal places in Java?

Try this:-

private static String getDecimalFormat(double value) {

    String getValue = String.valueOf(value).split("[.]")[1];

      if (getValue.length() == 1) {
          return String.valueOf(value).split("[.]")[0] +
                "."+ getValue.substring(0, 1) + 
                String.format("%0"+1+"d", 0);
       } else {
          return String.valueOf(value).split("[.]")[0]
            +"." + getValue.substring(0, 2);
      }


 }

How do I find out what version of Sybase is running

1)From OS level(UNIX):-

dataserver -v

2)From Syabse isql:-

select @@version
go

sp_version
go

Android Studio and Gradle build error

If you are using the Gradle Wrapper (the recommended option in Android Studio), you enable stacktrace by running gradlew compileDebug --stacktrace from the command line in the root folder of your project (where the gradlew file is).

If you are not using the gradle wrapper, you use gradle compileDebug --stacktrace instead (presumably).

You don't really need to run with --stacktrace though, running gradlew compileDebug by itself, from the command line, should tell you where the error is.

I based this information on this comment:

Android Studio new project can not run, throwing error

JQuery to load Javascript file dynamically

Yes, use getScript instead of document.write - it will even allow for a callback once the file loads.

You might want to check if TinyMCE is defined, though, before including it (for subsequent calls to 'Add Comment') so the code might look something like this:

$('#add_comment').click(function() {
    if(typeof TinyMCE == "undefined") {
        $.getScript('tinymce.js', function() {
            TinyMCE.init();
        });
    }
});

Assuming you only have to call init on it once, that is. If not, you can figure it out from here :)

Running Bash commands in Python

Call it with subprocess

import subprocess
subprocess.Popen("cwm --rdf test.rdf --ntriples > test.nt")

The error you are getting seems to be because there is no swap module on the server, you should install swap on the server then run the script again

How to specify different Debug/Release output directories in QMake .pro file

This is my Makefile for different debug/release output directories. This Makefile was tested successfully on Ubuntu linux. It should work seamlessly on Windows provided that Mingw-w64 is installed correctly.

ifeq ($(OS),Windows_NT)
    ObjExt=obj
    mkdir_CMD=mkdir
    rm_CMD=rmdir /S /Q
else
    ObjExt=o
    mkdir_CMD=mkdir -p
    rm_CMD=rm -rf
endif

CC     =gcc
CFLAGS =-Wall -ansi
LD     =gcc

OutRootDir=.
DebugDir  =Debug
ReleaseDir=Release


INSTDIR =./bin
INCLUDE =.

SrcFiles=$(wildcard *.c)
EXEC_main=myapp

OBJ_C_Debug   =$(patsubst %.c,  $(OutRootDir)/$(DebugDir)/%.$(ObjExt),$(SrcFiles))
OBJ_C_Release =$(patsubst %.c,  $(OutRootDir)/$(ReleaseDir)/%.$(ObjExt),$(SrcFiles))

.PHONY: Release Debug cleanDebug cleanRelease clean

# Target specific variables
release: CFLAGS += -O -DNDEBUG
debug:   CFLAGS += -g

################################################
#Callable Targets
release: $(OutRootDir)/$(ReleaseDir)/$(EXEC_main)
debug:   $(OutRootDir)/$(DebugDir)/$(EXEC_main)

cleanDebug:
    -$(rm_CMD) "$(OutRootDir)/$(DebugDir)"
    @echo cleanDebug done

cleanRelease:
    -$(rm_CMD) "$(OutRootDir)/$(ReleaseDir)"
    @echo cleanRelease done

clean: cleanDebug cleanRelease
################################################

# Pattern Rules
# Multiple targets cannot be used with pattern rules [https://www.gnu.org/software/make/manual/html_node/Multiple-Targets.html]
$(OutRootDir)/$(ReleaseDir)/%.$(ObjExt): %.c | $(OutRootDir)/$(ReleaseDir)
    $(CC) -I$(INCLUDE) $(CFLAGS) -c $< -o"$@"

$(OutRootDir)/$(DebugDir)/%.$(ObjExt):   %.c | $(OutRootDir)/$(DebugDir)
    $(CC) -I$(INCLUDE) $(CFLAGS) -c $< -o"$@"

# Create output directory
$(OutRootDir)/$(ReleaseDir) $(OutRootDir)/$(DebugDir) $(INSTDIR):
    -$(mkdir_CMD) $@

# Create the executable
# Multiple targets [https://www.gnu.org/software/make/manual/html_node/Multiple-Targets.html]
$(OutRootDir)/$(ReleaseDir)/$(EXEC_main): $(OBJ_C_Release)
$(OutRootDir)/$(DebugDir)/$(EXEC_main):   $(OBJ_C_Debug)
$(OutRootDir)/$(ReleaseDir)/$(EXEC_main) $(OutRootDir)/$(DebugDir)/$(EXEC_main):
    $(LD) $^ -o$@

Sending Windows key using SendKeys

SetForegroundWindow( /* window to gain focus */ );
SendKeys.SendWait("^{ESC}"); // ^{ESC} is code for ctrl + esc which mimics the windows key.

VideoView Full screen in android application

On Button click start the native video player which will open in full screen:

Intent intent = new Intent(Intent.ACTION_VIEW );
intent.setDataAndType(Uri.parse(path), "video/*");
startActivity(intent);

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

Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

Setting a system environment variable from a Windows batch file?

For XP, I used a (free/donateware) tool called "RAPIDEE" (Rapid Environment Editor), but SETX is definitely sufficient for Win 7 (I did not know about this before).

How to update data in one table from corresponding data in another table in SQL Server 2005

 UPDATE Employee SET Empid=emp3.empid 
 FROM EMP_Employee AS emp3
 WHERE Employee.Empid=emp3.empid

Checking length of dictionary object

var c = {'a':'A', 'b':'B', 'c':'C'};
var count = 0;
for (var i in c) {
   if (c.hasOwnProperty(i)) count++;
}

alert(count);

Set a cookie to never expire

All cookies expire as per the cookie specification, so this is not a PHP limitation.

Use a far future date. For example, set a cookie that expires in ten years:

setcookie(
  "CookieName",
  "CookieValue",
  time() + (10 * 365 * 24 * 60 * 60)
);

Note that if you set a date past 2038 in 32-bit PHP, the number will wrap around and you'll get a cookie that expires instantly.

Default fetch type for one-to-one, many-to-one and one-to-many in Hibernate

To answer your question, Hibernate is an implementation of the JPA standard. Hibernate has its own quirks of operation, but as per the Hibernate docs

By default, Hibernate uses lazy select fetching for collections and lazy proxy fetching for single-valued associations. These defaults make sense for most associations in the majority of applications.

So Hibernate will always load any object using a lazy fetching strategy, no matter what type of relationship you have declared. It will use a lazy proxy (which should be uninitialized but not null) for a single object in a one-to-one or many-to-one relationship, and a null collection that it will hydrate with values when you attempt to access it.

It should be understood that Hibernate will only attempt to fill these objects with values when you attempt to access the object, unless you specify fetchType.EAGER.

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly

In my case, I had to setup the public key for another user, as I already had one for my main user. once I switched users and performed the commands in the link above I was able to perform the setup for my test server without a problem.

JQuery Ajax Post results in 500 Internal Server Error

I found myself having this error to. I had .htaccess redirect configured in a directory. Well it reroutes ajax calls to ofcourse ($.post(../ajax.php)), so it couldn't find the actual file (resulting in 500 error).

I 'fixed' it by placing the ajax.php in a directory (So .htaccess didn't affect).

decompiling DEX into Java sourcecode

It's easy

Get these tools:

  1. dex2jar to translate dex files to jar files

  2. jd-gui to view the java files in the jar

The source code is quite readable as dex2jar makes some optimizations.

Procedure:

And here's the procedure on how to decompile:

Step 1:

Convert classes.dex in test_apk-debug.apk to test_apk-debug_dex2jar.jar

d2j-dex2jar.sh -f -o output_jar.jar apk_to_decompile.apk
d2j-dex2jar.sh -f -o output_jar.jar dex_to_decompile.dex

Note 1: In the Windows machines all the .sh scripts are replaced by .bat scripts

Note 2: On linux/mac don't forget about sh or bash. The full command should be:

sh d2j-dex2jar.sh -f -o output_jar.jar apk_to_decompile.apk 

Note 3: Also, remember to add execute permission to dex2jar-X.X directory e.g. sudo chmod -R +x dex2jar-2.0

dex2jar documentation

Step 2:

Open the jar in JD-GUI

The decompiled source

How to clear all input fields in a specific div with jQuery?

Change this:

 <div class=fetch_results>

To this:

 <div id="fetch_results">

Then the following should work:

$("#fetch_results input").each(function() {
      this.value = "";
  })?

http://jsfiddle.net/NVqeR/

jQuery UI Dialog - missing close icon

I found three fixes:

  1. You can just load bootsrap first. And them load jquery-ui. But it is not good idea. Because you will see errors in console.
  2. This:

    var bootstrapButton = $.fn.button.noConflict();
    $.fn.bootstrapBtn = bootstrapButton;
    

    helps. But other buttons look terrible. And now we don't have bootstrap buttons.

  3. I just want to use bootsrap styles and also I want to have close button with an icon. I've done following:

    How close button looks after fix

    .ui-dialog-titlebar-close {
        padding:0 !important;
    }
    
    .ui-dialog-titlebar-close:after {
        content: '';
        width: 20px;
        height: 20px;
        display: inline-block;
        /* Change path to image*/
        background-image: url(themes/base/images/ui-icons_777777_256x240.png);
        background-position: -96px -128px;
        background-repeat: no-repeat;
    }
    

Sleeping in a batch file

The Resource Kit has always included this. At least since Windows 2000.

Also, the Cygwin package has a sleep - plop that into your PATH and include the cygwin.dll (or whatever it's called) and way to go!

Apply global variable to Vuejs

You can use a Global Mixin to affect every Vue instance. You can add data to this mixin, making a value/values available to all vue components.

To make that value Read Only, you can use the method described in this Stack Overflow answer.

Here is an example:

_x000D_
_x000D_
// This is a global mixin, it is applied to every vue instance. 
// Mixins must be instantiated *before* your call to new Vue(...)
Vue.mixin({
  data: function() {
    return {
      get globalReadOnlyProperty() {
        return "Can't change me!";
      }
    }
  }
})

Vue.component('child', {
  template: "<div>In Child: {{globalReadOnlyProperty}}</div>"
});

new Vue({
  el: '#app',
  created: function() {
    this.globalReadOnlyProperty = "This won't change it";
  }
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.3/vue.js"></script>
<div id="app">
  In Root: {{globalReadOnlyProperty}}
  <child></child>
</div>
_x000D_
_x000D_
_x000D_

Does a foreign key automatically create an index?

Foreign keys do not create indexes. Only alternate key constraints(UNIQUE) and primary key constraints create indexes. This is true in Oracle and SQL Server.

AngularJS : automatically detect change in model

In views with {{}} and/or ng-model, Angular is setting up $watch()es for you behind the scenes.

By default $watch compares by reference. If you set the third parameter to $watch to true, Angular will instead "shallow" watch the object for changes. For arrays this means comparing the array items, for object maps this means watching the properties. So this should do what you want:

$scope.$watch('myModel', function() { ... }, true);

Update: Angular v1.2 added a new method for this, `$watchCollection():

$scope.$watchCollection('myModel', function() { ... });

Note that the word "shallow" is used to describe the comparison rather than "deep" because references are not followed -- e.g., if the watched object contains a property value that is a reference to another object, that reference is not followed to compare the other object.

Better way to sum a property value in an array

I was already using jquery. But I think its intuitive enough to just have:

var total_amount = 0; 
$.each(traveler, function( i, v ) { total_amount += v.Amount ; });

This is basically just a short-hand version of @akhouri's answer.

Please explain the exec() function and its family

The exec family of functions make your process execute a different program, replacing the old program it was running. I.e., if you call

execl("/bin/ls", "ls", NULL);

then the ls program is executed with the process id, current working dir and user/group (access rights) of the process that called execl. Afterwards, the original program is not running anymore.

To start a new process, the fork system call is used. To execute a program without replacing the original, you need to fork, then exec.

What is the difference between "::" "." and "->" in c++

Put very simple :: is the scoping operator, . is the access operator (I forget what the actual name is?), and -> is the dereference arrow.

:: - Scopes a function. That is, it lets the compiler know what class the function lives in and, thus, how to call it. If you are using this operator to call a function, the function is a static function.

. - This allows access to a member function on an already created object. For instance, Foo x; x.bar() calls the method bar() on instantiated object x which has type Foo. You can also use this to access public class variables.

-> - Essentially the same thing as . except this works on pointer types. In essence it dereferences the pointer, than calls .. Using this is equivalent to (*ptr).method()

IIS URL Rewrite and Web.config

Just tried this rule, and it worked with GoDaddy hosting since they've already have the Microsoft URL Rewriting module installed for every IIS 7 account.

<rewrite>
  <rules>
    <rule name="enquiry" stopProcessing="true">
      <match url="^enquiry$" />
      <action type="Rewrite" url="/Enquiry.aspx" />
    </rule>
  </rules>
</rewrite>

Convert image from PIL to openCV format

The code commented works as well, just choose which do you prefer

import numpy as np
from PIL import Image


def convert_from_cv2_to_image(img: np.ndarray) -> Image:
    # return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    return Image.fromarray(img)


def convert_from_image_to_cv2(img: Image) -> np.ndarray:
    # return cv2.cvtColor(numpy.array(img), cv2.COLOR_RGB2BGR)
    return np.asarray(img)

How to check if mod_rewrite is enabled in php?

Two lines of code:

$isEnabled = in_array('mod_rewrite', apache_get_modules());
echo ($isEnabled) ? 'Enabled' : 'Not enabled';

ASP.NET MVC 3 Razor: Include JavaScript file in the head tag

You can use Named Sections.

_Layout.cshtml

<head>
    <script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
    @RenderSection("JavaScript", required: false)
</head>

_SomeView.cshtml

@section JavaScript
{
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
   <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}

What happens if you mount to a non-empty mount point with fuse?

You need to make sure that the files on the device mounted by fuse will not have the same paths and file names as files which already existing in the nonempty mountpoint. Otherwise this would lead to confusion. If you are sure, pass -o nonempty to the mount command.

You can try what is happening using the following commands.. (Linux rocks!) .. without destroying anything..

// create 10 MB file 
dd if=/dev/zero of=partition bs=1024 count=10240

// create loopdevice from that file
sudo losetup /dev/loop0 ./partition

// create  filesystem on it
sudo e2mkfs.ext3 /dev/loop0

// mount the partition to temporary folder and create a file
mkdir test
sudo mount -o loop /dev/loop0 test
echo "bar" | sudo tee test/foo

# unmount the device
sudo umount /dev/loop0

# create the file again
echo "bar2" > test/foo

# now mount the device (having file with same name on it) 
# and see what happens
sudo mount -o loop /dev/loop0 test

How to share data between different threads In C# using AOP?

You can't beat the simplicity of a locked message queue. I say don't waste your time with anything more complex.

Read up on the lock statement.

lock

EDIT

Here is an example of the Microsoft Queue object wrapped so all actions against it are thread safe.

public class Queue<T>
{
    /// <summary>Used as a lock target to ensure thread safety.</summary>
    private readonly Locker _Locker = new Locker();

    private readonly System.Collections.Generic.Queue<T> _Queue = new System.Collections.Generic.Queue<T>();

    /// <summary></summary>
    public void Enqueue(T item)
    {
        lock (_Locker)
        {
            _Queue.Enqueue(item);
        }
    }

    /// <summary>Enqueues a collection of items into this queue.</summary>
    public virtual void EnqueueRange(IEnumerable<T> items)
    {
        lock (_Locker)
        {
            if (items == null)
            {
                return;
            }

            foreach (T item in items)
            {
                _Queue.Enqueue(item);
            }
        }
    }

    /// <summary></summary>
    public T Dequeue()
    {
        lock (_Locker)
        {
            return _Queue.Dequeue();
        }
    }

    /// <summary></summary>
    public void Clear()
    {
        lock (_Locker)
        {
            _Queue.Clear();
        }
    }

    /// <summary></summary>
    public Int32 Count
    {
        get
        {
            lock (_Locker)
            {
                return _Queue.Count;
            }
        }
    }

    /// <summary></summary>
    public Boolean TryDequeue(out T item)
    {
        lock (_Locker)
        {
            if (_Queue.Count > 0)
            {
                item = _Queue.Dequeue();
                return true;
            }
            else
            {
                item = default(T);
                return false;
            }
        }
    }
}

EDIT 2

I hope this example helps. Remember this is bare bones. Using these basic ideas you can safely harness the power of threads.

public class WorkState
{
    private readonly Object _Lock = new Object();
    private Int32 _State;

    public Int32 GetState()
    {
        lock (_Lock)
        {
            return _State;
        }
    }

    public void UpdateState()
    {
        lock (_Lock)
        {
            _State++;   
        }   
    }
}

public class Worker
{
    private readonly WorkState _State;
    private readonly Thread _Thread;
    private volatile Boolean _KeepWorking;

    public Worker(WorkState state)
    {
        _State = state;
        _Thread = new Thread(DoWork);
        _KeepWorking = true;                
    }

    public void DoWork()
    {
        while (_KeepWorking)
        {
            _State.UpdateState();                   
        }
    }

    public void StartWorking()
    {
        _Thread.Start();
    }

    public void StopWorking()
    {
        _KeepWorking = false;
    }
}



private void Execute()
{
    WorkState state = new WorkState();
    Worker worker = new Worker(state);

    worker.StartWorking();

    while (true)
    {
        if (state.GetState() > 100)
        {
            worker.StopWorking();
            break;
        }
    }                   
}

Can I apply a CSS style to an element name?

This is the perfect job for the query selector...

var Set1=document.querySelectorAll('input[type=button]');  // by type

var Set2=document.querySelectorAll('input[name=goButton]'); // by name

var Set3=document.querySelectorAll('input[value=Go]'); // by value

You can then loop through these collections to operate on elements found.

How to change the value of ${user} variable used in Eclipse templates

just other option. goto PREFERENCES >> JAVA >> EDITOR >> TEMPLATES, Select @author and change the variable ${user}.

Reload a DIV without reloading the whole page

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js" />

<div class="View"><?php include 'Small.php'; ?></div>

<script type="text/javascript">
$(document).ready(function() {
$('.View').load('Small.php');
var auto_refresh = setInterval(
    function ()
    {
        $('.View').load('Small.php').fadeIn("slow");
    }, 15000); // refresh every 15000 milliseconds
        $.ajaxSetup({ cache: true });
    });
</script>

Import a module from a relative path

This is the relevant PEP:

http://www.python.org/dev/peps/pep-0328/

In particular, presuming dirFoo is a directory up from dirBar...

In dirFoo\Foo.py:

from ..dirBar import Bar

Composer - the requested PHP extension mbstring is missing from your system

For php 7.1

sudo apt-get install php7.1-mbstring

Cheers!

class << self idiom in Ruby

In fact if you write any C extensions for your Ruby projects there is really only one way to define a Module method.

rb_define_singleton_method

I know this self business just opens up all kinds of other questions so you could do better by searching each part.

Objects first.

foo = Object.new

Can I make a method for foo?

Sure

def foo.hello
 'hello'
end

What do I do with it?

foo.hello
 ==>"hello"

Just another object.

foo.methods

You get all the Object methods plus your new one.

def foo.self
 self
end

foo.self

Just the foo Object.

Try to see what happens if you make foo from other Objects like Class and Module. The examples from all the answers are nice to play with but you have to work with different ideas or concepts to really understand what is going on with the way the code is written. So now you have lots of terms to go look at.

Singleton, Class, Module, self, Object, and Eigenclass was brought up but Ruby doesn't name Object Models that way. It's more like Metaclass. Richard or __why shows you the idea here. http://viewsourcecode.org/why/hacking/seeingMetaclassesClearly.html And if the blows you away then try looking up Ruby Object Model in search. Two videos that I know of on YouTube are Dave Thomas and Peter Cooper. They try to explain that concept too. It took Dave a long time to get it so don't worry. I'm still working on it too. Why else would I be here? Thanks for your question. Also take a look at the standard library. It has a Singleton Module just as an FYI.

This is pretty good. https://www.youtube.com/watch?v=i4uiyWA8eFk

How to write a confusion matrix in Python?

A numpy-only solution for any number of classes that doesn't require looping:

import numpy as np

classes = 3
true = np.random.randint(0, classes, 50)
pred = np.random.randint(0, classes, 50)

np.bincount(true * classes + pred).reshape((classes, classes))

Group By Eloquent ORM

Eloquent uses the query builder internally, so you can do:

$users = User::orderBy('name', 'desc')
                ->groupBy('count')
                ->having('count', '>', 100)
                ->get();

Selenium using Java - The path to the driver executable must be set by the webdriver.gecko.driver system property

The Selenium client bindings will try to locate the geckodriver executable from the system PATH. You will need to add the directory containing the executable to the system path.

  • On Unix systems you can do the following to append it to your system’s search path, if you’re using a bash-compatible shell:

    export PATH=$PATH:/path/to/geckodriver
    
  • On Windows you need to update the Path system variable to add the full directory path to the executable. The principle is the same as on Unix.

All below configuration for launching latest firefox using any programming language binding is applicable for Selenium2 to enable Marionette explicitly. With Selenium 3.0 and later, you shouldn't need to do anything to use Marionette, as it's enabled by default.

To use Marionette in your tests you will need to update your desired capabilities to use it.

Java :

As exception is clearly saying you need to download latest geckodriver.exe from here and set downloaded geckodriver.exe path where it's exists in your computer as system property with with variable webdriver.gecko.driver before initiating marionette driver and launching firefox as below :-

//if you didn't update the Path system variable to add the full directory path to the executable as above mentioned then doing this directly through code
System.setProperty("webdriver.gecko.driver", "path/to/geckodriver.exe");

//Now you can Initialize marionette driver to launch firefox
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
WebDriver driver = new MarionetteDriver(capabilities); 

And for Selenium3 use as :-

WebDriver driver = new FirefoxDriver();

If you're still in trouble follow this link as well which would help you to solving your problem

.NET :

var driver = new FirefoxDriver(new FirefoxOptions());

Python :

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

caps = DesiredCapabilities.FIREFOX

# Tell the Python bindings to use Marionette.
# This will not be necessary in the future,
# when Selenium will auto-detect what remote end
# it is talking to.
caps["marionette"] = True

# Path to Firefox DevEdition or Nightly.
# Firefox 47 (stable) is currently not supported,
# and may give you a suboptimal experience.
#
# On Mac OS you must point to the binary executable
# inside the application package, such as
# /Applications/FirefoxNightly.app/Contents/MacOS/firefox-bin
caps["binary"] = "/usr/bin/firefox"

driver = webdriver.Firefox(capabilities=caps)

Ruby :

# Selenium 3 uses Marionette by default when firefox is specified
# Set Marionette in Selenium 2 by directly passing marionette: true
# You might need to specify an alternate path for the desired version of Firefox

Selenium::WebDriver::Firefox::Binary.path = "/path/to/firefox"
driver = Selenium::WebDriver.for :firefox, marionette: true

JavaScript (Node.js) :

const webdriver = require('selenium-webdriver');
const Capabilities = require('selenium-webdriver/lib/capabilities').Capabilities;

var capabilities = Capabilities.firefox();

// Tell the Node.js bindings to use Marionette.
// This will not be necessary in the future,
// when Selenium will auto-detect what remote end
// it is talking to.
capabilities.set('marionette', true);

var driver = new webdriver.Builder().withCapabilities(capabilities).build();

Using RemoteWebDriver

If you want to use RemoteWebDriver in any language, this will allow you to use Marionette in Selenium Grid.

Python:

caps = DesiredCapabilities.FIREFOX

# Tell the Python bindings to use Marionette.
# This will not be necessary in the future,
# when Selenium will auto-detect what remote end
# it is talking to.
caps["marionette"] = True

driver = webdriver.Firefox(capabilities=caps)

Ruby :

# Selenium 3 uses Marionette by default when firefox is specified
# Set Marionette in Selenium 2 by using the Capabilities class
# You might need to specify an alternate path for the desired version of Firefox

caps = Selenium::WebDriver::Remote::Capabilities.firefox marionette: true, firefox_binary: "/path/to/firefox"
driver = Selenium::WebDriver.for :remote, desired_capabilities: caps

Java :

DesiredCapabilities capabilities = DesiredCapabilities.firefox();

// Tell the Java bindings to use Marionette.
// This will not be necessary in the future,
// when Selenium will auto-detect what remote end
// it is talking to.
capabilities.setCapability("marionette", true);

WebDriver driver = new RemoteWebDriver(capabilities); 

.NET

DesiredCapabilities capabilities = DesiredCapabilities.Firefox();

// Tell the .NET bindings to use Marionette.
// This will not be necessary in the future,
// when Selenium will auto-detect what remote end
// it is talking to.
capabilities.SetCapability("marionette", true);

var driver = new RemoteWebDriver(capabilities); 

Note : Just like the other drivers available to Selenium from other browser vendors, Mozilla has released now an executable that will run alongside the browser. Follow this for more details.

You can download latest geckodriver executable to support latest firefox from here

AngularJS accessing DOM elements inside directive template

You could write a directive for this, which simply assigns the (jqLite) element to the scope using an attribute-given name.

Here is the directive:

app.directive("ngScopeElement", function () {
  var directiveDefinitionObject = {

    restrict: "A",

    compile: function compile(tElement, tAttrs, transclude) {
      return {
          pre: function preLink(scope, iElement, iAttrs, controller) {
            scope[iAttrs.ngScopeElement] = iElement;
          }
        };
    }
  };

  return directiveDefinitionObject;
});

Usage:

app.directive("myDirective", function() {
    return {
        template: '<div><ul ng-scope-element="list"><li ng-repeat="item in items"></ul></div>',
        link: function(scope, element, attrs) {
            scope.list[0] // scope.list is the jqlite element, 
                          // scope.list[0] is the native dom element
        }
    }
});

Some remarks:

  • Due to the compile and link order for nested directives you can only access scope.list from myDirectives postLink-Function, which you are very likely using anyway
  • ngScopeElement uses a preLink-function, so that directives nested within the element having ng-scope-element can already access scope.list
  • not sure how this behaves performance-wise

Android, landscape only orientation?

Just two steps needed:

  1. Apply setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); after setContentView().

  2. In the AndroidMainfest.xml, put this statement <activity android:name=".YOURCLASSNAME" android:screenOrientation="landscape" />

Hope it helps and happy coding :)

Git add and commit in one command

To keep it in one line use:

git add . && git commit -am "comment"

This line will add and commit all changed and added files to repository.

How to check if a network port is open on linux?

Netstat tool simply parses some /proc files like /proc/net/tcp and combines it with other files contents. Yep, it's highly platform specific, but for Linux-only solution you can stick with it. Linux kernel documentation describes these files in details so you can find there how to read them.

Please also notice your question is too ambiguous because "port" could also mean serial port (/dev/ttyS* and analogs), parallel port, etc.; I've reused understanding from another answer this is network port but I'd ask you to formulate your questions more accurately.

Convert PDF to clean SVG?

This topic is quite old, but here is a handy solution that I found:

http://www.cityinthesky.co.uk/opensource/pdf2svg/

It offers a tool, pdf2png, which once installed does exactly the job in command line. I've tested it with irreproachable results so far, including with bitmaps.

EDIT : My mistake, this tool also converts letters to paths, so it does not address the initial question. However it does a good job anyway, and can be useful to anyone who does not intend to modify the code in the svg file, so I'll leave the post.

How to include bootstrap css and js in reactjs app?

Somehow the accepted answer is only talking about including css file from bootstrap.

But I think this question is related to the one here - Bootstrap Dropdown not working in React

There are couple of answers that can help -

  1. https://stackoverflow.com/a/52251319/4266842
  2. https://stackoverflow.com/a/54188034/4266842

Accessing elements of Python dictionary by index

If the questions is, if I know that I have a dict of dicts that contains 'Apple' as a fruit and 'American' as a type of apple, I would use:

myDict = {'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
          'Grapes':{'Arabian':'25','Indian':'20'} }


print myDict['Apple']['American']

as others suggested. If instead the questions is, you don't know whether 'Apple' as a fruit and 'American' as a type of 'Apple' exist when you read an arbitrary file into your dict of dict data structure, you could do something like:

print [ftype['American'] for f,ftype in myDict.iteritems() if f == 'Apple' and 'American' in ftype]

or better yet so you don't unnecessarily iterate over the entire dict of dicts if you know that only Apple has the type American:

if 'Apple' in myDict:
    if 'American' in myDict['Apple']:
        print myDict['Apple']['American']

In all of these cases it doesn't matter what order the dictionaries actually store the entries. If you are really concerned about the order, then you might consider using an OrderedDict:

http://docs.python.org/dev/library/collections.html#collections.OrderedDict

How to read HDF5 files in Python

What you need to do is create a dataset. If you take a look at the quickstart guide, it shows you that you need to use the file object in order to create a dataset. So, f.create_dataset and then you can read the data. This is explained in the docs.

Resize on div element

If you just want to resize the div itself you need to specify that in css style. You need to add overflow and resize property.

Below is my code snippet

#div1 {
        width: 90%;
        height: 350px;
        padding: 10px;
        border: 1px solid #aaaaaa;
        overflow: auto;
        resize: both;
    }

<div id="div1">

</div>

What are the differences between Mustache.js and Handlebars.js?

—In addition to using "this" for handlebars, and the nested variable within variable block for mustache, you can also use the nested dot in a block for mustache:

    {{#variable}}<span class="text">{{.}}</span>{{/variable}}

'tsc command not found' in compiling typescript

I had this same problem on Ubuntu 19.10 LTS.

To solve this I ran the following command:

$ sudo apt install node-typescript

After that, I was able to use tsc.

JavaScript Nested function

_x000D_
_x000D_
function foo() {_x000D_
  function bar() {_x000D_
    return 1;_x000D_
  }_x000D_
}_x000D_
bar();
_x000D_
_x000D_
_x000D_
Will throw an error. Since bar is defined inside foo, bar will only be accessible inside foo.
To use bar you need to run it inside foo.

_x000D_
_x000D_
function foo() {_x000D_
  function bar() {_x000D_
    return 1;_x000D_
  }_x000D_
  bar();_x000D_
}
_x000D_
_x000D_
_x000D_

Add a new item to recyclerview programmatically?

simply add to your data structure ( mItems ) , and then notify your adapter about dataset change

private void addItem(String item) {
  mItems.add(item);
  mAdapter.notifyDataSetChanged();
}

addItem("New Item");

How to use multiple databases in Laravel

Laravel has inbuilt support for multiple database systems, you need to provide connection details in config/database.php file

return [
    'default' => env('DB_CONNECTION', 'mysql'),

    'connections' => [
        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],
'mysqlOne' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST_ONE', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE_ONE', 'forge'),
            'username' => env('DB_USERNAME_ONE', 'forge'),
            'password' => env('DB_PASSWORD_ONE', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],
];

Once you have this you can create two base model class for each connection and define the connection name in those models

//BaseModel.php
protected $connection = 'mysql';

//BaseModelOne.php
protected $connection = 'mysqlOne';

You can extend these models to create more models for tables in each DB.

How to trigger jQuery change event in code

for me $('#element').val('...').change() is the best way.

Finding a substring within a list in Python

I'd just use a simple regex, you can do something like this

import re
old_list = ['abc123', 'def456', 'ghi789']
new_list = [x for x in old_list if re.search('abc', x)]
for item in new_list:
    print item

What's the difference between Docker Compose vs. Dockerfile

Dockerfile

enter image description here

A Dockerfile is a simple text file that contains the commands a user could call to assemble an image.

Example, Dockerfile

FROM ubuntu:latest
MAINTAINER john doe 

RUN apt-get update
RUN apt-get install -y python python-pip wget
RUN pip install Flask

ADD hello.py /home/hello.py

WORKDIR /home

Docker Compose

enter image description here

Docker Compose

  • is a tool for defining and running multi-container Docker applications.

  • define the services that make up your app in docker-compose.yml so they can be run together in an isolated environment.

  • get an app running in one command by just running docker-compose up

Example, docker-compose.yml

version: "3"
services:
  web:
    build: .
    ports:
    - '5000:5000'
    volumes:
    - .:/code
    - logvolume01:/var/log
    links:
    - redis
  redis:
    image: redis
    volumes:
      logvolume01: {}

Getting the last element of a list

some_list[-1] is the shortest and most Pythonic.

In fact, you can do much more with this syntax. The some_list[-n] syntax gets the nth-to-last element. So some_list[-1] gets the last element, some_list[-2] gets the second to last, etc, all the way down to some_list[-len(some_list)], which gives you the first element.

You can also set list elements in this way. For instance:

>>> some_list = [1, 2, 3]
>>> some_list[-1] = 5 # Set the last element
>>> some_list[-2] = 3 # Set the second to last element
>>> some_list
[1, 3, 5]

Note that getting a list item by index will raise an IndexError if the expected item doesn't exist. This means that some_list[-1] will raise an exception if some_list is empty, because an empty list can't have a last element.

jQuery - Check if DOM element already exists

if ID is available - You can use getElementById()

var element =  document.getElementById('elementId');
  if (typeof(element) != 'undefined' && element != null)
  { 
     // exists.
  }

OR Try with Jquery -

if ($(document).find(yourElement).length == 0) 
{ 
 // -- Not Exist
}

display HTML page after loading complete

you can also go for this.... this will only show the HTML section once javascript has loaded.

<!-- Adds the hidden style and removes it when javascript has loaded -->
<style type="text/css">
    .hideAll  {
        visibility:hidden;
     }
</style>

<script type="text/javascript">
    $(window).load(function () {
        $("#tabs").removeClass("hideAll");
    });
</script>

<div id="tabs" class="hideAll">
   ##Content##
</div>

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

If you use the procedural style, you have to provide both a connection and a string:

$name = mysqli_real_escape_string($conn, $name);

Only the object oriented version can be done with just a string:

$name = $link->real_escape_string($name);

The documentation should hopefully make this clear.

Is there an XSLT name-of element?

<xsl:value-of select="name(.)" /> : <xsl:value-of select="."/>

Transport security has blocked a cleartext HTTP

How to fix it?

enter image description here

Below steps to fix it.

enter image description here enter image description here enter image description here enter image description here enter image description here

Size-limited queue that holds last N elements in Java

Apache commons collections 4 has a CircularFifoQueue<> which is what you are looking for. Quoting the javadoc:

CircularFifoQueue is a first-in first-out queue with a fixed size that replaces its oldest element if full.

    import java.util.Queue;
    import org.apache.commons.collections4.queue.CircularFifoQueue;

    Queue<Integer> fifo = new CircularFifoQueue<Integer>(2);
    fifo.add(1);
    fifo.add(2);
    fifo.add(3);
    System.out.println(fifo);

    // Observe the result: 
    // [2, 3]

If you are using an older version of the Apache commons collections (3.x), you can use the CircularFifoBuffer which is basically the same thing without generics.

Update: updated answer following release of commons collections version 4 that supports generics.

Setting a minimum/maximum character count for any character using a regular expression

If you also want to match newlines, then you might want to use "^[\s\S]{1,35}$" (depending on the regex engine). Otherwise, as others have said, you should used "^.{1,35}$"

Do AJAX requests retain PHP Session info?

What you're really getting at is: are cookies sent to with the AJAX request? Assuming the AJAX request is to the same domain (or within the domain constraints of the cookie), the answer is yes. So AJAX requests back to the same server do retain the same session info (assuming the called scripts issue a session_start() as per any other PHP script wanting access to session information).

How to use ImageBackground to set background image for screen in react-native

ImageBackground is a very simple and useful component.Put your component inside ImageBackground as a nested component and tweak a position of your component by using position.

Here's an example.

_x000D_
_x000D_
<ImageBackground_x000D_
  source={{ uri: hoge }}_x000D_
  style={{_x000D_
    height: 100,_x000D_
    width: 100,_x000D_
    position: 'relative', _x000D_
    top: 0,_x000D_
    left: 0_x000D_
  }}_x000D_
>_x000D_
  <Text_x000D_
    style={{_x000D_
      fontWeight: 'bold',_x000D_
      color: 'white',_x000D_
      position: 'absolute', _x000D_
      bottom: 0, _x000D_
      left: 0_x000D_
    }}_x000D_
  >_x000D_
    Hello World_x000D_
  </Text>_x000D_
</ImageBackground>
_x000D_
_x000D_
_x000D_

How do I convert a long to a string in C++?

The way I typically do it is with sprintf. So for a long you could do the following assuming that you are on a 32 bit architecture:

char buf[5] = {0}; // one extra byte for null    
sprintf(buf, "%l", var_for_long);

jQuery How to Get Element's Margin and Padding?

I've a snippet that shows, how to get the spacings of elements with jQuery:

/* messing vertical spaces of block level elements with jQuery in pixels */

console.clear();

var jObj = $('selector');

for(var i = 0, l = jObj.length; i < l; i++) {
  //jObj.eq(i).css('display', 'block');
  console.log('jQuery object:', jObj.eq(i));
  console.log('plain element:', jObj[i]);

  console.log('without spacings                - jObj.eq(i).height():         ', jObj.eq(i).height());
  console.log('with padding                    - jObj[i].clientHeight:        ', jObj[i].clientHeight);
  console.log('with padding and border         - jObj.eq(i).outerHeight():    ', jObj.eq(i).outerHeight());
  console.log('with padding, border and margin - jObj.eq(i).outerHeight(true):', jObj.eq(i).outerHeight(true));
  console.log('total vertical spacing:                                        ', jObj.eq(i).outerHeight(true) - jObj.eq(i).height());
}

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

Apart from the possible solutions in other answers, it is also possible that somehow Maven dependency corruption has occurred on your machine. I was facing the same error on trying to run my (Web) Spring boot application, and it got resolved by running the following -

mvn dependency:purge-local-repository -DreResolve=true

followed by

mvn package

I came onto this solution looking into another issue where Eclipse wouldn't let me run the main application class from the IDE, due to a different error, similar to one on this SO thread -> The type org.springframework.context.ConfigurableApplicationContext cannot be resolved. It is indirectly referenced from required .class files

Read next word in java

You do not necessarily have to split the line because java.util.Scanner's default delimiter is whitespace.

You can just create a new Scanner object within your while statement.

    Scanner sc2 = null;
    try {
        sc2 = new Scanner(new File("translate.txt"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();  
    }
    while (sc2.hasNextLine()) {
            Scanner s2 = new Scanner(sc2.nextLine());
        while (s2.hasNext()) {
            String s = s2.next();
            System.out.println(s);
        }
    }

How can I represent an 'Enum' in Python?

On 2013-05-10, Guido agreed to accept PEP 435 into the Python 3.4 standard library. This means that Python finally has builtin support for enumerations!

There is a backport available for Python 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4. It's on Pypi as enum34.

Declaration:

>>> from enum import Enum
>>> class Color(Enum):
...     red = 1
...     green = 2
...     blue = 3

Representation:

>>> print(Color.red)
Color.red
>>> print(repr(Color.red))
<Color.red: 1>

Iteration:

>>> for color in Color:
...   print(color)
...
Color.red
Color.green
Color.blue

Programmatic access:

>>> Color(1)
Color.red
>>> Color['blue']
Color.blue

For more information, refer to the proposal. Official documentation will probably follow soon.

Shell - How to find directory of some command?

Like this:

which lshw

To see all of the commands that match in your path:

which -a lshw 

Why does python use 'else' after for and while loops?

To make it simple, you can think of it like that;

  • If it encounters the break command in the for loop, the else part will not be called.
  • If it does not encounter the break command in the for loop, the else part will be called.

In other words, if for loop iteration is not "broken" with break, the else part will be called.

Prevent linebreak after </div>

try float your div's in css

.label {
float:left;
width:200px;
}
.text {
float:left;
}

Iterating through all the cells in Excel VBA or VSTO 2005

In Excel VBA, this function will give you the content of any cell in any worksheet.

Function getCellContent(Byref ws As Worksheet, ByVal rowindex As Integer, ByVal colindex As Integer) as String
    getCellContent = CStr(ws.Cells(rowindex, colindex))
End Function

So if you want to check the value of cells, just put the function in a loop, give it the reference to the worksheet you want and the row index and column index of the cell. Row index and column index both start from 1, meaning that cell A1 will be ws.Cells(1,1) and so on.

Convert a RGB Color Value to a Hexadecimal String

Random ra = new Random();
int r, g, b;
r=ra.nextInt(255);
g=ra.nextInt(255);
b=ra.nextInt(255);
Color color = new Color(r,g,b);
String hex = Integer.toHexString(color.getRGB() & 0xffffff);
if (hex.length() < 6) {
    hex = "0" + hex;
}
hex = "#" + hex;

How do you pass a function as a parameter in C?

I am gonna explain with a simple example code which takes a compare function as parameter to another sorting function. Lets say I have a bubble sort function that takes a custom compare function and uses it instead of a fixed if statement.

Compare Function

bool compare(int a, int b) {
    return a > b;
}

Now , the Bubble sort that takes another function as its parameter to perform comparison

Bubble sort function

void bubble_sort(int arr[], int n, bool (&cmp)(int a, int b)) {

    for (int i = 0;i < n - 1;i++) {
        for (int j = 0;j < (n - 1 - i);j++) {
            
            if (cmp(arr[j], arr[j + 1])) {
                swap(arr[j], arr[j + 1]);
            }
        }
    }
}

Finally , the main which calls the Bubble sort function by passing the boolean compare function as argument.

int main()
{
    int i, n = 10, key = 11;
    int arr[10] = { 20, 22, 18, 8, 12, 3, 6, 12, 11, 15 };

    bubble_sort(arr, n, compare);
    cout<<"Sorted Order"<<endl;
    for (int i = 0;i < n;i++) {
        cout << arr[i] << " ";
    }
}

Output:

Sorted Order
3 6 8 11 12 12 15 18 20 22

How to insert an item into a key/value pair object?

List<KeyValuePair<string, string>> kvpList = new List<KeyValuePair<string, string>>()
{
    new KeyValuePair<string, string>("Key1", "Value1"),
    new KeyValuePair<string, string>("Key2", "Value2"),
    new KeyValuePair<string, string>("Key3", "Value3"),
};

kvpList.Insert(0, new KeyValuePair<string, string>("New Key 1", "New Value 1"));

Using this code:

foreach (KeyValuePair<string, string> kvp in kvpList)
{
    Console.WriteLine(string.Format("Key: {0} Value: {1}", kvp.Key, kvp.Value);
}

the expected output should be:

Key: New Key 1 Value: New Value 1
Key: Key 1 Value: Value 1
Key: Key 2 Value: Value 2
Key: Key 3 Value: Value 3

The same will work with a KeyValuePair or whatever other type you want to use..

Edit -

To lookup by the key, you can do the following:

var result = stringList.Where(s => s == "Lookup");

You could do this with a KeyValuePair by doing the following:

var result = kvpList.Where (kvp => kvp.Value == "Lookup");

Last edit -

Made the answer specific to KeyValuePair rather than string.

docker error - 'name is already in use by container'

removing all the exited containers

docker rm $(docker ps -a -f status=exited -q)

Fullscreen Activity in Android?

Inside styles.xml...

<!-- No action bar -->
<style name="NoActonBar" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Theme customization. -->
    <item name="colorPrimary">#000</item>
    <item name="colorPrimaryDark">#444</item>
    <item name="colorAccent">#999</item>
    <item name="android:windowFullscreen">true</item>
</style>

This worked for me. Hope it'll help you.

Java SSLException: hostname in certificate didn't match

The concern is we should not use ALLOW_ALL_HOSTNAME_VERIFIER.

How about I implement my own hostname verifier?

class MyHostnameVerifier implements org.apache.http.conn.ssl.X509HostnameVerifier
{
    @Override
    public boolean verify(String host, SSLSession session) {
        String sslHost = session.getPeerHost();
        System.out.println("Host=" + host);
        System.out.println("SSL Host=" + sslHost);    
        if (host.equals(sslHost)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void verify(String host, SSLSocket ssl) throws IOException {
        String sslHost = ssl.getInetAddress().getHostName();
        System.out.println("Host=" + host);
        System.out.println("SSL Host=" + sslHost);    
        if (host.equals(sslHost)) {
            return;
        } else {
            throw new IOException("hostname in certificate didn't match: " + host + " != " + sslHost);
        }
    }

    @Override
    public void verify(String host, X509Certificate cert) throws SSLException {
        throw new SSLException("Hostname verification 1 not implemented");
    }

    @Override
    public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
        throw new SSLException("Hostname verification 2 not implemented");
    }
}

Let's test against https://www.rideforrainbows.org/ which is hosted on a shared server.

public static void main (String[] args) throws Exception {
    //org.apache.http.conn.ssl.SSLSocketFactory sf = org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory();
    //sf.setHostnameVerifier(new MyHostnameVerifier());
    //org.apache.http.conn.scheme.Scheme sch = new Scheme("https", 443, sf);

    org.apache.http.client.HttpClient client = new DefaultHttpClient();
    //client.getConnectionManager().getSchemeRegistry().register(sch);
    org.apache.http.client.methods.HttpPost post = new HttpPost("https://www.rideforrainbows.org/");
    org.apache.http.HttpResponse response = client.execute(post);
    java.io.InputStream is = response.getEntity().getContent();
    java.io.BufferedReader rd = new java.io.BufferedReader(new java.io.InputStreamReader(is));
    String line;
    while ((line = rd.readLine()) != null) { 
        System.out.println(line);
    }
}

SSLException:

Exception in thread "main" javax.net.ssl.SSLException: hostname in certificate didn't match: www.rideforrainbows.org != stac.rt.sg OR stac.rt.sg OR www.stac.rt.sg
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:231)
...

Do with MyHostnameVerifier:

public static void main (String[] args) throws Exception {
    org.apache.http.conn.ssl.SSLSocketFactory sf = org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory();
    sf.setHostnameVerifier(new MyHostnameVerifier());
    org.apache.http.conn.scheme.Scheme sch = new Scheme("https", 443, sf);

    org.apache.http.client.HttpClient client = new DefaultHttpClient();
    client.getConnectionManager().getSchemeRegistry().register(sch);
    org.apache.http.client.methods.HttpPost post = new HttpPost("https://www.rideforrainbows.org/");
    org.apache.http.HttpResponse response = client.execute(post);
    java.io.InputStream is = response.getEntity().getContent();
    java.io.BufferedReader rd = new java.io.BufferedReader(new java.io.InputStreamReader(is));
    String line;
    while ((line = rd.readLine()) != null) { 
        System.out.println(line);
    }
}

Shows:

Host=www.rideforrainbows.org
SSL Host=www.rideforrainbows.org

At least I have the logic to compare (Host == SSL Host) and return true.

The above source code is working for httpclient-4.2.3.jar and httpclient-4.3.3.jar.

What permission do I need to access Internet from an Android application?

If you want using Internet in your app as well as check the network state i.e. Is app is connected to the internet then you have to use below code outside of the application tag.

For Internet Permission:

<uses-permission android:name="android.permission.INTERNET" />

For Access network state:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Complete Code:

<uses-sdk
    android:minSdkVersion="9"
    android:targetSdkVersion="16" />

 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >


    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

How to set Default Controller in asp.net MVC 4 & MVC 5

I didnt see this question answered:

How should I setup a default Area when the application starts?

So, here is how you can set up a default Area:

var route = routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    ).DataTokens = new RouteValueDictionary(new { area = "MyArea" });

SQL Server default character encoding

If you need to know the default collation for a newly created database use:

SELECT SERVERPROPERTY('Collation')

This is the server collation for the SQL Server instance that you are running.

What does %s mean in a python format string?

It is a string formatting syntax (which it borrows from C).

Please see "PyFormat":

Python supports formatting values into strings. Although this can include very complicated expressions, the most basic usage is to insert values into a string with the %s placeholder.

Edit: Here is a really simple example:

#Python2
name = raw_input("who are you? ")
print "hello %s" % (name,)

#Python3+
name = input("who are you? ")
print("hello %s" % (name,))

The %s token allows me to insert (and potentially format) a string. Notice that the %s token is replaced by whatever I pass to the string after the % symbol. Notice also that I am using a tuple here as well (when you only have one string using a tuple is optional) to illustrate that multiple strings can be inserted and formatted in one statement.

Perfect 100% width of parent container for a Bootstrap input?

Just add box-sizing:

input[type="text"] {
    box-sizing: border-box;
}

How to generate a QR Code for an Android application?

Maybe this old topic but i found this library is very helpful and easy to use

QRGen

example for using it in android

 Bitmap myBitmap = QRCode.from("www.example.org").bitmap();
ImageView myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);

Can I try/catch a warning?

try checking whether it returns some boolean value then you can simply put it as a condition. I encountered this with the oci_execute(...) which was returning some violation with my unique keys.

ex.
oci_parse($res, "[oracle pl/sql]");
if(oci_execute){
...do something
}

Removing elements by class name?

Using jQuery (which you really could be using in this case, I think), you could do this like so:

$('.column').remove();

Otherwise, you're going to need to use the parent of each element to remove it:

element.parentNode.removeChild(element);

Calculating how many days are between two dates in DB2?

values timestampdiff (16, char( 
    timestamp(current timestamp + 1 year + 2 month - 3 day)- 
    timestamp(current timestamp)))
1
=
422



values timestampdiff (16, char( 
    timestamp('2012-03-08-00.00.00')- 
    timestamp('2011-12-08-00.00.00')))
1
=
90

---------- EDIT BY galador

SELECT TIMESTAMPDIFF(16, CHAR(CURRENT TIMESTAMP - TIMESTAMP_FORMAT(CHDLM, 'YYYYMMDD'))
FROM CHCART00
WHERE CHSTAT = '05'

EDIT

As it has been pointed out by X-Zero, this function returns only an estimate. This is true. For accurate results I would use the following to get the difference in days between two dates a and b:

SELECT days (current date) - days (date(TIMESTAMP_FORMAT(CHDLM, 'YYYYMMDD')))
FROM CHCART00 
WHERE CHSTAT = '05';

What does "make oldconfig" do exactly in the Linux kernel makefile?

It reads the existing .config file that was used for an old kernel and prompts the user for options in the current kernel source that are not found in the file. This is useful when taking an existing configuration and moving it to a new kernel.

Typedef function pointer?

  1. typedef is used to alias types; in this case you're aliasing FunctionFunc to void(*)().

  2. Indeed the syntax does look odd, have a look at this:

    typedef   void      (*FunctionFunc)  ( );
    //         ^                ^         ^
    //     return type      type name  arguments
    
  3. No, this simply tells the compiler that the FunctionFunc type will be a function pointer, it doesn't define one, like this:

    FunctionFunc x;
    void doSomething() { printf("Hello there\n"); }
    x = &doSomething;
    
    x(); //prints "Hello there"
    

How can I run a program from a batch file without leaving the console open after the program starts?

You can use the exit keyword. Here is an example from one of my batch files:

start myProgram.exe param1
exit

Convert UTC to local time in Rails 3

It is easy to configure it using your system local zone, Just in your application.rb add this

config.time_zone = Time.now.zone

Then, rails should show you timestamps in your localtime or you can use something like this instruction to get the localtime

Post.created_at.localtime

Redeploy alternatives to JRebel

Take a look at DCEVM, it's a modification of the HotSpot VM that allows unlimited class redefinitions at runtime. You can add/remove fields and methods and change the super types of a class at runtime.

The binaries available on the original site are limited to Java 6u25 and to early versions of Java 7. The project has been forked on Github and supports recent versions of Java 7 and 8. The maintainer provides binaries for 32/64 bits VMs on Windows/Linux. Starting with Java 11 the project moved to a new GitHub repository and now also provides binaries for OS X.

DCEVM is packaged for Debian and Ubuntu, it's conveniently integrated with OpenJDK and can be invoked with java -dcevm. The name of the package depends on the version of the default JDK:

Convert String to double in Java

If you have problems in parsing string to decimal values, you need to replace "," in the number to "."


String number = "123,321";
double value = Double.parseDouble( number.replace(",",".") );

PHP to write Tab Characters inside a file?

This should do:

$chunk = "abc\tdef\tghi";

Here is a link to an article with more extensive examples.

PostgreSQL: insert from another table

Very late answer, but I think my answer is more straight forward for specific use cases where users want to simply insert (copy) data from table A into table B:

INSERT INTO table_b (col1, col2, col3, col4, col5, col6)
SELECT col1, 'str_val', int_val, col4, col5, col6
FROM table_a

Eclipse: "'Periodic workspace save.' has encountered a pro?blem."

I had the same problem.

'Periodic workspace save.' has encountered a problem. Could not write metadata for '/External Files'. D:\java\fuentes\.metadata\.plugins\org.eclipse.core.resources\.projects\External Files\.markers.snap (El sistema no puede hallar la ruta especificada)

I created the folder "External Files" and it worked fine. In a few minutes the files ".markers.snap" and ".syncinfo.snap" appeared in this folder and the message didn´t appear any more.

CSS image resize percentage of itself?

function shrinkImage(idOrClass, className, percentShrinkage){
'use strict';
    $(idOrClass+className).each(function(){
        var shrunkenWidth=this.naturalWidth;
        var shrunkenHeight=this.naturalHeight;
        $(this).height(shrunkenWidth*percentShrinkage);
        $(this).height(shrunkenHeight*percentShrinkage);
    });
};

$(document).ready(function(){
    'use strict';
     shrinkImage(".","anyClass",.5);  //CHANGE THE VALUES HERE ONLY. 
});

This solution uses js and jquery and resizes based only on the image properties and not on the parent. It can resize a single image or a group based using class and id parameters.

for more, go here: https://gist.github.com/jennyvallon/eca68dc78c3f257c5df5

Get current index from foreach loop

IEnumerable list = DataGridDetail.ItemsSource as IEnumerable;
List<string> lstFile = new List<string>();

int i = 0;
foreach (var row in list)
{
bool IsChecked = (bool)((CheckBox)DataGridDetail.Columns[0].GetCellContent(row)).IsChecked;
if (IsChecked)
{
  MessageBox.show(i);
--Here i want to get the index or current row from the list                   

}
 ++i;
}