Programs & Examples On #Dirtyrectangle

Convert string in base64 to image and save on filesystem in Python

Try this solution,

image file --> binary encoded string

binary encoded string --> image file

import base64

"""
1st step - convert image into binary
"""
with open("original_image.png", "rb") as original_file:
    encoded_string = base64.b64encode(original_file.read())

print(encoded_string)
# xmzWowsfJbpGwCe0DTveqwvos7Mf0lcVNe/Q+G1hO/p+UNPd/stUse8AhP/3fDixf8HI3No67nvhlYAAAAASUVORK5CYII='

print(type(encoded_string))
# <class 'bytes'>

"""
2nd step - create new image using the encoded string
"""
with open("new_image.png", "wb") as new_file:
    new_file.write(base64.decodebytes(encoded_string))

References:

Is there a label/goto in Python?

I think while loop is alternate for the "goto_Statement". Because after 3.6 goto loop is not working anymore. I also write an example of the while loop.

str1 = "stop"
while str1 == "back":
    var1 = int(input(" Enter Ist Number: "))
    var2 = int(input(" Enter 2nd Number: "))
    var3 = print("""  What is your next operation
                      For Addition   Press And Enter : 'A'
                      For Muliplt    Press And Enter : 'M'
                      For Division   Press And Enter : 'D'
                      For Subtaction Press And Enter : 'S' """)

    var4 = str(input("For operation press any number : "))
    if(var1 == 45) and (var2 == 3):
        print("555")
    elif(var1 == 56) and (var2 == 9):
        print("77")
    elif(var1 == 56) and (var2 == 6):
        print("4")
    else:
        if(var4 == "A" or "a"):
            print(var1 + var2)
        if(var4 == "M" or "m"):
            print(var1 * var2)
        if(var4 == "D" or "d"):
            print(var1 / var2)
        if(var4 == "S" or "s"):
            print(var1 - var2)

    print("if you want to continue then type  'stop'")

    str1 = input()
print("Strt again")    

How to center form in bootstrap 3

A simple way is to add

.center_div{
    margin: 0 auto;
    width:80% /* value of your choice which suits your alignment */
}

to you class .container.Add width:xx % to it and you get perfectly centered div!

eg :

<div class="container center_div">

but i feel that by default container is centered in BS!

How do I split an int into its digits?

Given the number 12345 :

5 is 12345 % 10
4 is 12345 / 10 % 10
3 is 12345 / 100 % 10
2 is 12345 / 1000 % 10
1 is 12345 / 10000 % 10

I won't provide a complete code as this surely looks like homework, but I'm sure you get the pattern.

What characters are allowed in an email address?

Check for @ and . and then send an email for them to verify.

I still can't use my .name email address on 20% of the sites on the internet because someone screwed up their email validation, or because it predates the new addresses being valid.

Error: Expression must have integral or unscoped enum type

Your variable size is declared as: float size;

You can't use a floating point variable as the size of an array - it needs to be an integer value.

You could cast it to convert to an integer:

float *temp = new float[(int)size];

Your other problem is likely because you're writing outside of the bounds of the array:

   float *temp = new float[size];

    //Getting input from the user
    for (int x = 1; x <= size; x++){
        cout << "Enter temperature " << x << ": ";

        // cin >> temp[x];
        // This should be:
        cin >> temp[x - 1];
    }

Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.

Windows equivalent of OS X Keychain?

The "traditional" Windows equivalent would be the Protected Storage subsystem, used by IE (pre IE 7), Outlook Express, and a few other programs. I believe it's encrypted with your login password, which prevents some offline attacks, but once you're logged in, any program that wants to can read it. (See, for example, NirSoft's Protected Storage PassView.)

Windows also provides the CryptoAPI and Data Protection API that might help. Again, though, I don't think that Windows does anything to prevent processes running under the same account from seeing each other's passwords.

It looks like the book Mechanics of User Identification and Authentication provides more details on all of these.

Eclipse (via its Secure Storage feature) implements something like this, if you're interested in seeing how other software does it.

Vertically and horizontally centering text in circle in CSS (like iphone notification badge)

Horizontal centering is easy: text-align: center;. Vertical centering of text inside an element can be done by setting line-height equal to the container height, but this has subtle differences between browsers. On small elements, like a notification badge, these are more pronounced.

Better is to set line-height equal to font-size (or slightly smaller) and use padding. You'll have to adjust your height to accomodate.

Here's a CSS-only, single <div> solution that looks pretty iPhone-like. They expand with content.

Demo: http://jsfiddle.net/ThinkingStiff/mLW47/

Output:

enter image description here

CSS:

.badge {
    background: radial-gradient( 5px -9px, circle, white 8%, red 26px );
    background-color: red;
    border: 2px solid white;
    border-radius: 12px; /* one half of ( (border * 2) + height + padding ) */
    box-shadow: 1px 1px 1px black;
    color: white;
    font: bold 15px/13px Helvetica, Verdana, Tahoma;
    height: 16px; 
    min-width: 14px;
    padding: 4px 3px 0 3px;
    text-align: center;
}

HTML:

<div class="badge">1</div>
<div class="badge">2</div>
<div class="badge">3</div>
<div class="badge">44</div>
<div class="badge">55</div>
<div class="badge">666</div>
<div class="badge">777</div>
<div class="badge">8888</div>
<div class="badge">9999</div>

Hide Signs that Meteor.js was Used

A Meteor app does not, by default, add any X-Powered-By headers to HTTP responses, as you might find in various PHP apps. The headers look like:

$ curl -I https://atmosphere.meteor.com  HTTP/1.1 200 OK content-type: text/html; charset=utf-8 date: Tue, 31 Dec 2013 23:12:25 GMT connection: keep-alive 

However, this doesn't mask that Meteor was used. Viewing the source of a Meteor app will look very distinctive.

<script type="text/javascript"> __meteor_runtime_config__ = {"meteorRelease":"0.6.3.1","ROOT_URL":"http://atmosphere.meteor.com","serverId":"62a4cf6a-3b28-f7b1-418f-3ddf038f84af","DDP_DEFAULT_CONNECTION_URL":"ddp+sockjs://ddp--****-atmosphere.meteor.com/sockjs"}; </script> 

If you're trying to avoid people being able to tell you are using Meteor even by viewing source, I don't think that's possible.

Checkbox angular material checked by default

If you are using Reactive form you can set it to default like this:

In the form model, set the value to false. So if it's checked its value will be true else false

let form = this.formBuilder.group({
    is_known: [false]
})

//In HTML

 <mat-checkbox matInput formControlName="is_known">Known</mat-checkbox>

DIV :after - add content after DIV

Position your <div> absolutely at the bottom and don't forget to give div.A a position: relative - http://jsfiddle.net/TTaMx/

    .A {
        position: relative;
        margin: 40px 0;
        height: 40px;
        width: 200px;
        background: #eee;
    }

    .A:after {
        content: " ";
        display: block;
        background: #c00;
        height: 29px;
        width: 100%;

        position: absolute;
        bottom: -29px;
    }?

How to sort a HashMap in Java

http://snipplr.com/view/2789/sorting-map-keys-by-comparing-its-values/

get the keys

List keys = new ArrayList(yourMap.keySet());

Sort them

 Collections.sort(keys)

print them.

In any case, you can't have sorted values in HashMap (according to API This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time ].

Though you can push all these values to LinkedHashMap, for later use as well.

Why is there still a row limit in Microsoft Excel?

Probably because of optimizations. Excel 2007 can have a maximum of 16 384 columns and 1 048 576 rows. Strange numbers?

14 bits = 16 384, 20 bits = 1 048 576

14 + 20 = 34 bits = more than one 32 bit register can hold.

But they also need to store the format of the cell (text, number etc) and formatting (colors, borders etc). Assuming they use two 32-bit words (64 bit) they use 34 bits for the cell number and have 30 bits for other things.

Why is that important? In memory they don't need to allocate all the memory needed for the whole spreadsheet but only the memory necessary for your data, and every data is tagged with in what cell it is supposed to be in.

Update 2016:

Found a link to Microsoft's specification for Excel 2013 & 2016

  • Open workbooks: Limited by available memory and system resources
  • Worksheet size: 1,048,576 rows (20 bits) by 16,384 columns (14 bits)
  • Column width: 255 characters (8 bits)
  • Row height: 409 points
  • Page breaks: 1,026 horizontal and vertical (unexpected number, probably wrong, 10 bits is 1024)
  • Total number of characters that a cell can contain: 32,767 characters (signed 16 bits)
  • Characters in a header or footer: 255 (8 bits)
  • Sheets in a workbook: Limited by available memory (default is 1 sheet)
  • Colors in a workbook: 16 million colors (32 bit with full access to 24 bit color spectrum)
  • Named views in a workbook: Limited by available memory
  • Unique cell formats/cell styles: 64,000 (16 bits = 65536)
  • Fill styles: 256 (8 bits)
  • Line weight and styles: 256 (8 bits)
  • Unique font types: 1,024 (10 bits) global fonts available for use; 512 per workbook
  • Number formats in a workbook: Between 200 and 250, depending on the language version of Excel that you have installed
  • Names in a workbook: Limited by available memory
  • Windows in a workbook: Limited by available memory
  • Hyperlinks in a worksheet: 66,530 hyperlinks (unexpected number, probably wrong. 16 bits = 65536)
  • Panes in a window: 4
  • Linked sheets: Limited by available memory
  • Scenarios: Limited by available memory; a summary report shows only the first 251 scenarios
  • Changing cells in a scenario: 32
  • Adjustable cells in Solver: 200
  • Custom functions: Limited by available memory
  • Zoom range: 10 percent to 400 percent
  • Reports: Limited by available memory
  • Sort references: 64 in a single sort; unlimited when using sequential sorts
  • Undo levels: 100
  • Fields in a data form: 32
  • Workbook parameters: 255 parameters per workbook
  • Items displayed in filter drop-down lists: 10,000

Get user's current location

Try this code using the hostip.info service:

$country=file_get_contents('http://api.hostip.info/get_html.php?ip=');
echo $country;

// Reformat the data returned (Keep only country and country abbr.)
$only_country=explode (" ", $country);

echo "Country : ".$only_country[1]." ".substr($only_country[2],0,4);

DatabaseError: current transaction is aborted, commands ignored until end of transaction block?

I am using the python package psycopg2 and I got this error while querying. I kept running just the query and then the execute function, but when I reran the connection (shown below), it resolved the issue. So rerun what is above your script i.e the connection, because as someone said above, I think it lost the connection or was out of sync or something.

connection = psycopg2.connect(user = "##",
        password = "##",
        host = "##",
        port = "##",
        database = "##")
cursor = connection.cursor()

Passing parameters to addTarget:action:forControlEvents

To pass custom params along with the button click you just need to SUBCLASS UIButton.

(ASR is on, so there's no releases in the code.)

This is myButton.h

#import <UIKit/UIKit.h>

@interface myButton : UIButton {
    id userData;
}

@property (nonatomic, readwrite, retain) id userData;

@end

This is myButton.m

#import "myButton.h"
@implementation myButton
@synthesize userData;
@end

Usage:

myButton *bt = [myButton buttonWithType:UIButtonTypeCustom];
[bt setFrame:CGRectMake(0,0, 100, 100)];
[bt setExclusiveTouch:NO];
[bt setUserData:**(insert user data here)**];

[bt addTarget:self action:@selector(touchUpHandler:) forControlEvents:UIControlEventTouchUpInside];

[view addSubview:bt];

Recieving function:

- (void) touchUpHandler:(myButton *)sender {
    id userData = sender.userData;
}

If you need me to be more specific on any part of the above code — feel free to ask about it in comments.

Split an integer into digits to compute an ISBN checksum

How about a one-liner list of digits...

ldigits = lambda n, l=[]: not n and l or l.insert(0,n%10) or ldigits(n/10,l)

How can I send an inner <div> to the bottom of its parent <div>?

You may not want absolute positioning because it breaks the reflow: in some circumstances, a better solution is to make the grandparent element display:table; and the parent element display:table-cell;vertical-align:bottom;. After doing this, you should be able to give the the child elements display:inline-block; and they will automagically flow towards the bottom of the parent.

Best way to make a shell script daemon?

try executing using & if you save this file as program.sh

you can use

$. program.sh &

C# Set collection?

Try HashSet:

The HashSet(Of T) class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order...

The capacity of a HashSet(Of T) object is the number of elements that the object can hold. A HashSet(Of T) object's capacity automatically increases as elements are added to the object.

The HashSet(Of T) class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of the Dictionary(Of TKey, TValue) or Hashtable collections. In simple terms, the HashSet(Of T) class can be thought of as a Dictionary(Of TKey, TValue) collection without values.

A HashSet(Of T) collection is not sorted and cannot contain duplicate elements...

Batch Script to Run as Administrator

My solution, if you dont need to have .bat file, is to convert the batch file to .exe file then you will be able to set up run as admin.

Convert string to symbol-able in ruby

intern ? symbol Returns the Symbol corresponding to str, creating the symbol if it did not previously exist

"edition".intern # :edition

http://ruby-doc.org/core-2.1.0/String.html#method-i-intern

Remove a specific character using awk or sed

tr can be more concise for removing characters than sed or awk, especially when you want to remove different characters from a string.

Removing double quotes:

echo '"Hi"' | tr -d \"
# Produces Hi without quotes

Removing different kinds of brackets:

echo '[{Hi}]' | tr -d {}[]
# Produces Hi without brackets

-d stands for "delete".

Delete specified file from document directory

In Swift both 3&4

 func removeImageLocalPath(localPathName:String) {
            let filemanager = FileManager.default
            let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask,true)[0] as NSString
            let destinationPath = documentsPath.appendingPathComponent(localPathName)
 do {
        try filemanager.removeItem(atPath: destinationPath)
        print("Local path removed successfully")
    } catch let error as NSError {
        print("------Error",error.debugDescription)
    }
    }

or This method can delete all local file

func deletingLocalCacheAttachments(){
        let fileManager = FileManager.default
        let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
        do {
            let fileURLs = try fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
            if fileURLs.count > 0{
                for fileURL in fileURLs {
                    try fileManager.removeItem(at: fileURL)
                }
            }
        } catch {
            print("Error while enumerating files \(documentsURL.path): \(error.localizedDescription)")
        }
    }

Reading from text file until EOF repeats last line

The EOF pattern needs a prime read to 'bootstrap' the EOF checking process. Consider the empty file will not initially have its EOF set until the first read. The prime read will catch the EOF in this instance and properly skip the loop completely.

What you need to remember here is that you don't get the EOF until the first attempt to read past the available data of the file. Reading the exact amount of data will not flag the EOF.

I should point out if the file was empty your given code would have printed since the EOF will have prevented a value from being set to x on entry into the loop.

  • 0

So add a prime read and move the loop's read to the end:

int x;

iFile >> x; // prime read here
while (!iFile.eof()) {
    cerr << x << endl;
    iFile >> x;
}

Can't use SURF, SIFT in OpenCV

Install Python opencv

pip install opencv-python

and instead of using ..

cv2.SIFT()

Use

cv2.SIFT_create()

working code using opencv-python below

import cv2
img1 = cv2.imread('yourimg.png',0)
sift = cv2.SIFT_create()
kp1, des1 = sift.detectAndCompute(img1,None) #keypoint and descriptors
...

you can also install "opencv-contrib-python" and use "cv2.xfeatures2d.SIFT_create()" but that is secondary and up to you.. working code using the python package opencv-contrib-python

import cv2
img1 = cv2.imread('yourimg.png',0)
sift = cv2.xfeatures2d.SIFT_create()
kp1, des1 = sift.detectAndCompute(img1,None) #keypoint and descriptors

Thanks

Relative path in HTML

You say your website is in http://localhost/mywebsite, and let's say that your image is inside a subfolder named pictures/:

Absolute path

If you use an absolute path, / would point to the root of the site, not the root of the document: localhost in your case. That's why you need to specify your document's folder in order to access the pictures folder:

"/mywebsite/pictures/picture.png"

And it would be the same as:

"http://localhost/mywebsite/pictures/picture.png"

Relative path

A relative path is always relative to the root of the document, so if your html is at the same level of the directory, you'd need to start the path directly with your picture's directory name:

"pictures/picture.png"

But there are other perks with relative paths:

dot-slash (./)

Dot (.) points to the same directory and the slash (/) gives access to it:

So this:

"pictures/picture.png"

Would be the same as this:

"./pictures/picture.png"

Double-dot-slash (../)

In this case, a double dot (..) points to the upper directory and likewise, the slash (/) gives you access to it. So if you wanted to access a picture that is on a directory one level above of the current directory your document is, your URL would look like this:

"../picture.png"

You can play around with them as much as you want, a little example would be this:

Let's say you're on directory A, and you want to access directory X.

- root
   |- a
      |- A
   |- b
   |- x
      |- X

Your URL would look either:

Absolute path

"/x/X/picture.png"

Or:

Relative path

"./../x/X/picture.png"

Set Encoding of File to UTF8 With BOM in Sublime Text 3

Into Preferences > Settings - Users
File : Preferences.sublime-settings

Write this :

"show_encoding" : true,

It's explain on the release note date 17 December 2013. Build 3059. Official site Sublime Text 3

How do you install GLUT and OpenGL in Visual Studio 2012?

For an easy and appropriate way of doing this, first download a prepackaged release of freeglut from here. Then read its Readme.txt.

I copied some important parts of that package here:

... Create a folder on your PC which is readable by all users, for example “C:\Program Files\Common Files\MSVC\freeglut\” on a typical Windows system. Copy the “lib\” and “include\” folders from this zip archive to that location ... freeglut DLL can be placed in the same folder as your application...

... Open up the project properties, and select “All Configurations” (this is necessary to ensure our changes are applied for both debug and release builds). Open up the “general” section under “C/C++”, and configure the “include\” folder you created above as an “Additional Include Directory”. If you have more than one GLUT package which contains a “glut.h” file, it’s important to ensure that the freeglut include folder appears above all other GLUT include folders ... Open up the “general” section under “Linker”, and configure the “lib\” folder you created above as an “Additional Library Directory”...

How to check for null/empty/whitespace values with a single test?

While checking null or Empty value for a column, I noticed that there are some support concerns in various Databases.

Every Database doesn't support TRIM method.

Below is the matrix just to understand the supported methods by different databases.

The TRIM function in SQL is used to remove specified prefix or suffix from a string. The most common pattern being removed is white spaces. This function is called differently in different databases:

  • MySQL: TRIM(), RTRIM(), LTRIM()
  • Oracle: RTRIM(), LTRIM()
  • SQL Server: TRIM(), RTRIM(), LTRIM()

How to Check Empty/Null/Whitespace :-

Below are two different ways according to different Databases-

The syntax for these trim functions are:

  1. Use of Trim to check-

    SELECT FirstName FROM UserDetails WHERE TRIM(LastName) IS NULL

  2. Use of LTRIM & RTRIM to check-

    SELECT FirstName FROM UserDetails WHERE LTRIM(RTRIM(LastName)) IS NULL

Above both ways provide same result just use based on your DataBase support. It Just returns the FirstName from UserDetails table if it has an empty LastName

Hoping this will help others too :)

What are the differences between delegates and events?

For people live in 2020, and want a clean answer...

Definitions:

  • delegate: defines a function pointer.
  • event: defines
    • (1) protected interfaces, and
    • (2) operations(+=, -=), and
    • (3) advantage: you don't need to use new keyword anymore.

Regarding the adjective protected:

// eventTest.SomeoneSay = null;              // Compile Error.
// eventTest.SomeoneSay = new Say(SayHello); // Compile Error.

Also notice this section from Microsoft: https://docs.microsoft.com/en-us/dotnet/standard/events/#raising-multiple-events

Code Example:

with delegate:

public class DelegateTest
{
    public delegate void Say(); // Define a pointer type "void <- ()" named "Say".
    private Say say;

    public DelegateTest() {
        say  = new Say(SayHello);     // Setup the field, Say say, first.
        say += new Say(SayGoodBye);
        
        say.Invoke();
    }
    
    public void SayHello() { /* display "Hello World!" to your GUI. */ }
    public void SayGoodBye() { /* display "Good bye!" to your GUI. */ }
}

with event:

public class EventTest
{
    public delegate void Say();
    public event Say SomeoneSay;  // Use the type "Say" to define event, an 
                                  // auto-setup-everything-good field for you.
    public EventTest() {
         SomeoneSay += SayHello;
         SomeoneSay += SayGoodBye;

         SomeoneSay();
    }
    
    public void SayHello() { /* display "Hello World!" to your GUI. */ }
    public void SayGoodBye() { /* display "Good bye!" to your GUI. */ }
}

Reference:

Event vs. Delegate - Explaining the important differences between the Event and Delegate patterns in C# and why they're useful.: https://dzone.com/articles/event-vs-delegate

Linq filter List<string> where it contains a string value from another List<string>

Try the following:

var filteredFileSet = fileList.Where(item => filterList.Contains(item));

When you iterate over filteredFileSet (See LINQ Execution) it will consist of a set of IEnumberable values. This is based on the Where Operator checking to ensure that items within the fileList data set are contained within the filterList set.

As fileList is an IEnumerable set of string values, you can pass the 'item' value directly into the Contains method.

Set Focus on EditText

For Xamarin.Android I have created this extension.

public static class ViewExtensions
{
    public static void FocusEditText(this EditText editText, Activity activity)
    {
        if (editText.RequestFocus())
        {
            InputMethodManager imm = (InputMethodManager)activity.GetSystemService(Context.InputMethodService);
            imm.ShowSoftInput(editText, ShowFlags.Implicit);
        }
    }
}

What is the exact location of MySQL database tables in XAMPP folder?

The exact location is stored in "my.ini" which exists under main mysql installation directory. In my.ini file, look for 'datadir'. This parameter points the data folder.

Align an element to bottom with flexbox

When setting your display to flex, you could simply use the flex property to mark which content can grow and which content cannot.

Flex property

_x000D_
_x000D_
div.content {_x000D_
 height: 300px;_x000D_
 display: flex;_x000D_
 flex-direction: column;_x000D_
}_x000D_
_x000D_
div.up {_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
div.down {_x000D_
  flex: none;_x000D_
}
_x000D_
<div class="content">_x000D_
  <div class="up">_x000D_
    <h1>heading 1</h1>_x000D_
    <h2>heading 2</h2>_x000D_
    <p>Some more or less text</p>_x000D_
  </div>_x000D_
_x000D_
  <div class="down">_x000D_
    <a href="/" class="button">Click me</a>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I turn a JSONArray into a JSONObject?

Can't you originally get the data as a JSONObject?

Perhaps parse the string as both a JSONObject and a JSONArray in the first place? Where is the JSON string coming from?

I'm not sure that it is possible to convert a JsonArray into a JsonObject.

I presume you are using the following from json.org

  • JSONObject.java
    A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get() and opt() methods for accessing the values by name, and put() methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.

  • JSONArray.java
    A JSONArray is an ordered sequence of values. Its external form is a string wrapped in square brackets with commas between the values. The internal form is an object having get() and opt() methods for accessing the values by index, and put() methods for adding or replacing values. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.

How to set default values in Rails?

If you are referring to ActiveRecord objects, you have (more than) two ways of doing this:

1. Use a :default parameter in the DB

E.G.

class AddSsl < ActiveRecord::Migration
  def self.up
    add_column :accounts, :ssl_enabled, :boolean, :default => true
  end

  def self.down
    remove_column :accounts, :ssl_enabled
  end
end

More info here: http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

2. Use a callback

E.G. before_validation_on_create

More info here: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html#M002147

#1273 - Unknown collation: 'utf8mb4_unicode_ci' cPanel

The easiest way to do is export your database to .sql, open it on Notepad++ and "Search and Replace" the utf8mb4_unicode_ci to utf8_unicode_ci and also replace utf8mb4 to utf8. Also don't forget to change the database collation to utf8_unicode_ci (Operations > Collation).

Slide right to left?

You can define first the width of the element as 0, floating right, and then on the event that you are about to show it.. it would be like

$('#the_element_to_slide_from_right_left').animate({ width:'your desired width' }, 600);

Simple as that.

rand() returns the same number each time the program is run

For what its worth you are also only generating numbers between 0 and 99 (inclusive). If you wanted to generate values between 0 and 100 you would need.

rand() % 101

in addition to calling srand() as mentioned by others.

Export Postgresql table data using pgAdmin

  1. Right-click on your table and pick option Backup..
  2. On File Options, set Filepath/Filename and pick PLAIN for Format
  3. Ignore Dump Options #1 tab
  4. In Dump Options #2 tab, check USE INSERT COMMANDS
  5. In Dump Options #2 tab, check Use Column Inserts if you want column names in your inserts.
  6. Hit Backup button

Line break (like <br>) using only css

You can use ::after to create a 0px-height block after the <h4>, which effectively moves anything after the <h4> to the next line:

_x000D_
_x000D_
h4 {_x000D_
  display: inline;_x000D_
}_x000D_
h4::after {_x000D_
  content: "";_x000D_
  display: block;_x000D_
}
_x000D_
<ul>_x000D_
  <li>_x000D_
    Text, text, text, text, text. <h4>Sub header</h4>_x000D_
    Text, text, text, text, text._x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How do you format code in Visual Studio Code (VSCode)

You have to install the appropriate plug-in first (i.e., XML, C#, etc.).

Formatting won't become available until you've installed the relevant plugin, and saved the file with an appropriate extension.

How to find the lowest common ancestor of two nodes in any binary tree?

Here is the C++ way of doing it. Have tried to keep the algorithm as much easy as possible to understand:

// Assuming that `BinaryNode_t` has `getData()`, `getLeft()` and `getRight()`
class LowestCommonAncestor
{
  typedef char type;    
  // Data members which would behave as place holders
  const BinaryNode_t* m_pLCA;
  type m_Node1, m_Node2;

  static const unsigned int TOTAL_NODES = 2;

  // The core function which actually finds the LCA; It returns the number of nodes found
  // At any point of time if the number of nodes found are 2, then it updates the `m_pLCA` and once updated, we have found it!
  unsigned int Search (const BinaryNode_t* const pNode)
  {
    if(pNode == 0)
      return 0;

    unsigned int found = 0;

    found += (pNode->getData() == m_Node1);
    found += (pNode->getData() == m_Node2);

    found += Search(pNode->getLeft()); // below condition can be after this as well
    found += Search(pNode->getRight());

    if(found == TOTAL_NODES && m_pLCA == 0)
      m_pLCA = pNode;  // found !

    return found;
  }

public:
  // Interface method which will be called externally by the client
  const BinaryNode_t* Search (const BinaryNode_t* const pHead,
                              const type node1,
                              const type node2)
  {
    // Initialize the data members of the class
    m_Node1 = node1;
    m_Node2 = node2;
    m_pLCA = 0;

    // Find the LCA, populate to `m_pLCANode` and return
    (void) Search(pHead);
    return m_pLCA;
  }
};

How to use it:

LowestCommonAncestor lca;
BinaryNode_t* pNode = lca.Search(pWhateverBinaryTreeNodeToBeginWith);
if(pNode != 0)
  ...

What is a segmentation fault?

There are several good explanations of "Segmentation fault" in the answers, but since with segmentation fault often there's a dump of the memory content, I wanted to share where the relationship between the "core dumped" part in Segmentation fault (core dumped) and memory comes from:

From about 1955 to 1975 - before semiconductor memory - the dominant technology in computer memory used tiny magnetic doughnuts strung on copper wires. The doughnuts were known as "ferrite cores" and main memory thus known as "core memory" or "core".

Taken from here.

How to define a Sql Server connection string to use in VB.NET?

Imports System.Data.SqlClient
Imports System.Data.Sql
Imports System.IO
Imports System.Configuration
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConString").ConnectionString
Dim cn As New SqlConnection(connectionString)
Dim cmd As New SqlCommand
Dim dr As SqlDataAdapter

One-liner if statements, how to convert this if-else-statement

If expression returns a boolean, you can just return the result of it.

Example

 return (a > b)

Convert a binary NodeJS Buffer to JavaScript ArrayBuffer

Use the following excellent npm package: to-arraybuffer.

Or, you can implement it yourself. If your buffer is called buf, do this:

buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)

How to use OpenCV SimpleBlobDetector

You may store the parameters for the blob detector in a file, but this is not necessary. Example:

// set up the parameters (check the defaults in opencv's code in blobdetector.cpp)
cv::SimpleBlobDetector::Params params;
params.minDistBetweenBlobs = 50.0f;
params.filterByInertia = false;
params.filterByConvexity = false;
params.filterByColor = false;
params.filterByCircularity = false;
params.filterByArea = true;
params.minArea = 20.0f;
params.maxArea = 500.0f;
// ... any other params you don't want default value

// set up and create the detector using the parameters
cv::SimpleBlobDetector blob_detector(params);
// or cv::Ptr<cv::SimpleBlobDetector> detector = cv::SimpleBlobDetector::create(params)

// detect!
vector<cv::KeyPoint> keypoints;
blob_detector.detect(image, keypoints);

// extract the x y coordinates of the keypoints: 

for (int i=0; i<keypoints.size(); i++){
    float X = keypoints[i].pt.x; 
    float Y = keypoints[i].pt.y;
}

gson throws MalformedJsonException

In the debugger you don't need to add back slashes, the input field understands the special chars.

In java code you need to escape the special chars

No provider for HttpClient

You have not provided providers in your module:

<strike>import { HttpModule } from '@angular/http';</strike>
import { HttpClientModule, HttpClient } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    HttpClientModule,
    BrowserAnimationsModule,
    FormsModule,
    AppRoutingModule
  ],
  providers: [ HttpClientModule, ... ]
  // ...
})
export class MyModule { /* ... */ }

Using HttpClient in Tests

You will need to add the HttpClientTestingModule to the TestBed configuration when running ng test and getting the "No provider for HttpClient" error:

// Http testing module and mocking controller
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

// Other imports
import { TestBed } from '@angular/core/testing';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';

describe('HttpClient testing', () => {
  let httpClient: HttpClient;
  let httpTestingController: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ HttpClientTestingModule ]
    });

    // Inject the http service and test controller for each test
    httpClient = TestBed.get(HttpClient);
    httpTestingController = TestBed.get(HttpTestingController);
  });

  it('works', () => {
  });
});

Compiling php with curl, where is curl installed?

For Ubuntu 17.0 +

Adding to @netcoder answer above, If you are using Ubuntu 17+, installing libcurl header files is half of the solution. The installation path in ubuntu 17.0+ is different than the installation path in older Ubuntu version. After installing libcurl, you will still get the "cURL not found" error. You need to perform one extra step (as suggested by @minhajul in the OP comment section).

Add a symlink in /usr/include of the cURL installation folder (cURL installation path in Ubuntu 17.0.4 is /usr/include/x86_64-linux-gnu/curl).

My server was running Ubuntu 17.0.4, the commands to enable cURL support were

sudo apt-get install libcurl4-gnutls-dev

Then create a link to cURL installation

cd /usr/include
sudo ln -s x86_64-linux-gnu/curl

Filter output in logcat by tagname

use this:

adb logcat -s "TAGNAME"

How can I move all the files from one folder to another using the command line?

This command will move all the files in originalfolder to destinationfolder.

MOVE c:\originalfolder\* c:\destinationfolder

(However it wont move any sub-folders to the new location.)

To lookup the instructions for the MOVE command type this in a windows command prompt:

MOVE /?

C#/Linq: Apply a mapping function to each element in an IEnumerable?

You're looking for Select which can be used to transform\project the input sequence:

IEnumerable<string> strings = integers.Select(i => i.ToString());

AngularJS: Service vs provider vs factory

Little late to the party. But I thought this is more helpful for who would like to learn (or have clarity) on developing Angular JS Custom Services using factory, service and provider methodologies.

I came across this video which explains clearly about factory, service and provider methodologies for developing AngularJS Custom Services:

https://www.youtube.com/watch?v=oUXku28ex-M

Source Code: http://www.techcbt.com/Post/353/Angular-JS-basics/how-to-develop-angularjs-custom-service

Code posted here is copied straight from the above source, to benefit readers.

The code for "factory" based custom service is as follows (which goes with both sync and async versions along with calling http service):

_x000D_
_x000D_
var app = angular.module("app", []);_x000D_
app.controller('emp', ['$scope', 'calcFactory',_x000D_
  function($scope, calcFactory) {_x000D_
    $scope.a = 10;_x000D_
    $scope.b = 20;_x000D_
_x000D_
    $scope.doSum = function() {_x000D_
      //$scope.sum = calcFactory.getSum($scope.a, $scope.b); //synchronous_x000D_
      calcFactory.getSum($scope.a, $scope.b, function(r) { //aynchronous_x000D_
        $scope.sum = r;_x000D_
      });_x000D_
    };_x000D_
_x000D_
  }_x000D_
]);_x000D_
_x000D_
app.factory('calcFactory', ['$http', '$log',_x000D_
  function($http, $log) {_x000D_
    $log.log("instantiating calcFactory..");_x000D_
    var oCalcService = {};_x000D_
_x000D_
    //oCalcService.getSum = function(a,b){_x000D_
    // return parseInt(a) + parseInt(b);_x000D_
    //};_x000D_
_x000D_
    //oCalcService.getSum = function(a, b, cb){_x000D_
    // var s = parseInt(a) + parseInt(b);_x000D_
    // cb(s);_x000D_
    //};_x000D_
_x000D_
    oCalcService.getSum = function(a, b, cb) { //using http service_x000D_
_x000D_
      $http({_x000D_
        url: 'http://localhost:4467/Sum?a=' + a + '&b=' + b,_x000D_
        method: 'GET'_x000D_
      }).then(function(resp) {_x000D_
        $log.log(resp.data);_x000D_
        cb(resp.data);_x000D_
      }, function(resp) {_x000D_
        $log.error("ERROR occurred");_x000D_
      });_x000D_
    };_x000D_
_x000D_
    return oCalcService;_x000D_
  }_x000D_
]);
_x000D_
_x000D_
_x000D_

The code for "service" methodology for Custom Services (this is pretty similar to 'factory', but different from syntax point of view):

_x000D_
_x000D_
var app = angular.module("app", []);_x000D_
app.controller('emp', ['$scope', 'calcService', function($scope, calcService){_x000D_
 $scope.a = 10;_x000D_
 $scope.b = 20;_x000D_
_x000D_
 $scope.doSum = function(){_x000D_
  //$scope.sum = calcService.getSum($scope.a, $scope.b);_x000D_
  _x000D_
  calcService.getSum($scope.a, $scope.b, function(r){_x000D_
   $scope.sum = r;_x000D_
  });  _x000D_
 };_x000D_
_x000D_
}]);_x000D_
_x000D_
app.service('calcService', ['$http', '$log', function($http, $log){_x000D_
 $log.log("instantiating calcService..");_x000D_
 _x000D_
 //this.getSum = function(a,b){_x000D_
 // return parseInt(a) + parseInt(b);_x000D_
 //};_x000D_
_x000D_
 //this.getSum = function(a, b, cb){_x000D_
 // var s = parseInt(a) + parseInt(b);_x000D_
 // cb(s);_x000D_
 //};_x000D_
_x000D_
 this.getSum = function(a, b, cb){_x000D_
  $http({_x000D_
   url: 'http://localhost:4467/Sum?a=' + a + '&b=' + b,_x000D_
   method: 'GET'_x000D_
  }).then(function(resp){_x000D_
   $log.log(resp.data);_x000D_
   cb(resp.data);_x000D_
  },function(resp){_x000D_
   $log.error("ERROR occurred");_x000D_
  });_x000D_
 };_x000D_
_x000D_
}]);
_x000D_
_x000D_
_x000D_

The code for "provider" methodology for Custom Services (this is necessary, if you would like to develop service which could be configured):

_x000D_
_x000D_
var app = angular.module("app", []);_x000D_
app.controller('emp', ['$scope', 'calcService', function($scope, calcService){_x000D_
 $scope.a = 10;_x000D_
 $scope.b = 20;_x000D_
_x000D_
 $scope.doSum = function(){_x000D_
  //$scope.sum = calcService.getSum($scope.a, $scope.b);_x000D_
  _x000D_
  calcService.getSum($scope.a, $scope.b, function(r){_x000D_
   $scope.sum = r;_x000D_
  });  _x000D_
 };_x000D_
_x000D_
}]);_x000D_
_x000D_
app.provider('calcService', function(){_x000D_
_x000D_
 var baseUrl = '';_x000D_
_x000D_
 this.config = function(url){_x000D_
  baseUrl = url;_x000D_
 };_x000D_
_x000D_
 this.$get = ['$log', '$http', function($log, $http){_x000D_
  $log.log("instantiating calcService...")_x000D_
  var oCalcService = {};_x000D_
_x000D_
  //oCalcService.getSum = function(a,b){_x000D_
  // return parseInt(a) + parseInt(b);_x000D_
  //};_x000D_
_x000D_
  //oCalcService.getSum = function(a, b, cb){_x000D_
  // var s = parseInt(a) + parseInt(b);_x000D_
  // cb(s); _x000D_
  //};_x000D_
_x000D_
  oCalcService.getSum = function(a, b, cb){_x000D_
_x000D_
   $http({_x000D_
    url: baseUrl + '/Sum?a=' + a + '&b=' + b,_x000D_
    method: 'GET'_x000D_
   }).then(function(resp){_x000D_
    $log.log(resp.data);_x000D_
    cb(resp.data);_x000D_
   },function(resp){_x000D_
    $log.error("ERROR occurred");_x000D_
   });_x000D_
  };  _x000D_
_x000D_
  return oCalcService;_x000D_
 }];_x000D_
_x000D_
});_x000D_
_x000D_
app.config(['calcServiceProvider', function(calcServiceProvider){_x000D_
 calcServiceProvider.config("http://localhost:4467");_x000D_
}]);
_x000D_
_x000D_
_x000D_

Finally the UI which works with any of the above services:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
 <title></title>_x000D_
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js" ></script>_x000D_
 <script type="text/javascript" src="t03.js"></script>_x000D_
</head>_x000D_
<body ng-app="app">_x000D_
 <div ng-controller="emp">_x000D_
  <div>_x000D_
   Value of a is {{a}},_x000D_
   but you can change_x000D_
   <input type=text ng-model="a" /> <br>_x000D_
_x000D_
   Value of b is {{b}},_x000D_
   but you can change_x000D_
   <input type=text ng-model="b" /> <br>_x000D_
_x000D_
  </div>_x000D_
  Sum = {{sum}}<br>_x000D_
  <button ng-click="doSum()">Calculate</button>_x000D_
 </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

No notification sound when sending notification from firebase in android

The onMessageReceived method is fired only when app is in foreground or the notification payload only contains the data type.

From the Firebase docs

For downstream messaging, FCM provides two types of payload: notification and data.

For notification type, FCM automatically displays the message to end-user devices on behalf of the client app. Notifications have a predefined set of user-visible keys.
For data type, client app is responsible for processing data messages. Data messages have only custom key-value pairs.

Use notifications when you want FCM to handle displaying a notification on your client app's behalf. Use data messages when you want your app to handle the display or process the messages on your Android client app, or if you want to send messages to iOS devices when there is a direct FCM connection.

Further down the docs

App behaviour when receiving messages that include both notification and data payloads depends on whether the app is in the background or the foreground—essentially, whether or not it is active at the time of receipt.
When in the background, apps receive the notification payload in the notification tray, and only handle the data payload when the user taps on the notification.
When in the foreground, your app receives a message object with both payloads available.

If you are using the firebase console to send notifications, the payload will always contain the notification type. You have to use the Firebase API to send the notification with only the data type in the notification payload. That way your app is always notified when a new notification is received and the app can handle the notification payload.

If you want to play notification sound when app is in background using the conventional method, you need to add the sound parameter to the notification payload.

Simulating a click in jQuery/JavaScript on a link

You can use the the click function to trigger the click event on the selected element.

Example:

$( 'selector for your link' ).click ();

You can learn about various selectors in jQuery's documentation.

EDIT: like the commenters below have said; this only works on events attached with jQuery, inline or in the style of "element.onclick". It does not work with addEventListener, and it will not follow the link if no event handlers are defined. You could solve this with something like this:

var linkEl = $( 'link selector' );
if ( linkEl.attr ( 'onclick' ) === undefined ) {
    document.location = linkEl.attr ( 'href' );
} else {
    linkEl.click ();
}

Don't know about addEventListener though.

Add and remove multiple classes in jQuery

easiest way to append class name using javascript. It can be useful when .siblings() are misbehaving.

document.getElementById('myId').className += ' active';

Postgres: check if array field contains value?

This should work:

select * from mytable where 'Journal'=ANY(pub_types);

i.e. the syntax is <value> = ANY ( <array> ). Also notice that string literals in postresql are written with single quotes.

Is this a good way to clone an object in ES6?

Following on from the answer by @marcel I found some functions were still missing on the cloned object. e.g.

function MyObject() {
  var methodAValue = null,
      methodBValue = null

  Object.defineProperty(this, "methodA", {
    get: function() { return methodAValue; },
    set: function(value) {
      methodAValue = value || {};
    },
    enumerable: true
  });

  Object.defineProperty(this, "methodB", {
    get: function() { return methodAValue; },
    set: function(value) {
      methodAValue = value || {};
    }
  });
}

where on MyObject I could clone methodA but methodB was excluded. This occurred because it is missing

enumerable: true

which meant it did not show up in

for(let key in item)

Instead I switched over to

Object.getOwnPropertyNames(item).forEach((key) => {
    ....
  });

which will include non-enumerable keys.

I also found that the prototype (proto) was not cloned. For that I ended up using

if (obj.__proto__) {
  copy.__proto__ = Object.assign(Object.create(Object.getPrototypeOf(obj)), obj);
}

PS: Frustrating that I could not find a built in function to do this.

In Mongoose, how do I sort by date? (node.js)

Been dealing with this issue today using Mongoose 3.5(.2) and none of the answers quite helped me solve this issue. The following code snippet does the trick

Post.find().sort('-posted').find(function (err, posts) {
    // user posts array
});

You can send any standard parameters you need to find() (e.g. where clauses and return fields) but no callback. Without a callback it returns a Query object which you chain sort() on. You need to call find() again (with or without more parameters -- shouldn't need any for efficiency reasons) which will allow you to get the result set in your callback.

Visual Studio Expand/Collapse keyboard shortcuts

Collapse to definitions

CTRL + M, O

Expand all outlining

CTRL + M, X

Expand or collapse everything

CTRL + M, L

This also works with other languages like TypeScript and JavaScript

How do I detect whether 32-bit Java is installed on x64 Windows, only looking at the filesystem and registry?

If it is not Oracle's Java, you may not be able to tell. When I install Oracle Java 64-bit, the files go into C:\Program Files\Java, but when I install a 32-bit version, they default to C:\Program Files (x86)\Java instead. Of course, the person who installed Java could have overridden those defaults.

Prevent flex items from stretching

You don't want to stretch the span in height?
You have the possiblity to affect one or more flex-items to don't stretch the full height of the container.

To affect all flex-items of the container, choose this:
You have to set align-items: flex-start; to div and all flex-items of this container get the height of their content.

_x000D_
_x000D_
div {_x000D_
  align-items: flex-start;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}
_x000D_
<div>_x000D_
  <span>This is some text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

To affect only a single flex-item, choose this:
If you want to unstretch a single flex-item on the container, you have to set align-self: flex-start; to this flex-item. All other flex-items of the container aren't affected.

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
  background: tan;_x000D_
}_x000D_
span.only {_x000D_
  background: red;_x000D_
  align-self:flex-start;_x000D_
}_x000D_
span {_x000D_
    background:green;_x000D_
}
_x000D_
<div>_x000D_
  <span class="only">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why is this happening to the span?
The default value of the property align-items is stretch. This is the reason why the span fill the height of the div.

Difference between baseline and flex-start?
If you have some text on the flex-items, with different font-sizes, you can use the baseline of the first line to place the flex-item vertically. A flex-item with a smaller font-size have some space between the container and itself at top. With flex-start the flex-item will be set to the top of the container (without space).

_x000D_
_x000D_
div {_x000D_
  align-items: baseline;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}_x000D_
span.fontsize {_x000D_
  font-size:2em;_x000D_
}
_x000D_
<div>_x000D_
  <span class="fontsize">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can find more information about the difference between baseline and flex-start here:
What's the difference between flex-start and baseline?

Why is sed not recognizing \t as a tab?

TAB=$(printf '\t')
sed "s/${TAB}//g" input_file

It works for me on Red Hat, which will remove tabs from the input file.

How do I prevent site scraping?

Most have been already said, but have you considered the CloudFlare protection? I mean this:

image description

Other companies probably do this too, CloudFlare is the only one I know.

I'm pretty sure that would complicate their work. I also once got IP banned automatically for 4 months when I tried to scrap data of a site protected by CloudFlare due to rate limit (I used simple AJAX request loop).

Creating a daemon in Linux

If your app is one of:

{
  ".sh": "bash",
  ".py": "python",
  ".rb": "ruby",
  ".coffee" : "coffee",
  ".php": "php",
  ".pl" : "perl",
  ".js" : "node"
}

and you don't mind a NodeJS dependency then install NodeJS and then:

npm install -g pm2

pm2 start yourapp.yourext --name "fred" # where .yourext is one of the above

pm2 start yourapp.yourext -i 0 --name "fred" # run your app on all cores

pm2 list

To keep all apps running on reboot (and daemonise pm2):

pm2 startup

pm2 save

Now you can:

service pm2 stop|restart|start|status

(also easily allows you to watch for code changes in your app directory and auto restart the app process when a code change happens)

Angular 2 Hover event

In your js/ts file for the html that will be hovered

@Output() elemHovered: EventEmitter<any> = new EventEmitter<any>();
onHoverEnter(): void {
    this.elemHovered.emit([`The button was entered!`,this.event]);
}

onHoverLeave(): void {
    this.elemHovered.emit([`The button was left!`,this.event])
}

In your HTML that will be hovered

 (mouseenter) = "onHoverEnter()" (mouseleave)="onHoverLeave()"

In your js/ts file that will receive info of the hovering

elemHoveredCatch(d): void {
    console.log(d)
}

In your HTML element that is connected with catching js/ts file

(elemHovered) = "elemHoveredCatch($event)"

Xcode is not currently available from the Software Update server

I know this is an old post but I also ran into this problem today. I found out that when I executed sudo softwareupdate -l the Command Line Tools were listed as an update, so I installed them using sudo softwareupdate -i -a.

Get last 5 characters in a string

I opened this thread looking for a quick solution to a simple question, but I found that the answers here were either not helpful or overly complicated. The best way to get the last 5 chars of a string is, in fact, to use the Right() method. Here is a simple example:

Dim sMyString, sLast5 As String

sMyString = "I will be going to school in 2011!"
sLast5 = Right(sMyString, - 5)
MsgBox("sLast5 = " & sLast5)

If you're getting an error then there is probably something wrong with your syntax. Also, with the Right() method you don't need to worry much about going over or under the string length. In my example you could type in 10000 instead of 5 and it would just MsgBox the whole string, or if sMyString was NULL or "", the message box would just pop up with nothing.

npm notice created a lockfile as package-lock.json. You should commit this file

Yes. You should add this file to your version control system, i.e. You should commit it.

This file is intended to be committed into source repositories

You can read more about what it is/what it does here:

package-lock.json is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.

How do I set the rounded corner radius of a color drawable using xml?

mbaird's answer works fine. Just be aware that there seems to be a bug in Android (2.1 at least), that if you set any individual corner's radius to 0, it forces all the corners to 0 (at least that's the case with "dp" units; I didn't try it with any other units).

I needed a shape where the top corners were rounded and the bottom corners were square. I got achieved this by setting the corners I wanted to be square to a value slightly larger than 0: 0.1dp. This still renders as square corners, but it doesn't force the other corners to be 0 radius.

Comparing two joda DateTime instances

This code (example) :

    Chronology ch1 = GregorianChronology.getInstance();     Chronology ch2 = ISOChronology.getInstance();      DateTime dt = new DateTime("2013-12-31T22:59:21+01:00",ch1);     DateTime dt2 = new DateTime("2013-12-31T22:59:21+01:00",ch2);      System.out.println(dt);     System.out.println(dt2);      boolean b = dt.equals(dt2);      System.out.println(b); 

Will print :

2013-12-31T16:59:21.000-05:00 2013-12-31T16:59:21.000-05:00 false 

You are probably comparing two DateTimes with same date but different Chronology.

PSEXEC, access denied errors

I just added "-?" parameter. It makes Psexec copy executable to remote machine. So it works without access errors.

Using headers with the Python requests library's get method

Seems pretty straightforward, according to the docs on the page you linked (emphasis mine).

requests.get(url, params=None, headers=None, cookies=None, auth=None, timeout=None)

Sends a GET request. Returns Response object.

Parameters:

  • url – URL for the new Request object.
  • params – (optional) Dictionary of GET Parameters to send with the Request.
  • headers – (optional) Dictionary of HTTP Headers to send with the Request.
  • cookies – (optional) CookieJar object to send with the Request.
  • auth – (optional) AuthObject to enable Basic HTTP Auth.
  • timeout – (optional) Float describing the timeout of the request.

parent & child with position fixed, parent overflow:hidden bug

Because a fixed position element is fixed with respect to the viewport, not another element. Therefore since the viewport isn't cutting it off, the overflow becomes irrelevant.

Whereas the position and dimensions of an element with position:absolute are relative to its containing block, the position and dimensions of an element with position:fixed are always relative to the initial containing block. This is normally the viewport: the browser window or the paper’s page box.

ref: http://www.w3.org/wiki/CSS_absolute_and_fixed_positioning#Fixed_positioning

Java - Check if JTextField is empty or not

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // Submit Button        

    String Fname = jTextField1.getText();
    String Lname = jTextField2.getText();
    String Desig = jTextField3.getText();
    String Nic = jTextField4.getText();
    String Phone = jTextField5.getText();
    String Add = jTextArea1.getText();
    String Dob = jTextField6.getText();
    // String Gender;
    // Image

    if (Fname.hashCode() == 0 || Lname.hashCode() == 0 || Desig.hashCode() == 0 || Nic.hashCode() == 0 || Phone.hashCode() == 0 || Add.hashCode() == 0)
    {
        JOptionPane.showMessageDialog(null, "Some fields are empty!");
    }
    else
    {
        JOptionPane.showMessageDialog(null, "OK");
    }
}

PHP/MySQL: How to create a comment section in your website

You can create a 'comment' table, with an id as primary key, then you add a text field to capture the text inserted by the user and you need another field to link the comment table to the article table (foreign key). Plus you need a field to store the user that has entered a comment, this field can be the user's email. Then you capture via GET or POST the user's email and comment and you insert everything in the DB:

"INSERT INTO comment (comment, email, approved) VALUES ('$comment', '$email', '$approved')"

This is a first hint. Of course adding a comment feature it takes a little bit. Then you should think about a form to let the admin to approve the comments and how to publish the comments in the end of articles.

Disable XML validation in Eclipse

In JBoss Developer 4.0 and above (Eclipse-based), this is a tad easier. Just right-click on your file or folder that contains xml-based files, choose "Exclude Validation", then click "Yes" to confirm. Then right-click the same files/folder again and click on "Validate", which will remove the errors with a confirmation.

Change language for bootstrap DateTimePicker

1.you will use different locale array element in datepicker.js from following link https://github.com/smalot/bootstrap-datetimepicker/tree/master/js/locales

2.add array in datepicker.js like this:

_x000D_
_x000D_
$.fn.datepicker.Constructor = Datepicker;_x000D_
    var dates = $.fn.datepicker.dates = {_x000D_
        en: {_x000D_
            days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],_x000D_
            daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],_x000D_
            daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],_x000D_
            months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],_x000D_
            monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],_x000D_
            today: "Today"_x000D_
        },_x000D_
        CN:{_x000D_
        days: ["???", "???", "???", "???", "???", "???", "???", "???"],_x000D_
        daysShort: ["??", "??", "??", "??", "??", "??", "??", "??"],_x000D_
    daysMin: ["?", "?", "?", "?", "?", "?", "?", "?"],_x000D_
    months: ["??", "??", "??", "??", "??", "??", "??", "??", "??", "??", "???", "???"],_x000D_
    monthsShort: ["??", "??", "??", "??", "??", "??", "??", "??", "??", "??", "???", "???"],_x000D_
    today: "??",_x000D_
    suffix: [],_x000D_
    meridiem: ["??", "??"]_x000D_
}_x000D_
 };
_x000D_
_x000D_
_x000D_

Interface extends another interface but implements its methods

ad 1. It does not implement its methods.

ad 4. The purpose of one interface extending, not implementing another, is to build a more specific interface. For example, SortedMap is an interface that extends Map. A client not interested in the sorting aspect can code against Map and handle all the instances of for example TreeMap, which implements SortedMap. At the same time, another client interested in the sorted aspect can use those same instances through the SortedMap interface.

In your example you are repeating the methods from the superinterface. While legal, it's unnecessary and doesn't change anything in the end result. The compiled code will be exactly the same whether these methods are there or not. Whatever Eclipse's hover says is irrelevant to the basic truth that an interface does not implement anything.

how to get the ipaddress of a virtual box running on local machine

Login to virtual machine use below command to check ip address. (anyone will work)

  1. ifconfig
  2. ip addr show

If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1

If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine

How to implement linear interpolation?

Building on Lauritz` answer, here's a version with the following changes

  • Updated to python3 (the map was causing problems for me and is unnecessary)
  • Fixed behavior at edge values
  • Raise exception when x is out of bounds
  • Use __call__ instead of __getitem__
from bisect import bisect_right

class Interpolate:
    def __init__(self, x_list, y_list):
        if any(y - x <= 0 for x, y in zip(x_list, x_list[1:])):
            raise ValueError("x_list must be in strictly ascending order!")
        self.x_list = x_list
        self.y_list = y_list
        intervals = zip(x_list, x_list[1:], y_list, y_list[1:])
        self.slopes = [(y2 - y1) / (x2 - x1) for x1, x2, y1, y2 in intervals]

    def __call__(self, x):
        if not (self.x_list[0] <= x <= self.x_list[-1]):
            raise ValueError("x out of bounds!")
        if x == self.x_list[-1]:
            return self.y_list[-1]
        i = bisect_right(self.x_list, x) - 1
        return self.y_list[i] + self.slopes[i] * (x - self.x_list[i])

Example usage:

>>> interp = Interpolate([1, 2.5, 3.4, 5.8, 6], [2, 4, 5.8, 4.3, 4])
>>> interp(4)
5.425

How to convert a char array to a string?

There is a small problem missed in top-voted answers. Namely, character array may contain 0. If we will use constructor with single parameter as pointed above we will lose some data. The possible solution is:

cout << string("123\0 123") << endl;
cout << string("123\0 123", 8) << endl;

Output is:

123
123 123

What is the difference between an interface and abstract class?

An explanation can be found here: http://www.developer.com/lang/php/article.php/3604111/PHP-5-OOP-Interfaces-Abstract-Classes-and-the-Adapter-Pattern.htm

An abstract class is a class that is only partially implemented by the programmer. It may contain one or more abstract methods. An abstract method is simply a function definition that serves to tell the programmer that the method must be implemented in a child class.

An interface is similar to an abstract class; indeed interfaces occupy the same namespace as classes and abstract classes. For that reason, you cannot define an interface with the same name as a class. An interface is a fully abstract class; none of its methods are implemented and instead of a class sub-classing from it, it is said to implement that interface.

Anyway I find this explanation of interfaces somewhat confusing. A more common definition is: An interface defines a contract that implementing classes must fulfill. An interface definition consists of signatures of public members, without any implementing code.

Difference between `Optional.orElse()` and `Optional.orElseGet()`

The difference is pretty subtle and if you dont pay much attention then you will keep it using in a wrong way.

Best way to understand the difference between orElse() and orElseGet() is that orElse() will always be executed if the Optional<T> is null or not, But orElseGet() will only be executed when Optional<T> is null.

The dictionary meaning of orElse is :- execute the part when something is not present, but here it contradicts, see the below example:

    Optional<String> nonEmptyOptional = Optional.of("Vishwa Ratna");
    String value = nonEmptyOptional.orElse(iAmStillExecuted());

    public static String iAmStillExecuted(){
    System.out.println("nonEmptyOptional is not NULL,still I am being executed");
    return "I got executed";
    }

Output: nonEmptyOptional is not NULL,still I am being executed


    Optional<String> emptyOptional = Optional.ofNullable(null);
    String value = emptyOptional.orElse(iAmStillExecuted());
    public static String iAmStillExecuted(){
    System.out.println("emptyOptional is NULL, I am being executed, it is normal as 
    per dictionary");
    return "I got executed";
    }

Output: emptyOptional is NULL, I am being executed, it is normal as per dictionary

For orElseGet() , The method goes as per dictionary meaning, The orElseGet() part will be executed only when the Optional is null.

Benchmarks:

+--------------------+------+-----+------------+-------------+-------+
| Benchmark          | Mode | Cnt | Score      | Error       | Units |
+--------------------+------+-----+------------+-------------+-------+
| orElseBenchmark    | avgt | 20  | 60934.425  | ± 15115.599 | ns/op |
+--------------------+------+-----+------------+-------------+-------+
| orElseGetBenchmark | avgt | 20  | 3.798      | ± 0.030     | ns/op |
+--------------------+------+-----+------------+-------------+-------+

Remarks: orElseGet() has clearly outperformed orElse() for our particular example.

Hope it clears the doubts of people like me who wants the very basic ground example :)

Import .bak file to a database in SQL server

Simply use

sp_restoredb 'Your Database Name' ,'Location From you want to restore'

Example: sp_restoredb 'omDB','D:\abc.bak'

Implementing INotifyPropertyChanged - does a better way exist?

I resolved in This Way (it's a little bit laboriouse, but it's surely the faster in runtime).

In VB (sorry, but I think it's not hard translate it in C#), I make this substitution with RE:

(?<Attr><(.*ComponentModel\.)Bindable\(True\)>)( |\r\n)*(?<Def>(Public|Private|Friend|Protected) .*Property )(?<Name>[^ ]*) As (?<Type>.*?)[ |\r\n](?![ |\r\n]*Get)

with:

Private _${Name} As ${Type}\r\n${Attr}\r\n${Def}${Name} As ${Type}\r\nGet\r\nReturn _${Name}\r\nEnd Get\r\nSet (Value As ${Type})\r\nIf _${Name} <> Value Then \r\n_${Name} = Value\r\nRaiseEvent PropertyChanged(Me, New ComponentModel.PropertyChangedEventArgs("${Name}"))\r\nEnd If\r\nEnd Set\r\nEnd Property\r\n

This transofrm all code like this:

<Bindable(True)>
Protected Friend Property StartDate As DateTime?

In

Private _StartDate As DateTime?
<Bindable(True)>
Protected Friend Property StartDate As DateTime?
    Get
        Return _StartDate
    End Get
    Set(Value As DateTime?)
        If _StartDate <> Value Then
            _StartDate = Value
            RaiseEvent PropertyChange(Me, New ComponentModel.PropertyChangedEventArgs("StartDate"))
        End If
    End Set
End Property

And If I want to have a more readable code, I can be the opposite just making the following substitution:

Private _(?<Name>.*) As (?<Type>.*)[\r\n ]*(?<Attr><(.*ComponentModel\.)Bindable\(True\)>)[\r\n ]*(?<Def>(Public|Private|Friend|Protected) .*Property )\k<Name> As \k<Type>[\r\n ]*Get[\r\n ]*Return _\k<Name>[\r\n ]*End Get[\r\n ]*Set\(Value As \k<Type>\)[\r\n ]*If _\k<Name> <> Value Then[\r\n ]*_\k<Name> = Value[\r\n ]*RaiseEvent PropertyChanged\(Me, New (.*ComponentModel\.)PropertyChangedEventArgs\("\k<Name>"\)\)[\r\n ]*End If[\r\n ]*End Set[\r\n ]*End Property

With

${Attr} ${Def} ${Name} As ${Type}

I throw to replace the IL code of the set method, but I can't write a lot of compiled code in IL... If a day I write it, I'll say you!

Working with INTERVAL and CURDATE in MySQL

You need DATE_ADD/DATE_SUB:

AND v.date > (DATE_SUB(CURDATE(), INTERVAL 2 MONTH))
AND v.date < (DATE_SUB(CURDATE(), INTERVAL 1 MONTH))

should work.

COPY with docker but with exclusion

For those who can't use a .dockerignore file (e.g. if you need the file in one COPY but not another):

Yes, but you need multiple COPY instructions. Specifically, you need a COPY for each letter in the filename you wish to exclude.

COPY [^n]*    # All files that don't start with 'n'
COPY n[^o]*   # All files that start with 'n', but not 'no'
COPY no[^d]*  # All files that start with 'no', but not 'nod'

Continuing until you have the full file name, or just the prefix you're reasonably sure won't have any other files.

How to sort with lambda in Python

lst = [('candy','30','100'), ('apple','10','200'), ('baby','20','300')]
lst.sort(key=lambda x:x[1])
print(lst)

It will print as following:

[('apple', '10', '200'), ('baby', '20', '300'), ('candy', '30', '100')]

What's the fastest way of checking if a point is inside a polygon in python

You can consider shapely:

from shapely.geometry import Point
from shapely.geometry.polygon import Polygon

point = Point(0.5, 0.5)
polygon = Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])
print(polygon.contains(point))

From the methods you've mentioned I've only used the second, path.contains_points, and it works fine. In any case depending on the precision you need for your test I would suggest creating a numpy bool grid with all nodes inside the polygon to be True (False if not). If you are going to make a test for a lot of points this might be faster (although notice this relies you are making a test within a "pixel" tolerance):

from matplotlib import path
import matplotlib.pyplot as plt
import numpy as np

first = -3
size  = (3-first)/100
xv,yv = np.meshgrid(np.linspace(-3,3,100),np.linspace(-3,3,100))
p = path.Path([(0,0), (0, 1), (1, 1), (1, 0)])  # square with legs length 1 and bottom left corner at the origin
flags = p.contains_points(np.hstack((xv.flatten()[:,np.newaxis],yv.flatten()[:,np.newaxis])))
grid = np.zeros((101,101),dtype='bool')
grid[((xv.flatten()-first)/size).astype('int'),((yv.flatten()-first)/size).astype('int')] = flags

xi,yi = np.random.randint(-300,300,100)/100,np.random.randint(-300,300,100)/100
vflag = grid[((xi-first)/size).astype('int'),((yi-first)/size).astype('int')]
plt.imshow(grid.T,origin='lower',interpolation='nearest',cmap='binary')
plt.scatter(((xi-first)/size).astype('int'),((yi-first)/size).astype('int'),c=vflag,cmap='Greens',s=90)
plt.show()

, the results is this:

point inside polygon within pixel tolerance

ng-change not working on a text input

When you want to edit something in Angular you need to insert an ngModel in your html

try this in your sample:

    <input type="text" name="abc" class="color" ng-model="myStyle.color">

You don't need to watch the change at all!

jQuery: Uncheck other checkbox on one checked

Bind a change handler, then just uncheck all of the checkboxes, apart from the one checked:

$('input.example').on('change', function() {
    $('input.example').not(this).prop('checked', false);  
});

Here's a fiddle

How do I update a Linq to SQL dbml file?

We use a custom written T4 template that dynamically queries the information_schema model for each table in all of our .DBML files, and then overwrites parts of the .DBML file with fresh schema info from the database. I highly recommend implementing a solution like this - it has saved me oodles of time, and unlike deleting and re-adding your tables to your model you get to keep your associations. With this solution, you'll get compile-time errors when your schema changes. You want to make sure that you're using a version control system though, because diffing is really handy. This is a great solution that works well if you're developing with a DB schema first approach. Of course, I can't share my company's code so you're on your own for writing this yourself. But if you know some Linq-to-XML and can go to school on this project, you can get to where you want to be.

Copying sets Java

Another way to do this is to use the copy constructor:

Collection<E> oldSet = ...
TreeSet<E> newSet = new TreeSet<E>(oldSet);

Or create an empty set and add the elements:

Collection<E> oldSet = ...
TreeSet<E> newSet = new TreeSet<E>();
newSet.addAll(oldSet);

Unlike clone these allow you to use a different set class, a different comparator, or even populate from some other (non-set) collection type.


Note that the result of copying a Set is a new Set containing references to the objects that are elements if the original Set. The element objects themselves are not copied or cloned. This conforms with the way that the Java Collection APIs are designed to work: they don't copy the element objects.

Python os.path.join() on a list

The problem is, os.path.join doesn't take a list as argument, it has to be separate arguments.

This is where *, the 'splat' operator comes into play...

I can do

>>> s = "c:/,home,foo,bar,some.txt".split(",")
>>> os.path.join(*s)
'c:/home\\foo\\bar\\some.txt'

Finding a branch point with Git?

Sometimes it is effectively impossible (with some exceptions of where you might be lucky to have additional data) and the solutions here wont work.

Git doesn't preserve ref history (which includes branches). It only stores the current position for each branch (the head). This means you can lose some branch history in git over time. Whenever you branch for example, it's immediately lost which branch was the original one. All a branch does is:

git checkout branch1    # refs/branch1 -> commit1
git checkout -b branch2 # branch2 -> commit1

You might assume that the first commited to is the branch. This tends to be the case but it's not always so. There's nothing stopping you from commiting to either branch first after the above operation. Additionally, git timestamps aren't guaranteed to be reliable. It's not until you commit to both that they truly become branches structurally.

While in diagrams we tend to number commits conceptually, git has no real stable concept of sequence when the commit tree branches. In this case you can assume the numbers (indicating order) are determined by timestamp (it might be fun to see how a git UI handles things when you set all the timestamps to the same).

This is what a human expect conceptually:

After branch:
       C1 (B1)
      /
    -
      \
       C1 (B2)
After first commit:
       C1 (B1)
      /
    - 
      \
       C1 - C2 (B2)

This is what you actually get:

After branch:
    - C1 (B1) (B2)
After first commit (human):
    - C1 (B1)
        \
         C2 (B2)
After first commit (real):
    - C1 (B1) - C2 (B2)

You would assume B1 to be the original branch but it could infact simply be a dead branch (someone did checkout -b but never committed to it). It's not until you commit to both that you get a legitimate branch structure within git:

Either:
      / - C2 (B1)
    -- C1
      \ - C3 (B2)
Or:
      / - C3 (B1)
    -- C1
      \ - C2 (B2)

You always know that C1 came before C2 and C3 but you never reliably know if C2 came before C3 or C3 came before C2 (because you can set the time on your workstation to anything for example). B1 and B2 is also misleading as you can't know which branch came first. You can make a very good and usually accurate guess at it in many cases. It is a bit like a race track. All things generally being equal with the cars then you can assume that a car that comes in a lap behind started a lap behind. We also have conventions that are very reliable, for example master will nearly always represent the longest lived branches although sadly I have seen cases where even this is not the case.

The example given here is a history preserving example:

Human:
    - X - A - B - C - D - F (B1)
           \     / \     /
            G - H ----- I - J (B2)
Real:
            B ----- C - D - F (B1)
           /       / \     /
    - X - A       /   \   /
           \     /     \ /
            G - H ----- I - J (B2)

Real here is also misleading because we as humans read it left to right, root to leaf (ref). Git does not do that. Where we do (A->B) in our heads git does (A<-B or B->A). It reads it from ref to root. Refs can be anywhere but tend to be leafs, at least for active branches. A ref points to a commit and commits only contain a like to their parent/s, not to their children. When a commit is a merge commit it will have more than one parent. The first parent is always the original commit that was merged into. The other parents are always commits that were merged into the original commit.

Paths:
    F->(D->(C->(B->(A->X)),(H->(G->(A->X))))),(I->(H->(G->(A->X))),(C->(B->(A->X)),(H->(G->(A->X)))))
    J->(I->(H->(G->(A->X))),(C->(B->(A->X)),(H->(G->(A->X)))))

This is not a very efficient representation, rather an expression of all the paths git can take from each ref (B1 and B2).

Git's internal storage looks more like this (not that A as a parent appears twice):

    F->D,I | D->C | C->B,H | B->A | A->X | J->I | I->H,C | H->G | G->A

If you dump a raw git commit you'll see zero or more parent fields. If there are zero, it means no parent and the commit is a root (you can actually have multiple roots). If there's one, it means there was no merge and it's not a root commit. If there is more than one it means that the commit is the result of a merge and all of the parents after the first are merge commits.

Paths simplified:
    F->(D->C),I | J->I | I->H,C | C->(B->A),H | H->(G->A) | A->X
Paths first parents only:
    F->(D->(C->(B->(A->X)))) | F->D->C->B->A->X
    J->(I->(H->(G->(A->X))) | J->I->H->G->A->X
Or:
    F->D->C | J->I | I->H | C->B->A | H->G->A | A->X
Paths first parents only simplified:
    F->D->C->B->A | J->I->->G->A | A->X
Topological:
    - X - A - B - C - D - F (B1)
           \
            G - H - I - J (B2)

When both hit A their chain will be the same, before that their chain will be entirely different. The first commit another two commits have in common is the common ancestor and from whence they diverged. there might be some confusion here between the terms commit, branch and ref. You can in fact merge a commit. This is what merge really does. A ref simply points to a commit and a branch is nothing more than a ref in the folder .git/refs/heads, the folder location is what determines that a ref is a branch rather than something else such as a tag.

Where you lose history is that merge will do one of two things depending on circumstances.

Consider:

      / - B (B1)
    - A
      \ - C (B2)

In this case a merge in either direction will create a new commit with the first parent as the commit pointed to by the current checked out branch and the second parent as the commit at the tip of the branch you merged into your current branch. It has to create a new commit as both branches have changes since their common ancestor that must be combined.

      / - B - D (B1)
    - A      /
      \ --- C (B2)

At this point D (B1) now has both sets of changes from both branches (itself and B2). However the second branch doesn't have the changes from B1. If you merge the changes from B1 into B2 so that they are syncronised then you might expect something that looks like this (you can force git merge to do it like this however with --no-ff):

Expected:
      / - B - D (B1)
    - A      / \
      \ --- C - E (B2)
Reality:
      / - B - D (B1) (B2)
    - A      /
      \ --- C

You will get that even if B1 has additional commits. As long as there aren't changes in B2 that B1 doesn't have, the two branches will be merged. It does a fast forward which is like a rebase (rebases also eat or linearise history), except unlike a rebase as only one branch has a change set it doesn't have to apply a changeset from one branch on top of that from another.

From:
      / - B - D - E (B1)
    - A      /
      \ --- C (B2)
To:
      / - B - D - E (B1) (B2)
    - A      /
      \ --- C

If you cease work on B1 then things are largely fine for preserving history in the long run. Only B1 (which might be master) will advance typically so the location of B2 in B2's history successfully represents the point that it was merged into B1. This is what git expects you to do, to branch B from A, then you can merge A into B as much as you like as changes accumulate, however when merging B back into A, it's not expected that you will work on B and further. If you carry on working on your branch after fast forward merging it back into the branch you were working on then your erasing B's previous history each time. You're really creating a new branch each time after fast forward commit to source then commit to branch. You end up with when you fast forward commit is lots of branches/merges that you can see in the history and structure but without the ability to determine what the name of that branch was or if what looks like two separate branches is really the same branch.

         0   1   2   3   4 (B1)
        /-\ /-\ /-\ /-\ /
    ----   -   -   -   -
        \-/ \-/ \-/ \-/ \
         5   6   7   8   9 (B2)

1 to 3 and 5 to 8 are structural branches that show up if you follow the history for either 4 or 9. There's no way in git to know which of this unnamed and unreferenced structural branches belong to with of the named and references branches as the end of the structure. You might assume from this drawing that 0 to 4 belongs to B1 and 4 to 9 belongs to B2 but apart from 4 and 9 was can't know which branch belongs to which branch, I've simply drawn it in a way that gives the illusion of that. 0 might belong to B2 and 5 might belong to B1. There are 16 different possibilies in this case of which named branch each of the structural branches could belong to. This is assuming that none of these structural branches came from a deleted branch or as a result of merging a branch into itself when pulling from master (the same branch name on two repos is infact two branches, a separate repository is like branching all branches).

There are a number of git strategies that work around this. You can force git merge to never fast forward and always create a merge branch. A horrible way to preserve branch history is with tags and/or branches (tags are really recommended) according to some convention of your choosing. I realy wouldn't recommend a dummy empty commit in the branch you're merging into. A very common convention is to not merge into an integration branch until you want to genuinely close your branch. This is a practice that people should attempt to adhere to as otherwise you're working around the point of having branches. However in the real world the ideal is not always practical meaning doing the right thing is not viable for every situation. If what you're doing on a branch is isolated that can work but otherwise you might be in a situation where when multiple developers are working one something they need to share their changes quickly (ideally you might really want to be working on one branch but not all situations suit that either and generally two people working on a branch is something you want to avoid).

Multiple Indexes vs Multi-Column Indexes

Yes. I recommend you check out Kimberly Tripp's articles on indexing.

If an index is "covering", then there is no need to use anything but the index. In SQL Server 2005, you can also add additional columns to the index that are not part of the key which can eliminate trips to the rest of the row.

Having multiple indexes, each on a single column may mean that only one index gets used at all - you will have to refer to the execution plan to see what effects different indexing schemes offer.

You can also use the tuning wizard to help determine what indexes would make a given query or workload perform the best.

How to increase font size in a plot in R?

Notice that "cex" does change things when the plot is made with text. For example, the plot of an agglomerative hierarchical clustering:

library(cluster)
data(votes.repub)
agn1 <- agnes(votes.repub, metric = "manhattan", stand = TRUE)
plot(agn1, which.plots=2)

will produce a plot with normal sized text:

enter image description here

and plot(agn1, which.plots=2, cex=0.5) will produce this one:

enter image description here

is inaccessible due to its protection level

In your base class Clubs the following are declared protected

  • club;
  • distance;
  • cleanclub;
  • scores;
  • par;
  • hole;

which means these can only be accessed by the class itself or any class which derives from Clubs.

In your main code, you try to access these outside of the class itself. eg:

Console.WriteLine("How far to the hole?");
myClub.distance = Console.ReadLine();

You have (somewhat correctly) provided public accessors to these variables. eg:

public string mydistance
{
    get
    {
        return distance;
    }
    set
    {
        distance = value;
    }
}        

which means your main code could be changed to

Console.WriteLine("How far to the hole?");
myClub.mydistance = Console.ReadLine();

How to pass multiple parameter to @Directives (@Components) in Angular with TypeScript?

From the Documentation

As with components, you can add as many directive property bindings as you need by stringing them along in the template.

Add an input property to HighlightDirective called defaultColor:

@Input() defaultColor: string;

Markup

<p [myHighlight]="color" defaultColor="violet">
  Highlight me too!
</p>

Angular knows that the defaultColor binding belongs to the HighlightDirective because you made it public with the @Input decorator.

Either way, the @Input decorator tells Angular that this property is public and available for binding by a parent component. Without @Input, Angular refuses to bind to the property.

For your example

With many parameters

Add properties into the Directive class with @Input() decorator

@Directive({
    selector: '[selectable]'
})
export class SelectableDirective{
    private el: HTMLElement;

    @Input('selectable') option:any;   
    @Input('first') f;
    @Input('second') s;

    ...
}

And in the template pass bound properties to your li element

<li *ngFor = 'let opt of currentQuestion.options' 
    [selectable] = 'opt' 
    [first]='YourParameterHere'
    [second]='YourParameterHere'
    (selectedOption) = 'onOptionSelection($event)'>
    {{opt.option}}
</li>

Here on the li element we have a directive with name selectable. In the selectable we have two @Input()'s, f with name first and s with name second. We have applied these two on the li properties with name [first] and [second]. And our directive will find these properties on that li element, which are set for him with @Input() decorator. So selectable, [first] and [second] will be bound to every directive on li, which has property with these names.

With single parameter

@Directive({
    selector: '[selectable]'
})
export class SelectableDirective{
    private el: HTMLElement;

    @Input('selectable') option:any;   
    @Input('params') params;

    ...
}

Markup

<li *ngFor = 'let opt of currentQuestion.options' 
    [selectable] = 'opt' 
    [params]='{firstParam: 1, seconParam: 2, thirdParam: 3}'
    (selectedOption) = 'onOptionSelection($event)'>
    {{opt.option}}
</li>

Failed to resolve: com.google.firebase:firebase-core:16.0.1

This is rare, but there is a chance your project's gradle offline mode is enable, disable offline mode with the following steps;

  • In android studio, locate the file tab of the header and click
  • In the drop own menu, select settings
  • In the dialog produced, select "Build, Execution, Deploy" and then select "Gradle"
  • Finally uncheck the "offline work" check box and apply changes

If this doesn't work leave a comment describing your Logcat response and i'll try to help more.

Programmatically go back to the previous fragment in the backstack

Android studio 4.0.1 Kotlin 1.3.72

Android Navigation architecture component.

The following code works for me:

findNavController().popBackStack()

Does Index of Array Exist

You can use LINQ to achieve that too:

var exists = array.ElementAtOrDefault(index) != null;

Set default syntax to different filetype in Sublime Text 2

In ST2 there's a package you can install called Default FileType which does just that.

More info here.

Using the GET parameter of a URL in JavaScript

Here's some sample code for that.

<script>
var param1var = getQueryVariable("param1");

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
  alert('Query Variable ' + variable + ' not found');
}
</script>

How to use concerns in Rails 4

So I found it out by myself. It is actually a pretty simple but powerful concept. It has to do with code reuse as in the example below. Basically, the idea is to extract common and / or context specific chunks of code in order to clean up the models and avoid them getting too fat and messy.

As an example, I'll put one well known pattern, the taggable pattern:

# app/models/product.rb
class Product
  include Taggable

  ...
end

# app/models/concerns/taggable.rb
# notice that the file name has to match the module name 
# (applying Rails conventions for autoloading)
module Taggable
  extend ActiveSupport::Concern

  included do
    has_many :taggings, as: :taggable
    has_many :tags, through: :taggings

    class_attribute :tag_limit
  end

  def tags_string
    tags.map(&:name).join(', ')
  end

  def tags_string=(tag_string)
    tag_names = tag_string.to_s.split(', ')

    tag_names.each do |tag_name|
      tags.build(name: tag_name)
    end
  end

  # methods defined here are going to extend the class, not the instance of it
  module ClassMethods

    def tag_limit(value)
      self.tag_limit_value = value
    end

  end

end

So following the Product sample, you can add Taggable to any class you desire and share its functionality.

This is pretty well explained by DHH:

In Rails 4, we’re going to invite programmers to use concerns with the default app/models/concerns and app/controllers/concerns directories that are automatically part of the load path. Together with the ActiveSupport::Concern wrapper, it’s just enough support to make this light-weight factoring mechanism shine.

Converting Chart.js canvas chart to image using .toDataUrl() results in blank image

You can access afterRender hook by using plugins.

And here are all the plugin api available.

In html file:

<html>
  <canvas id="myChart"></canvas>
  <div id="imgWrap"></div>
</html>

In js file:

var chart = new Chart(ctx, {
  ...,
  plugins: [{
    afterRender: function () {
      // Do anything you want
      renderIntoImage()
    },
  }],
  ...,
});

const renderIntoImage = () => {
  const canvas = document.getElementById('myChart')
  const imgWrap = document.getElementById('imgWrap')
  var img = new Image();
  img.src = canvas.toDataURL()
  imgWrap.appendChild(img)
  canvas.style.display = 'none'
}

Visual Studio Code open tab in new window

If you are using the excellent

VSCode for Mac, 2020

simply tap Apple-Shift-N (as in "new window")

Drag whatever you want there.

Accessing all items in the JToken

You can cast your JToken to a JObject and then use the Properties() method to get a list of the object properties. From there, you can get the names rather easily.

Something like this:

string json =
@"{
    ""ADDRESS_MAP"":{

        ""ADDRESS_LOCATION"":{
            ""type"":""separator"",
            ""name"":""Address"",
            ""value"":"""",
            ""FieldID"":40
        },
        ""LOCATION"":{
            ""type"":""locations"",
            ""name"":""Location"",
            ""keyword"":{
                ""1"":""LOCATION1""
            },
            ""value"":{
                ""1"":""United States""
            },
            ""FieldID"":41
        },
        ""FLOOR_NUMBER"":{
            ""type"":""number"",
            ""name"":""Floor Number"",
            ""value"":""0"",
            ""FieldID"":55
        },
        ""self"":{
            ""id"":""2"",
            ""name"":""Address Map""
        }
    }
}";

JToken outer = JToken.Parse(json);
JObject inner = outer["ADDRESS_MAP"].Value<JObject>();

List<string> keys = inner.Properties().Select(p => p.Name).ToList();

foreach (string k in keys)
{
    Console.WriteLine(k);
}

Output:

ADDRESS_LOCATION
LOCATION
FLOOR_NUMBER
self

How to get the screen width and height in iOS?

CGFloat width = [[UIScreen mainScreen] bounds].size.width; CGFloat height = [[UIScreen mainScreen]bounds ].size.height;

How to use jQuery to select a dropdown option?

answer with id:

$('#selectBoxId').find('option:eq(0)').attr('selected', true);

How to open a PDF file in an <iframe>?

It also important to make sure that the web server sends the file with Content-Disposition = inline. this might not be the case if you are reading the file yourself and send it's content to the browser:

in php it will look like this...

...headers...
header("Content-Disposition: inline; filename=doc.pdf");
...headers...

readfile('localfilepath.pdf')

Save the plots into a PDF

Never mind got the way to do it.

def plotGraph(X,Y):
     fignum = random.randint(0,sys.maxint)
     fig = plt.figure(fignum)
     ### Plotting arrangements ###
     return fig

------ plotting module ------

----- mainModule ----

 import matplotlib.pyplot as plt
 ### tempDLStats, tempDLlabels are the argument
 plot1 = plotGraph(tempDLstats, tempDLlabels)
 plot2 = plotGraph(tempDLstats_1, tempDLlabels_1)
 plot3 = plotGraph(tempDLstats_2, tempDLlabels_2)
 plt.show()
 plot1.savefig('plot1.png')
 plot2.savefig('plot2.png')
 plot3.savefig('plot3.png')

----- mainModule -----

Using C++ base class constructors?

You'll need to declare constructors in each of the derived classes, and then call the base class constructor from the initializer list:

class D : public A
{
public:
    D(const string &val) : A(0) {}
    D( int val ) : A( val ) {}
};

D variable1( "Hello" );
D variable2( 10 );

C++11 allows you to use the using A::A syntax you use in your decleration of D, but C++11 features aren't supported by all compilers just now, so best to stick with the older C++ methods until this feature is implemented in all the compilers your code will be used with.

How to save DataFrame directly to Hive?

You could use Hortonworks spark-llap library like this

import com.hortonworks.hwc.HiveWarehouseSession

df.write
  .format("com.hortonworks.spark.sql.hive.llap.HiveWarehouseConnector")
  .mode("append")
  .option("table", "myDatabase.myTable")
  .save()

How to change href attribute using JavaScript after opening the link in a new window?

You can change this in the page load.

My intention is that when the page comes to the load function, switch the links (the current link in the required one)

Drop all duplicate rows across multiple columns in Python Pandas

Just want to add to Ben's answer on drop_duplicates:

keep : {‘first’, ‘last’, False}, default ‘first’

  • first : Drop duplicates except for the first occurrence.

  • last : Drop duplicates except for the last occurrence.

  • False : Drop all duplicates.

So setting keep to False will give you desired answer.

DataFrame.drop_duplicates(*args, **kwargs) Return DataFrame with duplicate rows removed, optionally only considering certain columns

Parameters: subset : column label or sequence of labels, optional Only consider certain columns for identifying duplicates, by default use all of the columns keep : {‘first’, ‘last’, False}, default ‘first’ first : Drop duplicates except for the first occurrence. last : Drop duplicates except for the last occurrence. False : Drop all duplicates. take_last : deprecated inplace : boolean, default False Whether to drop duplicates in place or to return a copy cols : kwargs only argument of subset [deprecated] Returns: deduplicated : DataFrame

PowerShell on Windows 7: Set-ExecutionPolicy for regular users

This should solve your problem, you should try to run the following below:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser 

Algorithm to randomly generate an aesthetically-pleasing color palette

I would use a color wheel and given a random position you could add the golden angle (137,5 degrees)

http://en.wikipedia.org/wiki/Golden_angle

in order to get different colours each time that do not overlap.

Adjusting the brightness for the color wheel you could get also different bright/dark color combinations.

I've found this blog post that explains really well the problem and the solution using the golden ratio.

http://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/

UPDATE: I've just found this other approach:

It's called RYB(red, yellow, blue) method and it's described in this paper:

http://threekings.tk/mirror/ryb_TR.pdf

as "Paint Inspired Color Compositing".

The algorithm generates the colors and each new color is chosen to maximize its euclidian distance to the previously selected ones.

Here you can find a a good implementation in javascript:

http://afriggeri.github.com/RYB/

UPDATE 2:

The Sciences Po Medialb have just released a tool called "I want Hue" that generate color palettes for data scientists. Using different color spaces and generating the palettes by using k-means clustering or force vectors ( repulsion graphs) The results from those methods are very good, they show the theory and an implementation in their web page.

http://tools.medialab.sciences-po.fr/iwanthue/index.php

Python - How to convert JSON File to Dataframe

Creating dataframe from dictionary object.

import pandas as pd
data = [{'name': 'vikash', 'age': 27}, {'name': 'Satyam', 'age': 14}]
df = pd.DataFrame.from_dict(data, orient='columns')

df
Out[4]:
   age  name
0   27  vikash
1   14  Satyam

If you have nested columns then you first need to normalize the data:

data = [
  {
    'name': {
      'first': 'vikash',
      'last': 'singh'
    },
    'age': 27
  },
  {
    'name': {
      'first': 'satyam',
      'last': 'singh'
    },
    'age': 14
  }
]

df = pd.DataFrame.from_dict(pd.json_normalize(data), orient='columns')

df    
Out[8]:
age name.first  name.last
0   27  vikash  singh
1   14  satyam  singh

Source:

Adding a parameter to the URL with JavaScript

var MyApp = new Class();

MyApp.extend({
    utility: {
        queryStringHelper: function (url) {
            var originalUrl = url;
            var newUrl = url;
            var finalUrl;
            var insertParam = function (key, value) {
                key = escape(key);
                value = escape(value);

                //The previous post had the substr strat from 1 in stead of 0!!!
                var kvp = newUrl.substr(0).split('&');

                var i = kvp.length;
                var x;
                while (i--) {
                    x = kvp[i].split('=');

                    if (x[0] == key) {
                        x[1] = value;
                        kvp[i] = x.join('=');
                        break;
                    }
                }

                if (i < 0) {
                    kvp[kvp.length] = [key, value].join('=');
                }

                finalUrl = kvp.join('&');

                return finalUrl;
            };

            this.insertParameterToQueryString = insertParam;

            this.insertParams = function (keyValues) {
                for (var keyValue in keyValues[0]) {
                    var key = keyValue;
                    var value = keyValues[0][keyValue];
                    newUrl = insertParam(key, value);
                }
                return newUrl;
            };

            return this;
        }
    }
});

Difference between numeric, float and decimal in SQL Server

They Differ in Data Type Precedence

Decimal and Numeric are the same functionally but there is still data type precedence, which can be crucial in some cases.

SELECT SQL_VARIANT_PROPERTY(CAST(1 AS NUMERIC) + CAST(1 AS DECIMAL),'basetype')

The resulting data type is numeric because it takes data type precedence.

Exhaustive list of data types by precedence:

Reference link

Package structure for a Java project?

You could follow maven's standard project layout. You don't have to actually use maven, but it would make the transition easier in the future (if necessary). Plus, other developers will be used to seeing that layout, since many open source projects are layed out this way,

open resource with relative path in Java

For those using eclipse + maven. Say you try to access the file images/pic.jpg in src/main/resources. Doing it this way :

ClassLoader loader = MyClass.class.getClassLoader();
File file = new File(loader.getResource("images/pic.jpg").getFile());

is perfectly correct, but may result in a null pointer exception. Seems like eclipse doesn't recognize the folders in the maven directory structure as source folders right away. By removing and the src/main/resources folder from the project's source folders list and putting it back (project>properties>java build path> source>remove/add Folder), I was able to solve this.

Subversion ignoring "--password" and "--username" options

The prompt you're getting doesn't look like Subversion asking you for a password, it looks like ssh asking for a password. So my guess is that you have checked out an svn+ssh:// checkout, not an svn:// or http:// or https:// checkout.

IIRC all the options you're trying only work for the svn/http/https checkouts. Can you run svn info to confirm what kind of repository you are using ?

If you are using ssh, you should set up key-based authentication so that your scripts will work without prompting for a password.

Mercurial stuck "waiting for lock"

I had this problem with no detectable lock files. I found the solution here: http://schooner.uwaterloo.ca/twiki/bin/view/MAG/HgLockError

Here is a transcript from Tortoise Hg Workbench console

% hg debuglocks
lock:  user None, process 7168, host HPv32 (114213199s)
wlock: free
[command returned code 1 Sat Jan 07 18:00:18 2017]
% hg debuglocks --force-lock
[command completed successfully Sat Jan 07 18:03:15 2017]
cmdserver: Process crashed
PaniniDev% hg debuglocks
% hg debuglocks
lock:  free
wlock: free
[command completed successfully Sat Jan 07 18:03:30 2017]

After this the aborted pull ran sucessfully.

The lock had been set more than 2 years ago, by a process on a machine that is no longer on the LAN. Shame on the hg developers for a) not documenting locks adequately; b) not timestamping them for automatic removal when they get stale.

When should null values of Boolean be used?

I almost never use Boolean because its semantics are vague and obscure. Basically you have 3-state logic: true, false or unknown. Sometimes it is useful to use it when e.g. you gave user a choice between two values and the user didn't answer at all and you really want to know that information (think: NULLable database column).

I see no reason to convert from boolean to Boolean as it introduces extra memory overhead, NPE possibility and less typing. Typically I use awkward BooleanUtils.isTrue() to make my life a little bit easier with Boolean.

The only reason for the existence of Boolean is the ability to have collections of Boolean type (generics do not allow boolean, as well as all other primitives).

The remote host closed the connection. The error code is 0x800704CD

I get this one all the time. It means that the user started to download a file, and then it either failed, or they cancelled it.

To reproduce the exception try do this yourself - however I'm unaware of any ways to prevent it (except for handling this specific exception only).

You need to decide what the best way forward is depending on your app.

How to catch a click event on a button?

Just declare a method,e.g:if ur button id is button1 then,

button1.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Toast.makeText(Context, "Hello", Toast.LENGTH_SHORT).show();
        }
    });

If you want to make the imageview1 visible then in that method write:

imageview1.setVisibility(ImageView.VISIBLE);

How can I merge the columns from two tables into one output?

I guess that what you want to do is an UNION of both tables.

If both tables have the same columns then you can just do

SELECT category_id, col1, col2, col3
  FROM items_a
UNION 
SELECT category_id, col1, col2, col3 
  FROM items_b

Else, you might have to do something like

SELECT category_id, col1, col2, col3
  FROM items_a 
UNION 
SELECT category_id, col_1 as col1, col_2 as col2, col_3 as col3
  FROM items_b

How to configure PHP to send e-mail?

Usually a good place to start when you run into problems is the manual. The page on configuring email explains that there's a big difference between the PHP mail command running on MSWindows and on every other operating system; it's a good idea when posting a question to provide relevant information on how that part of your system is configured and what operating system it is running on.

Your PHP is configured to talk to an SMTP server - the default for an MSWindows machine, but either you have no MTA installed or it's blocking connections. While for a commercial website running your own MTA robably comes quite high on the list of things to do, it is not a trivial exercise - you really need to know what you're doing to get one configured and running securely. It would make a lot more sense in your case to use a service configured and managed by someone else.

Since you'll be connecting to a remote MTA using a gmail address, then you should probably use Gmail's server; you will need SMTP authenticaton and probably SSL support - neither of which are supported by the mail() function in PHP. There's a simple example here using swiftmailer with gmail or here's an example using phpmailer

How can I color dots in a xy scatterplot according to column value?

Try this:

Dim xrndom As Random
    Dim x As Integer
    xrndom = New Random

    Dim yrndom As Random
    Dim y As Integer
    yrndom = New Random
    'chart creation
    Chart1.Series.Add("a")
    Chart1.Series("a").ChartType = DataVisualization.Charting.SeriesChartType.Point
    Chart1.Series("a").MarkerSize = 10
    Chart1.Series.Add("b")
    Chart1.Series("b").ChartType = DataVisualization.Charting.SeriesChartType.Point
    Chart1.Series("b").MarkerSize = 10
    Chart1.Series.Add("c")
    Chart1.Series("c").ChartType = DataVisualization.Charting.SeriesChartType.Point
    Chart1.Series("c").MarkerSize = 10
    Chart1.Series.Add("d")
    Chart1.Series("d").ChartType = DataVisualization.Charting.SeriesChartType.Point
    Chart1.Series("d").MarkerSize = 10
    'color
    Chart1.Series("a").Color = Color.Red
    Chart1.Series("b").Color = Color.Orange
    Chart1.Series("c").Color = Color.Black
    Chart1.Series("d").Color = Color.Green
    Chart1.Series("Chart 1").Color = Color.Blue

    For j = 0 To 70
        x = xrndom.Next(0, 70)
        y = xrndom.Next(0, 70)
        'Conditions
        If j < 10 Then
            Chart1.Series("a").Points.AddXY(x, y)
        ElseIf j < 30 Then
            Chart1.Series("b").Points.AddXY(x, y)
        ElseIf j < 50 Then
            Chart1.Series("c").Points.AddXY(x, y)
        ElseIf 50 < j Then
            Chart1.Series("d").Points.AddXY(x, y)
        Else
            Chart1.Series("Chart 1").Points.AddXY(x, y)
        End If
    Next

How do I remove a single file from the staging area (undo git add)?

git reset <file>

Works whether or not you have any previous commits.

How to import a module in Python with importlib.import_module

For relative imports you have to:

  • a) use relative name
  • b) provide anchor explicitly

    importlib.import_module('.c', 'a.b')
    

Of course, you could also just do absolute import instead:

importlib.import_module('a.b.c')

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

Python 3.6+:

>>> i = 240
>>> f'{i:02x}'
'f0'

Dilemma: when to use Fragments vs Activities:

My philosophy is this:

Create an activity only if it's absolutely absolutely required. With the back stack made available for committing bunch of fragment transactions, I try to create as few activities in my app as possible. Also, communicating between various fragments is much easier than sending data back and forth between activities.

Activity transitions are expensive, right? At least I believe so - since the old activity has to be destroyed/paused/stopped, pushed onto the stack, and then the new activity has to be created/started/resumed.

It's just my philosophy since fragments were introduced.

Error "package android.support.v7.app does not exist"

I just got this error today and this is how I fixed.

  • On my build output, I double click on the class with the error.
  • After the class opened, I expanded the imports section and deleted existing imports with errors.
  • I then hovered my mouse near the errors which were:RecyclerView,LinearLayoutManager, and FragmentTransaction and chose Alt+Enter to import appropriate classes.

Note: in my case, the error occured after I migrated one of my old projects to androidx and so imports hard to be androidx related. I am using android studio.

Note: You may run into other issues, so everytime I run into an error, I check other called classes and makes sure their imports are correct. What I do mostly is press ctrl+shift+R, and put the old import in the first field and the correct import on the second field and then replace all. This way, I replace all imports that in the project at once.

You can use ctrl+shift+f to find where imports are used.

What does the line "#!/bin/sh" mean in a UNIX shell script?

The first line tells the shell that if you execute the script directly (./run.sh; as opposed to /bin/sh run.sh), it should use that program (/bin/sh in this case) to interpret it.

You can also use it to pass arguments, commonly -e (exit on error), or use other programs (/bin/awk, /usr/bin/perl, etc).

HTML Input - already filled in text

You seem to look for the input attribute value, "the initial value of the control"?

<input type="text" value="Morlodenhof 7" />

https://developer.mozilla.org/de/docs/Web/HTML/Element/Input#attr-value

How Do I Make Glyphicons Bigger? (Change Size?)

Yes, and basically you can also use inline style:

<span style="font-size: 15px" class="glyphicon glyphicon-cog"></span>

Number of processors/cores in command line

The most simplest tool comes with glibc and is called getconf:

$ getconf _NPROCESSORS_ONLN
4

How do you sort a dictionary by value?

Actually in C#, dictionaries don't have sort() methods. As you are more interested in sort by values, you can't get values until you provide them key. In short, you need to iterate through them using LINQ's OrderBy(),

var items = new Dictionary<string, int>();
items.Add("cat", 0);
items.Add("dog", 20);
items.Add("bear", 100);
items.Add("lion", 50);

// Call OrderBy() method here on each item and provide them the IDs.
foreach (var item in items.OrderBy(k => k.Key))
{
    Console.WriteLine(item);// items are in sorted order
}

You can do one trick:

var sortedDictByOrder = items.OrderBy(v => v.Value);

or:

var sortedKeys = from pair in dictName
            orderby pair.Value ascending
            select pair;

It also depends on what kind of values you are storing: single (like string, int) or multiple (like List, Array, user defined class). If it's single you can make list of it and then apply sort.
If it's user defined class, then that class must implement IComparable, ClassName: IComparable<ClassName> and override compareTo(ClassName c) as they are more faster and more object oriented than LINQ.

Convert seconds value to hours minutes seconds?

I know this is pretty old but in java 8:

LocalTime.MIN.plusSeconds(120).format(DateTimeFormatter.ISO_LOCAL_TIME)

Does Django scale?

Today we use many web apps and sites for our needs. Most of them are highly useful. I will show you some of them used by python or django.

Washington Post

The Washington Post’s website is a hugely popular online news source to accompany their daily paper. Its’ huge amount of views and traffic can be easily handled by the Django web framework. Washington Post - 52.2 million unique visitors (March, 2015)

NASA

The National Aeronautics and Space Administration’s official website is the place to find news, pictures, and videos about their ongoing space exploration. This Django website can easily handle huge amounts of views and traffic. 2 million visitors monthly

The Guardian

The Guardian is a British news and media website owned by the Guardian Media Group. It contains nearly all of the content of the newspapers The Guardian and The Observer. This huge data is handled by Django. The Guardian (commenting system) - 41,6 million unique visitors (October, 2014)

YouTube

We all know YouTube as the place to upload cat videos and fails. As one of the most popular websites in existence, it provides us with endless hours of video entertainment. The Python programming language powers it and the features we love.

DropBox

DropBox started the online document storing revolution that has become part of daily life. We now store almost everything in the cloud. Dropbox allows us to store, sync, and share almost anything using the power of Python.

Survey Monkey

Survey Monkey is the largest online survey company. They can handle over one million responses every day on their rewritten Python website.

Quora

Quora is the number one place online to ask a question and receive answers from a community of individuals. On their Python website relevant results are answered, edited, and organized by these community members.

Bitly

A majority of the code for Bitly URL shortening services and analytics are all built with Python. Their service can handle hundreds of millions of events per day.

Reddit

Reddit is known as the front page of the internet. It is the place online to find information or entertainment based on thousands of different categories. Posts and links are user generated and are promoted to the top through votes. Many of Reddit’s capabilities rely on Python for their functionality.

Hipmunk

Hipmunk is an online consumer travel site that compares the top travel sites to find you the best deals. This Python website’s tools allow you to find the cheapest hotels and flights for your destination.

Click here for more: 25-of-the-most-popular-python-and-django-websites, What-are-some-well-known-sites-running-on-Django

Writing binary number system in C code

Prefix you literal with 0b like in

int i = 0b11111111;

See here.

BigDecimal setScale and round

One important point that is alluded to but not directly addressed is the difference between "precision" and "scale" and how they are used in the two statements. "precision" is the total number of significant digits in a number. "scale" is the number of digits to the right of the decimal point.

The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.

setScale() obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.

If you move the decimal point one place to the right, the difference will become clear:

// 1.
new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
//result = 35.35
// 2.
new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
// result = 35.3456

Multiple Errors Installing Visual Studio 2015 Community Edition

This is a very elusive problem. No (simple) solution looks to apply. I tried -all- the previous options with the same negative result: multiple packages errors.
Resorted to install VS 2013, success no issues, then VS 15 (Preview) success no issues (btw very cool).
Finally what works for me, was to install the very basic first 'Visual Studio 2015' with -NO- updates. During the installation, setup automatically downloaded 'Update 2' and the installation finished successfully.

Android - Adding at least one Activity with an ACTION-VIEW intent-filter after Updating SDK version 23

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.app"
tools:ignore="GoogleAppIndexingWarning">

You can remove the warning by adding xmlns:tools="http://schemas.android.com/tools" and tools:ignore="GoogleAppIndexingWarning" to the <manifest> tag.

HTML code for an apostrophe

&#39; in decimal.

%27 in hex.

Choice between vector::resize() and vector::reserve()

From your description, it looks like that you want to "reserve" the allocated storage space of vector t_Names.

Take note that resize initialize the newly allocated vector where reserve just allocates but does not construct. Hence, 'reserve' is much faster than 'resize'

You can refer to the documentation regarding the difference of resize and reserve

Git ignore file for Xcode projects

Based on this guide for Mercurial my .gitignore includes:

.DS_Store
*.swp
*~.nib

build/

*.pbxuser
*.perspective
*.perspectivev3

I've also chosen to include:

*.mode1v3
*.mode2v3

which, according to this Apple mailing list post, are "user-specific project settings".

And for Xcode 4:

xcuserdata

MySQL dump by query

You can dump a query as csv like this:

SELECT * from myTable
INTO OUTFILE '/tmp/querydump.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'

segmentation fault : 11

What system are you running on? Do you have access to some sort of debugger (gdb, visual studio's debugger, etc.)?

That would give us valuable information, like the line of code where the program crashes... Also, the amount of memory may be prohibitive.

Additionally, may I recommend that you replace the numeric limits by named definitions?

As such:

#define DIM1_SZ 1000
#define DIM2_SZ 1000000

Use those whenever you wish to refer to the array dimension limits. It will help avoid typing errors.

Error in eval(expr, envir, enclos) : object not found

This can happen if you don't attach your dataset.

Determine the path of the executing BASH script

Assuming you type in the full path to the bash script, use $0 and dirname, e.g.:

#!/bin/bash
echo "$0"
dirname "$0"

Example output:

$ /a/b/c/myScript.bash
/a/b/c/myScript.bash
/a/b/c

If necessary, append the results of the $PWD variable to a relative path.

EDIT: Added quotation marks to handle space characters.

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

I encountered a similar problem when I was trying to connect my Django application to PostgreSQL database.

I wrote my Dockerfile with instructions to setup the Django project followed by instructions to install PostgreSQL and run Django server in my docker-compose.yml.

I defined two services in my docker-compose-yml.

services:
  postgres:
    image: "postgres:latest"
    environment:
      - POSTGRES_DB=abc
      - POSTGRES_USER=abc
      - POSTGRES_PASSWORD=abc
    volumes:
      - pg_data:/var/lib/postgresql/data/
  django:
    build: .
    command: python /code/manage.py runserver 0.0.0.0:8004
    volumes:
      - .:/app
    ports:
      - 8004:8004
    depends_on:
      - postgres 

Unfortunately whenever I used to run docker-compose up then same err. used to pop up.

And this is how my database was defined in Django settings.py.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'abc',
        'USER': 'abc',
        'PASSWORD': 'abc',
        'HOST': '127.0.0.1',
        'PORT': '5432',
        'OPTIONS': {
            'client_encoding': 'UTF8',
        },
    }
} 

So, In the end I made use of docker-compose networking which means if I change the host of my database to postgres which is defined as a service in docker-compose.yml will do the wonders.

So, Replacing 'HOST': '127.0.0.1' => 'HOST': 'postgres' did wonders for me.

After replacement this is how your Database config in settings.py will look like.

DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'NAME': 'abc',
            'USER': 'abc',
            'PASSWORD': 'abc',
            'HOST': 'postgres',
            'PORT': '5432',
            'OPTIONS': {
                'client_encoding': 'UTF8',
            },
        }
    } 

Get started with Latex on Linux

First you'll need to Install it:

  • If you're using a distro which packages LaTeX (almost all will do) then look for texlive or tetex. TeX Live is the newer of the two, and is replacing tetex on most distributions now.

If you're using Debian or Ubuntu, something like:

<code>apt-get install texlive</code>

..will get it installed.

RedHat or CentOS need:

<code>yum install tetex</code>

Note : This needs root permissions, so either use su to switch user to root, or prefix the commands with sudo, if you aren't already logged in as the root user.

Next you'll need to get a text editor. Any editor will do, so whatever you are comfortable with. You'll find that advanced editors like Emacs (and vim) add a lot of functionality and so will help with ensuring that your syntax is correct before you try and build your document output.

Create a file called test.tex and put some content in it, say the example from the LaTeX primer:

\documentclass[a4paper,12pt]{article}
\begin{document}

The foundations of the rigorous study of \emph{analysis}
were laid in the nineteenth century, notably by the
mathematicians Cauchy and Weierstrass. Central to the
study of this subject are the formal definitions of
\emph{limits} and \emph{continuity}.

Let $D$ be a subset of $\bf R$ and let
$f \colon D \to \mathbf{R}$ be a real-valued function on
$D$. The function $f$ is said to be \emph{continuous} on
$D$ if, for all $\epsilon > 0$ and for all $x \in D$,
there exists some $\delta > 0$ (which may depend on $x$)
such that if $y \in D$ satisfies
\[ |y - x| < \delta \]
then
\[ |f(y) - f(x)| < \epsilon. \]

One may readily verify that if $f$ and $g$ are continuous
functions on $D$ then the functions $f+g$, $f-g$ and
$f.g$ are continuous. If in addition $g$ is everywhere
non-zero then $f/g$ is continuous.

\end{document}

Once you've got this file you'll need to run latex on it to produce some output (as a .dvi file to start with, which is possible to convert to many other formats):

latex test.tex

This will print a bunch of output, something like this:

=> latex test.tex

This is pdfeTeX, Version 3.141592-1.21a-2.2 (Web2C 7.5.4)
entering extended mode
(./test.tex
LaTeX2e &lt;2003/12/01&gt;
Babel &lt;v3.8d&gt; and hyphenation patterns for american, french, german, ngerman, b
ahasa, basque, bulgarian, catalan, croatian, czech, danish, dutch, esperanto, e
stonian, finnish, greek, icelandic, irish, italian, latin, magyar, norsk, polis
h, portuges, romanian, russian, serbian, slovak, slovene, spanish, swedish, tur
kish, ukrainian, nohyphenation, loaded.
(/usr/share/texmf/tex/latex/base/article.cls
Document Class: article 2004/02/16 v1.4f Standard LaTeX document class
(/usr/share/texmf/tex/latex/base/size12.clo))
No file test.aux.
[1] (./test.aux) )
Output written on test.dvi (1 page, 1508 bytes).
Transcript written on test.log.

..don't worry about most of this output -- the important part is the Output written on test.dvi line, which says that it was successful.

Now you need to view the output file with xdvi:

xdvi test.dvi &

This will pop up a window with the beautifully formatted output in it. Hit `q' to quit this, or you can leave it open and it will automatically update when the test.dvi file is modified (so whenever you run latex to update the output).

To produce a PDF of this you simply run pdflatex instead of latex:

pdflatex test.tex

..and you'll have a test.pdf file created instead of the test.dvi file.

After this is all working fine, I would suggest going to the LaTeX primer page and running through the items on there as you need features for documents you want to write.

Future things to consider include:

  • Use tools such as xfig or dia to create diagrams. These can be easily inserted into your documents in a variety of formats. Note that if you are creating PDFs then you shouldn't use EPS (encapsulated postscript) for images -- use pdf exported from your diagram editor if possible, or you can use the epstopdf package to automatically convert from (e)ps to pdf for figures included with \includegraphics.

  • Start using version control on your documents. This seems excessive at first, but being able to go back and look at earlier versions when you are writing something large can be extremely useful.

  • Use make to run latex for you. When you start on having bibliographies, images and other more complex uses of latex you'll find that you need to run it over multiple files or multiple times (the first time updates the references, and the second puts references into the document, so they can be out-of-date unless you run latex twice...). Abstracting this into a makefile can save a lot of time and effort.

  • Use a better editor. Something like Emacs + AUCTeX is highly competent. This is of course a highly subjective subject, so I'll leave it at that (that and that Emacs is clearly the best option :)

How do I increase the cell width of the Jupyter/ipython notebook in my browser?

If you don't want to change your default settings, and you only want to change the width of the current notebook you're working on, you can enter the following into a cell:

from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))

How do I extract a substring from a string until the second space is encountered?

string testString = "o1 1232.5467 1232.5467.........";

string secondItem = testString.Split(new char[]{' '}, 3)[1];

CSS align one item right with flexbox

For a terse, pure flexbox option, group the left-aligned items and the right-aligned items:

<div class="wrap">
  <div>
    <span>One</span>
    <span>Two</span>
  </div>
  <div>Three</div>
</div>

and use space-between:

.wrap {
  display: flex;
  background: #ccc;
  justify-content: space-between;
}

This way you can group multiple items to the right(or just one).

https://jsfiddle.net/c9mkewwv/3/

How to stick text to the bottom of the page?

An old thread, but...Answer of Konerak works, but why would you even set size of a container by default. What I prefer is to use code wherever no matter of hog big page size is. So this my code:

<style>
   #container {
    position: relative;
    height: 100%;
 }
 #footer {
    position: absolute;
    bottom: 0;
 }
</style>

</HEAD>

<BODY>

 <div id="container">

    <h1>Some heading</h1>

<p>Some text you have</p> 

<br>
<br>

<div id="footer"><p>Rights reserved</p></div>

</div>

</BODY>
</HTML>

The trick is in <br> where you break new line. So, when page is small you'll see footer at bottom of page, as you want.

BUT, when a page is big SO THAT YOU MUST SCROLL IT DOWN, then your footer is going to be 2 new lines under the whole content above. And If you will then make page bigger, your footer is allways going to go DOWN. I hope somebody will find this useful.

LINQ select one field from list of DTO objects to array

You can select all Sku elements of your myLines list and then convert the result to an array.

string[] mySKUsArray = myLines.Select(x=>x.Sku).ToArray();

What is JSON and why would I use it?

JSON is JavaScript Object Notation. It is a much-more compact way of transmitting sets of data across network connections as compared to XML. I suggest JSON be used in any AJAX-like applications where XML would otherwise be the "recommended" option. The verbosity of XML will add to download time and increased bandwidth consumption ($$$). You can accomplish the same effect with JSON and its mark-up is almost exclusively dedicated to the data itself and not the underlying structure.

Check if string contains only whitespace

You want to use the isspace() method

str.isspace()

Return true if there are only whitespace characters in the string and there is at least one character, false otherwise.

That's defined on every string object. Here it is an usage example for your specific use case:

if aStr and (not aStr.isspace()):
    print aStr

How to get an absolute file path in Python

import os
os.path.abspath(os.path.expanduser(os.path.expandvars(PathNameString)))

Note that expanduser is necessary (on Unix) in case the given expression for the file (or directory) name and location may contain a leading ~/(the tilde refers to the user's home directory), and expandvars takes care of any other environment variables (like $HOME).

Spring @Transactional - isolation, propagation

Enough explanation about each parameter is given by other answers; However you asked for a real world example, here is the one that clarifies the purpose of different propagation options:

Suppose you're in charge of implementing a signup service in which a confirmation e-mail is sent to the user. You come up with two service objects, one for enrolling the user and one for sending e-mails, which the latter is called inside the first one. For example something like this:

/* Sign Up service */
@Service
@Transactional(Propagation=REQUIRED)
class SignUpService{
 ...
 void SignUp(User user){
    ...
    emailService.sendMail(User);
 }
}

/* E-Mail Service */
@Service
@Transactional(Propagation=REQUIRES_NEW)
class EmailService{
 ...
 void sendMail(User user){
  try{
     ... // Trying to send the e-mail
  }catch( Exception)
 }
}

You may have noticed that the second service is of propagation type REQUIRES_NEW and moreover chances are it throws an exception (SMTP server down ,invalid e-mail or other reasons).You probably don't want the whole process to roll-back, like removing the user information from database or other things; therefore you call the second service in a separate transaction.

Back to our example, this time you are concerned about the database security, so you define your DAO classes this way:

/* User DAO */
@Transactional(Propagation=MANDATORY)
class UserDAO{
 // some CRUD methods
}

Meaning that whenever a DAO object, and hence a potential access to db, is created, we need to reassure that the call was made from inside one of our services, implying that a live transaction should exist; otherwise an exception occurs.Therefore the propagation is of type MANDATORY.

Setting the default ssh key location

If you are only looking to point to a different location for you identity file, the you can modify your ~/.ssh/config file with the following entry:

IdentityFile ~/.foo/identity

man ssh_config to find other config options.

android - listview get item view by position

This is the Kotlin version of the function posted by VVB. I used it in the ListView Adapter to implement the "go to next row first EditText when Enter key is pressed on the last EditText of current row" feature in the getView().

In the ListViewAdapter class, fun getView(), add lastEditText.setOnKeyListner as below:

lastEditText.setOnKeyListener { v, keyCode, event ->
    var setOnKeyListener = false
    if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_UP) {
        try {
            val nextRow = getViewByPosition(position + 1, parent as ListView) as LinearLayout
            val nextET = nextRow.findViewById(R.id.firstEditText) as EditText
            nextET.isFocusableInTouchMode = true
            nextET.requestFocus()
        } catch (e: Exception) {
            // do nothing
        }
        setOnKeyListener = true
    }
    setOnKeyListener
}

add the fun getViewByPosition() after fun getView() as below:

private fun getViewByPosition(pos: Int, listView: ListView): View? {
    val firstListItemPosition: Int = listView.firstVisiblePosition
    val lastListItemPosition: Int = firstListItemPosition + listView.childCount - 1
    return if (pos < firstListItemPosition || pos > lastListItemPosition) {
        listView.adapter.getView(pos, null, listView)
    } else {
        val childIndex = pos + listView.headerViewsCount - firstListItemPosition
        listView.getChildAt(childIndex)
    }
}

How do I test a private function or a class that has private methods, fields or inner classes?

A private method is only to be accessed within the same class. So there is no way to test a “private” method of a target class from any test class. A way out is that you can perform unit testing manually or can change your method from “private” to “protected”.

And then a protected method can only be accessed within the same package where the class is defined. So, testing a protected method of a target class means we need to define your test class in the same package as the target class.

If all the above does not suits your requirement, use the reflection way to access the private method.

How to insert an item at the beginning of an array in PHP?

Use array_unshift() to insert the first element in an array.

User array_shift() to removes the first element of an array.

Running java with JAVA_OPTS env variable has no effect

You can setup _JAVA_OPTIONS instead of JAVA_OPTS. This should work without $_JAVA_OPTIONS.

Multiple INNER JOIN SQL ACCESS

Thanks HansUp for your answer, it is very helpful and it works!

I found three patterns working in Access, yours is the best, because it works in all cases.

  • INNER JOIN, your variant. I will call it "closed set pattern". It is possible to join more than two tables to the same table with good performance only with this pattern.

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM
         ((class
           INNER JOIN person AS cr 
           ON class.C_P_ClassRep=cr.P_Nr
         )
         INNER JOIN person AS cr2
         ON class.C_P_ClassRep2nd=cr2.P_Nr
      )
    

    ;

  • INNER JOIN "chained-set pattern"

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM person AS cr
    INNER JOIN ( class 
       INNER JOIN ( person AS cr2
       ) ON class.C_P_ClassRep2nd=cr2.P_Nr
    ) ON class.C_P_ClassRep=cr.P_Nr
    ;
    
  • CROSS JOIN with WHERE

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM class, person AS cr, person AS cr2
    WHERE class.C_P_ClassRep=cr.P_Nr AND class.C_P_ClassRep2nd=cr2.P_Nr
    ;
    

Getting the docstring from a function

You can also use inspect.getdoc. It cleans up the __doc__ by normalizing tabs to spaces and left shifting the doc body to remove common leading spaces.

Display List in a View MVC

Your action method considers model type asList<string>. But, in your view you are waiting for IEnumerable<Standings.Models.Teams>. You can solve this problem with changing the model in your view to List<string>.

But, the best approach would be to return IEnumerable<Standings.Models.Teams> as a model from your action method. Then you haven't to change model type in your view.

But, in my opinion your models are not correctly implemented. I suggest you to change it as:

public class Team
{
    public int Position { get; set; }
    public string HomeGround {get; set;}
    public string NickName {get; set;}
    public int Founded { get; set; }
    public string Name { get; set; }
}

Then you must change your action method as:

public ActionResult Index()
{
    var model = new List<Team>();

    model.Add(new Team { Name = "MU"});
    model.Add(new Team { Name = "Chelsea"});
    ...

    return View(model);
}

And, your view:

@model IEnumerable<Standings.Models.Team>

@{
     ViewBag.Title = "Standings";
}

@foreach (var item in Model)
{
    <div>
        @item.Name
        <hr />
    </div>
}

How to use a PHP class from another file?

In this case, it appears that you've already included the file somewhere. But for class files, you should really "include" them using require_once to avoid that sort of thing; it won't include the file if it already has been. (And you should usually use require[_once], not include[_once], the difference being that require will cause a fatal error if the file doesn't exist, instead of just issuing a warning.)

JavaScript hashmap equivalent

Problem description

JavaScript has no built-in general map type (sometimes called associative array or dictionary) which allows to access arbitrary values by arbitrary keys. JavaScript's fundamental data structure is the object, a special type of map which only accepts strings as keys and has special semantics like prototypical inheritance, getters and setters and some further voodoo.

When using objects as maps, you have to remember that the key will be converted to a string value via toString(), which results in mapping 5 and '5' to the same value and all objects which don't overwrite the toString() method to the value indexed by '[object Object]'. You might also involuntarily access its inherited properties if you don't check hasOwnProperty().

JavaScript's built-in array type does not help one bit: JavaScript arrays are not associative arrays, but just objects with a few more special properties. If you want to know why they can't be used as maps, look here.

Eugene's Solution

Eugene Lazutkin already described the basic idea of using a custom hash function to generate unique strings which can be used to look up the associated values as properties of a dictionary object. This will most likely be the fastest solution, because objects are internally implemented as hash tables.

  • Note: Hash tables (sometimes called hash maps) are a particular implementation of the map concept using a backing array and lookup via numeric hash values. The runtime environment might use other structures (such as search trees or skip lists) to implement JavaScript objects, but as objects are the fundamental data structure, they should be sufficiently optimised.

In order to get a unique hash value for arbitrary objects, one possibility is to use a global counter and cache the hash value in the object itself (for example, in a property named __hash).

A hash function which does this is and works for both primitive values and objects is:

function hash(value) {
    return (typeof value) + ' ' + (value instanceof Object ?
        (value.__hash || (value.__hash = ++arguments.callee.current)) :
        value.toString());
}

hash.current = 0;

This function can be used as described by Eugene. For convenience, we will further wrap it in a Map class.

My Map implementation

The following implementation will additionally store the key-value-pairs in a doubly linked list in order to allow fast iteration over both keys and values. To supply your own hash function, you can overwrite the instance's hash() method after creation.

// Linking the key-value-pairs is optional.
// If no argument is provided, linkItems === undefined, i.e. !== false
// --> linking will be enabled
function Map(linkItems) {
    this.current = undefined;
    this.size = 0;

    if(linkItems === false)
        this.disableLinking();
}

Map.noop = function() {
    return this;
};

Map.illegal = function() {
    throw new Error("illegal operation for maps without linking");
};

// Map initialisation from an existing object
// doesn't add inherited properties if not explicitly instructed to:
// omitting foreignKeys means foreignKeys === undefined, i.e. == false
// --> inherited properties won't be added
Map.from = function(obj, foreignKeys) {
    var map = new Map;

    for(var prop in obj) {
        if(foreignKeys || obj.hasOwnProperty(prop))
            map.put(prop, obj[prop]);
    }

    return map;
};

Map.prototype.disableLinking = function() {
    this.link = Map.noop;
    this.unlink = Map.noop;
    this.disableLinking = Map.noop;
    this.next = Map.illegal;
    this.key = Map.illegal;
    this.value = Map.illegal;
    this.removeAll = Map.illegal;

    return this;
};

// Overwrite in Map instance if necessary
Map.prototype.hash = function(value) {
    return (typeof value) + ' ' + (value instanceof Object ?
        (value.__hash || (value.__hash = ++arguments.callee.current)) :
        value.toString());
};

Map.prototype.hash.current = 0;

// --- Mapping functions

Map.prototype.get = function(key) {
    var item = this[this.hash(key)];
    return item === undefined ? undefined : item.value;
};

Map.prototype.put = function(key, value) {
    var hash = this.hash(key);

    if(this[hash] === undefined) {
        var item = { key : key, value : value };
        this[hash] = item;

        this.link(item);
        ++this.size;
    }
    else this[hash].value = value;

    return this;
};

Map.prototype.remove = function(key) {
    var hash = this.hash(key);
    var item = this[hash];

    if(item !== undefined) {
        --this.size;
        this.unlink(item);

        delete this[hash];
    }

    return this;
};

// Only works if linked
Map.prototype.removeAll = function() {
    while(this.size)
        this.remove(this.key());

    return this;
};

// --- Linked list helper functions

Map.prototype.link = function(item) {
    if(this.size == 0) {
        item.prev = item;
        item.next = item;
        this.current = item;
    }
    else {
        item.prev = this.current.prev;
        item.prev.next = item;
        item.next = this.current;
        this.current.prev = item;
    }
};

Map.prototype.unlink = function(item) {
    if(this.size == 0)
        this.current = undefined;
    else {
        item.prev.next = item.next;
        item.next.prev = item.prev;
        if(item === this.current)
            this.current = item.next;
    }
};

// --- Iterator functions - only work if map is linked

Map.prototype.next = function() {
    this.current = this.current.next;
};

Map.prototype.key = function() {
    return this.current.key;
};

Map.prototype.value = function() {
    return this.current.value;
};

Example

The following script,

var map = new Map;

map.put('spam', 'eggs').
    put('foo', 'bar').
    put('foo', 'baz').
    put({}, 'an object').
    put({}, 'another object').
    put(5, 'five').
    put(5, 'five again').
    put('5', 'another five');

for(var i = 0; i++ < map.size; map.next())
    document.writeln(map.hash(map.key()) + ' : ' + map.value());

generates this output:

string spam : eggs
string foo : baz
object 1 : an object
object 2 : another object
number 5 : five again
string 5 : another five

Further considerations

PEZ suggested to overwrite the toString() method, presumably with our hash function. This is not feasible, because it doesn't work for primitive values (changing toString() for primitives is a very bad idea). If we want toString() to return meaningful values for arbitrary objects, we would have to modify Object.prototype, which some people (myself not included) consider verboten.


The current version of my Map implementation as well as other JavaScript goodies can be obtained from here.

Zabbix server is not running: the information displayed may not be current

just get into the zabbix.conf.php

   >$sudo vim /etc/zabbix/web/zabbix.conf.php
   >$ZBX_SERVER      = '**your zabbix ip address or DNS name**';
   >$ZBX_SERVER_PORT = '10051';
   >$ZBX_SERVER_NAME = '**your zabbix hostname**';

just change the ip address you can resolve the error

Zabbix server is not running: the information displayed may not be current

After that restart the zabbix server

 >$sudo service zabbix-server restart

To verify go to Dashboard Administration -> queue there you see data

i resolved my error like this works fine for me.

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

Read file from line 2 or skip header row

with open(fname) as f:
    next(f)
    for line in f:
        #do something

Including another class in SCSS

Using @extend is a fine solution, but be aware that the compiled css will break up the class definition. Any classes that extends the same placeholder will be grouped together and the rules that aren't extended in the class will be in a separate definition. If several classes become extended, it can become unruly to look up a selector in the compiled css or the dev tools. Whereas a mixin will duplicate the mixin code and add any additional styles.

You can see the difference between @extend and @mixin in this sassmeister

How to set default font family in React Native?

The recommended way is to create your own component, such as MyAppText. MyAppText would be a simple component that renders a Text component using your universal style and can pass through other props, etc.

https://facebook.github.io/react-native/docs/text.html#limited-style-inheritance

C# - How to convert string to char?

A string can be converted to an array of characters by calling the ToCharArray string's method.

var characters = stringValue.ToCharArray();

An object of type string[] is not a string, but an array of strings. You cannot convert an array of strings to an array of characters by just calling a method like ToCharArray. To be more correct there isn't any method in the .NET framework that does this thing. You could however declare an extension method to do this, but this is another discussion.

If your intention is to build an array of the characters that make up the strings you have in your array, you could do so by calling the ToCharArray method on each string of your array.

Fastest JSON reader/writer for C++

http://lloyd.github.com/yajl/

http://www.digip.org/jansson/

Don't really know how they compare for speed, but the first one looks like the right idea for scaling to really big JSON data, since it parses only a small chunk at a time so they don't need to hold all the data in memory at once (This can be faster or slower depending on the library/use case)

jQuery find parent form

see also jquery/js -- How do I select the parent form based on which submit button is clicked?

$('form#myform1').submit(function(e){
     e.preventDefault(); //Prevent the normal submission action
     var form = this;
     // ... Handle form submission
});

How to add a filter class in Spring Boot?

If you use Spring Boot + Spring Security, you can do that in the security configuration.

In the below example, I'm adding a custom filter before the UsernamePasswordAuthenticationFilter (see all the default Spring Security filters and their order).

@EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired FilterDependency filterDependency;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .addFilterBefore(
                new MyFilter(filterDependency),
                UsernamePasswordAuthenticationFilter.class);
    }
}

And the filter class

class MyFilter extends OncePerRequestFilter  {
    private final FilterDependency filterDependency;

    public MyFilter(FilterDependency filterDependency) {
        this.filterDependency = filterDependency;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
        HttpServletResponse response,
        FilterChain filterChain)
        throws ServletException, IOException {
       // filter
       filterChain.doFilter(request, response);
    }
}

JavaScript push to array

Use the push() function to append to an array:

// initialize array
var arr = [
    "Hi",
    "Hello",
    "Bonjour"
];

// append new value to the array
arr.push("Hola");

Now array is

var arr = [
    "Hi",
    "Hello",
    "Bonjour"
    "Hola"
];

// append multiple values to the array
arr.push("Salut", "Hey");

Now array is

var arr = [
    "Hi",
    "Hello",
    "Bonjour"
    "Hola"
    "Salut"
    "Hey"
];

// display all values
for (var i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}

Will print:

Hi
Hello
Bonjour
Hola 
Salut
Hey

Update

If you want to add the items of one array to another array, you can use Array.concat:

var arr = [
    "apple",
    "banana",
    "cherry"
];

arr = arr.concat([
    "dragonfruit",
    "elderberry",
    "fig"
]);

console.log(arr);

Will print

["apple", "banana", "cherry", "dragonfruit", "elderberry", "fig"]

How to deal with floating point number precision in JavaScript?

var times = function (a, b) {
    return Math.round((a * b) * 100)/100;
};

---or---

var fpFix = function (n) {
    return Math.round(n * 100)/100;
};

fpFix(0.1*0.2); // -> 0.02

---also---

var fpArithmetic = function (op, x, y) {
    var n = {
            '*': x * y,
            '-': x - y,
            '+': x + y,
            '/': x / y
        }[op];        

    return Math.round(n * 100)/100;
};

--- as in ---

fpArithmetic('*', 0.1, 0.2);
// 0.02

fpArithmetic('+', 0.1, 0.2);
// 0.3

fpArithmetic('-', 0.1, 0.2);
// -0.1

fpArithmetic('/', 0.2, 0.1);
// 2

can't access mysql from command line mac

I've tried all the solutions from the answers but couldn't get mysql command to work from the terminal, always getting the message

bash: command not found

The solution is to change the .bash_profile, and add the mysql path to .bash_profile

To do so follow these steps: 1. Open a new Terminal window or make sure you are in the home directory 2. Open .bash_profile using

nano .bash_profile

3. Add the following command to add the mysql path

PATH="/usr/local/mysql/bin:${PATH}"
export PATH

4. Press Ctrl+X, then press y and press enter.

The following is how my .bash_profile looks like enter image description here

Find the IP address of the client in an SSH session

 who | cut -d"(" -f2 |cut -d")" -f1

Iteration over std::vector: unsigned vs signed index variable

To be complete, C++11 syntax enables just one another version for iterators (ref):

for(auto it=std::begin(polygon); it!=std::end(polygon); ++it) {
  // do something with *it
}

Which is also comfortable for reverse iteration

for(auto it=std::end(polygon)-1; it!=std::begin(polygon)-1; --it) {
  // do something with *it
}

Query for array elements inside JSON type

Create a table with column as type json

CREATE TABLE friends ( id serial primary key, data jsonb);

Now let's insert json data

INSERT INTO friends(data) VALUES ('{"name": "Arya", "work": ["Improvements", "Office"], "available": true}');
INSERT INTO friends(data) VALUES ('{"name": "Tim Cook", "work": ["Cook", "ceo", "Play"], "uses": ["baseball", "laptop"], "available": false}');

Now let's make some queries to fetch data

select data->'name' from friends;
select data->'name' as name, data->'work' as work from friends;

You might have noticed that the results comes with inverted comma( " ) and brackets ([ ])

    name    |            work            
------------+----------------------------
 "Arya"     | ["Improvements", "Office"]
 "Tim Cook" | ["Cook", "ceo", "Play"]
(2 rows)

Now to retrieve only the values just use ->>

select data->>'name' as name, data->'work'->>0 as work from friends;
select data->>'name' as name, data->'work'->>0 as work from friends where data->>'name'='Arya';

How to write and read java serialized objects into a file

if you serialize the whole list you also have to de-serialize the file into a list when you read it back. This means that you will inevitably load in memory a big file. It can be expensive. If you have a big file, and need to chunk it line by line (-> object by object) just proceed with your initial idea.

Serialization:

LinkedList<YourObject> listOfObjects = <something>;
try {
    FileOutputStream file = new FileOutputStream(<filePath>);
    ObjectOutputStream writer = new ObjectOutputStream(file);
    for (YourObject obj : listOfObjects) {
        writer.writeObject(obj);
    }
    writer.close();
    file.close();
} catch (Exception ex) {
    System.err.println("failed to write " + filePath + ", "+ ex);
}

De-serialization:

try {
    FileInputStream file = new FileInputStream(<filePath>);
    ObjectInputStream reader = new ObjectInputStream(file);
    while (true) {
        try { 
            YourObject obj = (YourObject)reader.readObject();
            System.out.println(obj)
        } catch (Exception ex) {
            System.err.println("end of reader file ");
            break;
        }
    }
} catch (Exception ex) {
    System.err.println("failed to read " + filePath + ", "+ ex);
}

Warning: mysql_connect(): Access denied for user 'root'@'localhost' (using password: YES)

try $conn = mysql_connect("localhost", "root") or $conn = mysql_connect("localhost", "root", "")

Cross-reference (named anchor) in markdown

Use a name. Using an id isn't necessary in HTML 5 and will create global variables in your JavaScript

See the HTML 5 specification, 5.9.8 Navigating to a fragment identifier - both id and name are used.

It's important to know that most browsers still turn IDs into global variables. Here's a quick test. Using a name avoids creating globals and any conflicts that may result.

Example using a name:

Take me to [pookie](#pookie)

And the destination anchor:

### <a name="pookie"></a>Some heading

How do I add BundleConfig.cs to my project?

BundleConfig is nothing more than bundle configuration moved to separate file. It used to be part of app startup code (filters, bundles, routes used to be configured in one class)

To add this file, first you need to add the Microsoft.AspNet.Web.Optimization nuget package to your web project:

Install-Package Microsoft.AspNet.Web.Optimization

Then under the App_Start folder create a new cs file called BundleConfig.cs. Here is what I have in my mine (ASP.NET MVC 5, but it should work with MVC 4):

using System.Web;
using System.Web.Optimization;

namespace CodeRepository.Web
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));
        }
    }
}

Then modify your Global.asax and add a call to RegisterBundles() in Application_Start():

using System.Web.Optimization;

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

A closely related question: How to add reference to System.Web.Optimization for MVC-3-converted-to-4 app

Hex colors: Numeric representation for "transparent"?

Very simple: no color, no opacity:

rgba(0, 0, 0, 0);