Programs & Examples On #Midp 2.0

MIDP 2.0 is a revised version of the MIDP 1.0 specification. Includes new features such as an enhanced user interface, multimedia and game functionality, greater connectivity, over-the-air (OTA) provisioning, and end-to-end security. MIDP 2.0 is backward compatible with MIDP 1.0, and continues to target mobile information devices such as mobile phones and PDAs.

How can I remove jenkins completely from linux

if you are ubuntu user than try this:

sudo apt-get remove jenkins
sudo apt-get remove --auto-remove jenkins

'apt-get remove' command is use to remove package.

XPath: Get parent node from child node

New, improved answer to an old, frequently asked question...

How could I get its parent? Result should be the store node.

Use a predicate rather than the parent:: or ancestor:: axis

Most answers here select the title and then traverse up to the targeted parent or ancestor (store) element. A simpler, direct approach is to select parent or ancestor element directly in the first place, obviating the need to traverse to a parent:: or ancestor:: axes:

//*[book/title = "50"]

Should the intervening elements vary in name:

//*[*/title = "50"]

Or, in name and depth:

//*[.//title = "50"]

How to import an existing directory into Eclipse?

I Using below simple way to create a project 1- First in a directory that desire to make it project, create a .project file with below contents:

<projectDescription>
    <name>Project-Name</name>
    <comment></comment>
    <projects>
    </projects>
    <buildSpec>
    </buildSpec>
    <natures>
    </natures>
</projectDescription>

2- Now instead of "Project-Name", write your project name, maybe current directory name

3- Now save this file to directory that desire to make that directory as project with name ".project" ( for save like this, use Notepad )

4- Now go to Eclips and open project and add your files to it.

alter the size of column in table containing data

Case 1 : Yes, this works fine.

Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.

Share and enjoy.

Java get last element of a collection

A Collection is not a necessarily ordered set of elements so there may not be a concept of the "last" element. If you want something that's ordered, you can use a SortedSet which has a last() method. Or you can use a List and call mylist.get(mylist.size()-1);

If you really need the last element you should use a List or a SortedSet. But if all you have is a Collection and you really, really, really need the last element, you could use toArray() or you could use an Iterator and iterate to the end of the list.

For example:

public Object getLastElement(final Collection c) {
    final Iterator itr = c.iterator();
    Object lastElement = itr.next();
    while(itr.hasNext()) {
        lastElement = itr.next();
    }
    return lastElement;
}

Bold & Non-Bold Text In A Single UILabel?

Update

In Swift we don't have to deal with iOS5 old stuff besides syntax is shorter so everything becomes really simple:

Swift 5

func attributedString(from string: String, nonBoldRange: NSRange?) -> NSAttributedString {
    let fontSize = UIFont.systemFontSize
    let attrs = [
        NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: fontSize),
        NSAttributedString.Key.foregroundColor: UIColor.black
    ]
    let nonBoldAttribute = [
        NSAttributedString.Key.font: UIFont.systemFont(ofSize: fontSize),
    ]
    let attrStr = NSMutableAttributedString(string: string, attributes: attrs)
    if let range = nonBoldRange {
        attrStr.setAttributes(nonBoldAttribute, range: range)
    }
    return attrStr
}

Swift 3

func attributedString(from string: String, nonBoldRange: NSRange?) -> NSAttributedString {
    let fontSize = UIFont.systemFontSize
    let attrs = [
        NSFontAttributeName: UIFont.boldSystemFont(ofSize: fontSize),
        NSForegroundColorAttributeName: UIColor.black
    ]
    let nonBoldAttribute = [
        NSFontAttributeName: UIFont.systemFont(ofSize: fontSize),
    ]
    let attrStr = NSMutableAttributedString(string: string, attributes: attrs)
    if let range = nonBoldRange {
        attrStr.setAttributes(nonBoldAttribute, range: range)
    }
    return attrStr
}

Usage:

let targetString = "Updated 2012/10/14 21:59 PM"
let range = NSMakeRange(7, 12)

let label = UILabel(frame: CGRect(x:0, y:0, width:350, height:44))
label.backgroundColor = UIColor.white
label.attributedText = attributedString(from: targetString, nonBoldRange: range)
label.sizeToFit()

Bonus: Internationalisation

Some people commented about internationalisation. I personally think this is out of scope of this question but for instructional purposes this is how I would do it

// Date we want to show
let date = Date()

// Create the string.
// I don't set the locale because the default locale of the formatter is `NSLocale.current` so it's good for internationalisation :p
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
let targetString = String(format: NSLocalizedString("Update %@", comment: "Updated string format"),
                          formatter.string(from: date))

// Find the range of the non-bold part
formatter.timeStyle = .none
let nonBoldRange = targetString.range(of: formatter.string(from: date))

// Convert Range<Int> into NSRange
let nonBoldNSRange: NSRange? = nonBoldRange == nil ?
    nil :
    NSMakeRange(targetString.distance(from: targetString.startIndex, to: nonBoldRange!.lowerBound),
                targetString.distance(from: nonBoldRange!.lowerBound, to: nonBoldRange!.upperBound))

// Now just build the attributed string as before :)
label.attributedText = attributedString(from: targetString,
                                        nonBoldRange: nonBoldNSRange)

Result (Assuming English and Japanese Localizable.strings are available)

enter image description here

enter image description here


Previous answer for iOS6 and later (Objective-C still works):

In iOS6 UILabel, UIButton, UITextView, UITextField, support attributed strings which means we don't need to create CATextLayers as our recipient for attributed strings. Furthermore to make the attributed string we don't need to play with CoreText anymore :) We have new classes in obj-c Foundation.framework like NSParagraphStyle and other constants that will make our life easier. Yay!

So, if we have this string:

NSString *text = @"Updated: 2012/10/14 21:59"

We only need to create the attributed string:

if ([_label respondsToSelector:@selector(setAttributedText:)])
{
    // iOS6 and above : Use NSAttributedStrings

    // Create the attributes
    const CGFloat fontSize = 13;
    NSDictionary *attrs = @{
        NSFontAttributeName:[UIFont boldSystemFontOfSize:fontSize],
        NSForegroundColorAttributeName:[UIColor whiteColor]
    };
    NSDictionary *subAttrs = @{
        NSFontAttributeName:[UIFont systemFontOfSize:fontSize]
    };

    // Range of " 2012/10/14 " is (8,12). Ideally it shouldn't be hardcoded
    // This example is about attributed strings in one label
    // not about internationalisation, so we keep it simple :)
    // For internationalisation example see above code in swift
    const NSRange range = NSMakeRange(8,12);

    // Create the attributed string (text + attributes)
    NSMutableAttributedString *attributedText =
      [[NSMutableAttributedString alloc] initWithString:text
                                             attributes:attrs];
    [attributedText setAttributes:subAttrs range:range];

    // Set it in our UILabel and we are done!
    [_label setAttributedText:attributedText];
} else {
    // iOS5 and below
    // Here we have some options too. The first one is to do something
    // less fancy and show it just as plain text without attributes.
    // The second is to use CoreText and get similar results with a bit
    // more of code. Interested people please look down the old answer.

    // Now I am just being lazy so :p
    [_label setText:text];
}

There is a couple of good introductory blog posts here from guys at invasivecode that explain with more examples uses of NSAttributedString, look for "Introduction to NSAttributedString for iOS 6" and "Attributed strings for iOS using Interface Builder" :)

PS: Above code it should work but it was brain-compiled. I hope it is enough :)


Old Answer for iOS5 and below

Use a CATextLayer with an NSAttributedString ! much lighter and simpler than 2 UILabels. (iOS 3.2 and above)

Example.

Don't forget to add QuartzCore framework (needed for CALayers), and CoreText (needed for the attributed string.)

#import <QuartzCore/QuartzCore.h>
#import <CoreText/CoreText.h>

Below example will add a sublayer to the toolbar of the navigation controller. à la Mail.app in the iPhone. :)

- (void)setRefreshDate:(NSDate *)aDate
{
    [aDate retain];
    [refreshDate release];
    refreshDate = aDate;

    if (refreshDate) {

        /* Create the text for the text layer*/    
        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        [df setDateFormat:@"MM/dd/yyyy hh:mm"];

        NSString *dateString = [df stringFromDate:refreshDate];
        NSString *prefix = NSLocalizedString(@"Updated", nil);
        NSString *text = [NSString stringWithFormat:@"%@: %@",prefix, dateString];
        [df release];

        /* Create the text layer on demand */
        if (!_textLayer) {
            _textLayer = [[CATextLayer alloc] init];
            //_textLayer.font = [UIFont boldSystemFontOfSize:13].fontName; // not needed since `string` property will be an NSAttributedString
            _textLayer.backgroundColor = [UIColor clearColor].CGColor;
            _textLayer.wrapped = NO;
            CALayer *layer = self.navigationController.toolbar.layer; //self is a view controller contained by a navigation controller
            _textLayer.frame = CGRectMake((layer.bounds.size.width-180)/2 + 10, (layer.bounds.size.height-30)/2 + 10, 180, 30);
            _textLayer.contentsScale = [[UIScreen mainScreen] scale]; // looks nice in retina displays too :)
            _textLayer.alignmentMode = kCAAlignmentCenter;
            [layer addSublayer:_textLayer];
        }

        /* Create the attributes (for the attributed string) */
        CGFloat fontSize = 13;
        UIFont *boldFont = [UIFont boldSystemFontOfSize:fontSize];
        CTFontRef ctBoldFont = CTFontCreateWithName((CFStringRef)boldFont.fontName, boldFont.pointSize, NULL);
        UIFont *font = [UIFont systemFontOfSize:13];
        CTFontRef ctFont = CTFontCreateWithName((CFStringRef)font.fontName, font.pointSize, NULL);
        CGColorRef cgColor = [UIColor whiteColor].CGColor;
        NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                    (id)ctBoldFont, (id)kCTFontAttributeName,
                                    cgColor, (id)kCTForegroundColorAttributeName, nil];
        CFRelease(ctBoldFont);
        NSDictionary *subAttributes = [NSDictionary dictionaryWithObjectsAndKeys:(id)ctFont, (id)kCTFontAttributeName, nil];
        CFRelease(ctFont);

        /* Create the attributed string (text + attributes) */
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:text attributes:attributes];
        [attrStr addAttributes:subAttributes range:NSMakeRange(prefix.length, 12)]; //12 is the length of " MM/dd/yyyy/ "

        /* Set the attributes string in the text layer :) */
        _textLayer.string = attrStr;
        [attrStr release];

        _textLayer.opacity = 1.0;
    } else {
        _textLayer.opacity = 0.0;
        _textLayer.string = nil;
    }
}

In this example I only have two different types of font (bold and normal) but you could also have different font size, different color, italics, underlined, etc. Take a look at NSAttributedString / NSMutableAttributedString and CoreText attributes string keys.

Hope it helps

Created Button Click Event c#

Create the Button and add it to Form.Controls list to display it on your form:

Button buttonOk = new Button();
buttonOk.Location = new Point(295, 45);  //or what ever position you want it to give
buttonOk.Text = "OK"; //or what ever you want to write over it
buttonOk.Click += new EventHandler(buttonOk_Click);
this.Controls.Add(buttonOk); //here you add it to the Form's Controls list

Create the button click method here:

void buttonOk_Click(object sender, EventArgs e)
        {
            MessageBox.Show("clicked");
            this.Close(); //all your choice to close it or remove this line
        }

Syncing Android Studio project with Gradle files

Keys combination:

Ctrl + F5

Syncs the project with Gradle files.

Oracle get previous day records

You can remove the time part of a date by using TRUNC.

select field,datetime_field 
  from database
 where datetime_field >= trunc(sysdate-1,'DD');

That query will give you all rows with dates starting from yesterday. Note the second argument to trunc(). You can use this to truncate any part of the date.

If your datetime_fied contains '2011-05-04 08:23:54', the following date will be returned

trunc(datetime_field, 'HH24') => 2011-05-04 08:00:00
trunc(datetime_field, 'DD')   => 2011-05-04 00:00:00
trunc(datetime_field, 'MM')   => 2011-05-01 00:00:00
trunc(datetime_field, 'YYYY') => 2011-00-01 00:00:00

Check, using jQuery, if an element is 'display:none' or block on click

You can use :visible for visible elements and :hidden to find out hidden elements. This hidden elements have display attribute set to none.

hiddenElements = $(':hidden');
visibleElements = $(':visible');

To check particular element.

if($('#yourID:visible').length == 0)
{

}

Elements are considered visible if they consume space in the document. Visible elements have a width or height that is greater than zero, Reference

You can also use is() with :visible

if(!$('#yourID').is(':visible'))
{

}

If you want to check value of display then you can use css()

if($('#yourID').css('display') == 'none')
{

}

If you are using display the following values display can have.

display: none

display: inline

display: block

display: list-item

display: inline-block

Check complete list of possible display values here.

To check the display property with JavaScript

var isVisible = document.getElementById("yourID").style.display == "block";
var isHidden = document.getElementById("yourID").style.display == "none"; 

How do I correctly setup and teardown for my pytest class with tests?

import pytest
class Test:
    @pytest.fixture()
    def setUp(self):
        print("setup")
        yield "resource"
        print("teardown")

    def test_that_depends_on_resource(self, setUp):
        print("testing {}".format(setUp))

In order to run:

pytest nam_of_the_module.py -v 

Pandas convert dataframe to array of tuples

The most efficient and easy way:

list(data_set.to_records())

You can filter the columns you need before this call.

How to put a jar in classpath in Eclipse?

First copy your jar file and paste into you Android project's libs folder.

Now right click on newly added (Pasted) jar file and select option

Build Path -> Add to build path

Now you added jar file will get displayed under Referenced Libraries. Again right click on it and select option

Build Path -> Configure Build path

A new window will get appeared. Select Java Build Path from left menu panel and then select Order and export Enable check on added jar file.

Now run your project.

More details @ Add-JARs-to-Project-Build-Paths-in-Eclipse-(Java)

select the TOP N rows from a table

select * from table_name LIMIT 100

remember this only works with MYSQL

Click events on Pie Charts in Chart.js

I have an elegant solution to this problem. If you have multiple dataset, identifying which dataset was clicked gets tricky. The _datasetIndex always returns zero. But this should do the trick. It will get you the label and the dataset label as well. Please note ** this.getElementAtEvent** is without the s in getElement

options: {
   onClick: function (e, items) {
    var firstPoint = this.getElementAtEvent(e)[0];
    if (firstPoint) {
      var label = firstPoint._model.label;
      var val = firstPoint._model.datasetLabel;
      console.log(label+" - "+val);
    }
    
  }
}

MySQL high CPU usage

First I'd say you probably want to turn off persistent connections as they almost always do more harm than good.

Secondly I'd say you want to double check your MySQL users, just to make sure it's not possible for anyone to be connecting from a remote server. This is also a major security thing to check.

Thirdly I'd say you want to turn on the MySQL Slow Query Log to keep an eye on any queries that are taking a long time, and use that to make sure you don't have any queries locking up key tables for too long.

Some other things you can check would be to run the following query while the CPU load is high:

SHOW PROCESSLIST;

This will show you any queries that are currently running or in the queue to run, what the query is and what it's doing (this command will truncate the query if it's too long, you can use SHOW FULL PROCESSLIST to see the full query text).

You'll also want to keep an eye on things like your buffer sizes, table cache, query cache and innodb_buffer_pool_size (if you're using innodb tables) as all of these memory allocations can have an affect on query performance which can cause MySQL to eat up CPU.

You'll also probably want to give the following a read over as they contain some good information.

It's also a very good idea to use a profiler. Something you can turn on when you want that will show you what queries your application is running, if there's duplicate queries, how long they're taking, etc, etc. An example of something like this is one I've been working on called PHP Profiler but there are many out there. If you're using a piece of software like Drupal, Joomla or Wordpress you'll want to ask around within the community as there's probably modules available for them that allow you to get this information without needing to manually integrate anything.

Android Recyclerview GridLayoutManager column spacing

Here is my modification of SpacesItemDecoration which can take numOfColums and space equally on top, bottom, left and right.

public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
    private int space;
    private int mNumCol;

    public SpacesItemDecoration(int space, int numCol) {
        this.space = space;
        this.mNumCol=numCol;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view,
                               RecyclerView parent, RecyclerView.State state) {

        //outRect.right = space;
        outRect.bottom = space;
        //outRect.left = space;

        //Log.d("ttt", "item position" + parent.getChildLayoutPosition(view));
        int position=parent.getChildLayoutPosition(view);

        if(mNumCol<=2) {
            if (position == 0) {
                outRect.left = space;
                outRect.right = space / 2;
            } else {
                if ((position % mNumCol) != 0) {
                    outRect.left = space / 2;
                    outRect.right = space;
                } else {
                    outRect.left = space;
                    outRect.right = space / 2;
                }
            }
        }else{
            if (position == 0) {
                outRect.left = space;
                outRect.right = space / 2;
            } else {
                if ((position % mNumCol) == 0) {
                    outRect.left = space;
                    outRect.right = space/2;
                } else if((position % mNumCol) == (mNumCol-1)){
                    outRect.left = space/2;
                    outRect.right = space;
                }else{
                    outRect.left=space/2;
                    outRect.right=space/2;
                }
            }

        }

        if(position<mNumCol){
            outRect.top=space;
        }else{
            outRect.top=0;
        }
        // Add top margin only for the first item to avoid double space between items
        /*
        if (parent.getChildLayoutPosition(view) == 0 ) {

        } else {
            outRect.top = 0;
        }*/
    }
}

and use below code on your logic.

recyclerView.addItemDecoration(new SpacesItemDecoration(spacingInPixels, numCol));

Python Dictionary Comprehension

you can't hash a list like that. try this instead, it uses tuples

d[tuple([i for i in range(1,11)])] = True

int object is not iterable?

Side note: if you want to get the sum of all digits, you can simply do

print sum(int(digit) for digit in raw_input('Enter a number:'))

JavaScript onclick redirect

Just do

onclick="SubmitFrm"

The javascript: prefix is only required for link URLs.

Get all messages from Whatsapp

Whatsapp store all messages in an encrypted database (pyCrypt) which is very easy to decipher using Python.

You can fetch this database easily on Android, iPhone, Blackberry and dump it into html file. Here are complete instructions: Read, Extract WhatsApp Messages backup on Android, iPhone, Blackberry

Disclaimer: I researched and wrote this extensive guide.

How do Mockito matchers work?

Just a small addition to Jeff Bowman's excellent answer, as I found this question when searching for a solution to one of my own problems:

If a call to a method matches more than one mock's when trained calls, the order of the when calls is important, and should be from the most wider to the most specific. Starting from one of Jeff's examples:

when(foo.quux(anyInt(), anyInt())).thenReturn(true);
when(foo.quux(anyInt(), eq(5))).thenReturn(false);

is the order that ensures the (probably) desired result:

foo.quux(3 /*any int*/, 8 /*any other int than 5*/) //returns true
foo.quux(2 /*any int*/, 5) //returns false

If you inverse the when calls then the result would always be true.

Is there a C# case insensitive equals operator?

System.Collections.CaseInsensitiveComparer

or

System.StringComparer.OrdinalIgnoreCase

SQL Server, How to set auto increment after creating a table without data loss?

Changing the IDENTITY property is really a metadata only change. But to update the metadata directly requires starting the instance in single user mode and messing around with some columns in sys.syscolpars and is undocumented/unsupported and not something I would recommend or will give any additional details about.

For people coming across this answer on SQL Server 2012+ by far the easiest way of achieving this result of an auto incrementing column would be to create a SEQUENCE object and set the next value for seq as the column default.

Alternatively, or for previous versions (from 2005 onwards), the workaround posted on this connect item shows a completely supported way of doing this without any need for size of data operations using ALTER TABLE...SWITCH. Also blogged about on MSDN here. Though the code to achieve this is not very simple and there are restrictions - such as the table being changed can't be the target of a foreign key constraint.

Example code.

Set up test table with no identity column.

CREATE TABLE dbo.tblFoo 
(
bar INT PRIMARY KEY,
filler CHAR(8000),
filler2 CHAR(49)
)


INSERT INTO dbo.tblFoo (bar)
SELECT TOP (10000) ROW_NUMBER() OVER (ORDER BY (SELECT 0))
FROM master..spt_values v1, master..spt_values v2

Alter it to have an identity column (more or less instant).

BEGIN TRY;
    BEGIN TRANSACTION;

    /*Using DBCC CHECKIDENT('dbo.tblFoo') is slow so use dynamic SQL to
      set the correct seed in the table definition instead*/
    DECLARE @TableScript nvarchar(max)
    SELECT @TableScript = 
    '
    CREATE TABLE dbo.Destination(
        bar INT IDENTITY(' + 
                     CAST(ISNULL(MAX(bar),0)+1 AS VARCHAR) + ',1)  PRIMARY KEY,
        filler CHAR(8000),
        filler2 CHAR(49)
        )

        ALTER TABLE dbo.tblFoo SWITCH TO dbo.Destination;
    '       
    FROM dbo.tblFoo
    WITH (TABLOCKX,HOLDLOCK)

    EXEC(@TableScript)


    DROP TABLE dbo.tblFoo;

    EXECUTE sp_rename N'dbo.Destination', N'tblFoo', 'OBJECT';


    COMMIT TRANSACTION;
END TRY
BEGIN CATCH
    IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;
    PRINT ERROR_MESSAGE();
END CATCH;

Test the result.

INSERT INTO dbo.tblFoo (filler,filler2) 
OUTPUT inserted.*
VALUES ('foo','bar')

Gives

bar         filler    filler2
----------- --------- ---------
10001       foo       bar      

Clean up

DROP TABLE dbo.tblFoo

Finding out the name of the original repository you cloned from in Git

Powershell version of command for git repo name:

(git config --get remote.origin.url) -replace '.*/' -replace '.git'

Socket.IO handling disconnect event

Ok, instead of identifying players by name track with sockets through which they have connected. You can have a implementation like

Server

var allClients = [];
io.sockets.on('connection', function(socket) {
   allClients.push(socket);

   socket.on('disconnect', function() {
      console.log('Got disconnect!');

      var i = allClients.indexOf(socket);
      allClients.splice(i, 1);
   });
});

Hope this will help you to think in another way

WampServer orange icon

After removing the innodb_additional_mem_pool_size=4M from my.ini and killing that process that used the port that Mysql wanted I managed it to go.

Suggested fix: 1) The quick solution: Comment the line innodb_additional_mem_pool_size=4M in the service's 'my.ini' file, 2) exclude the option from the 5.7.4 default config file or 3) un-unknow the variable to mysql ;)

link: http://bugs.mysql.com/bug.php?id=72533

Use number 1, remove the whole line. Save to my.ini. Kill the process if you have one running (look at them with resmon.exe and kill them with command taskkill /pid pid-of-process /f), then start wampmysql and your icon should turn green.

Regards SB

How to see PL/SQL Stored Function body in Oracle

You can also use DBMS_METADATA:

select dbms_metadata.get_ddl('FUNCTION', 'FGETALGOGROUPKEY', 'PADCAMPAIGN') 
from dual

Making a UITableView scroll when text field is selected

Since you have textfields in a table, the best way really is to resize the table - you need to set the tableView.frame to be smaller in height by the size of the keyboard (I think around 165 pixels) and then expand it again when the keyboard is dismissed.

You can optionally also disable user interaction for the tableView at that time as well, if you do not want the user scrolling.

How to save user input into a variable in html and js

Change your javascript to:

var input = document.getElementById('userInput').value;

This will get the value that has been types into the text box, not a DOM object

Python - OpenCV - imread - Displaying Image

Looks like the image is too big and the window simply doesn't fit the screen. Create window with the cv2.WINDOW_NORMAL flag, it will make it scalable. Then you can resize it to fit your screen like this:

from __future__ import division
import cv2


img = cv2.imread('1.jpg')

screen_res = 1280, 720
scale_width = screen_res[0] / img.shape[1]
scale_height = screen_res[1] / img.shape[0]
scale = min(scale_width, scale_height)
window_width = int(img.shape[1] * scale)
window_height = int(img.shape[0] * scale)

cv2.namedWindow('dst_rt', cv2.WINDOW_NORMAL)
cv2.resizeWindow('dst_rt', window_width, window_height)

cv2.imshow('dst_rt', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

According to the OpenCV documentation CV_WINDOW_KEEPRATIO flag should do the same, yet it doesn't and it's value not even presented in the python module.

Sort a list of tuples by 2nd item (integer value)

From python wiki:

>>> from operator import itemgetter, attrgetter    
>>> sorted(student_tuples, key=itemgetter(2))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]    
>>> sorted(student_objects, key=attrgetter('age'))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

Why am I getting an error "Object literal may only specify known properties"?

As of TypeScript 1.6, properties in object literals that do not have a corresponding property in the type they're being assigned to are flagged as errors.

Usually this error means you have a bug (typically a typo) in your code, or in the definition file. The right fix in this case would be to fix the typo. In the question, the property callbackOnLoactionHash is incorrect and should have been callbackOnLocationHash (note the mis-spelling of "Location").

This change also required some updates in definition files, so you should get the latest version of the .d.ts for any libraries you're using.

Example:

interface TextOptions {
    alignment?: string;
    color?: string;
    padding?: number;
}
function drawText(opts: TextOptions) { ... }
drawText({ align: 'center' }); // Error, no property 'align' in 'TextOptions'

But I meant to do that

There are a few cases where you may have intended to have extra properties in your object. Depending on what you're doing, there are several appropriate fixes

Type-checking only some properties

Sometimes you want to make sure a few things are present and of the correct type, but intend to have extra properties for whatever reason. Type assertions (<T>v or v as T) do not check for extra properties, so you can use them in place of a type annotation:

interface Options {
    x?: string;
    y?: number;
}

// Error, no property 'z' in 'Options'
let q1: Options = { x: 'foo', y: 32, z: 100 };
// OK
let q2 = { x: 'foo', y: 32, z: 100 } as Options;
// Still an error (good):
let q3 = { x: 100, y: 32, z: 100 } as Options;

These properties and maybe more

Some APIs take an object and dynamically iterate over its keys, but have 'special' keys that need to be of a certain type. Adding a string indexer to the type will disable extra property checking

Before

interface Model {
  name: string;
}
function createModel(x: Model) { ... }

// Error
createModel({name: 'hello', length: 100});

After

interface Model {
  name: string;
  [others: string]: any;
}
function createModel(x: Model) { ... }

// OK
createModel({name: 'hello', length: 100});

This is a dog or a cat or a horse, not sure yet

interface Animal { move; }
interface Dog extends Animal { woof; }
interface Cat extends Animal { meow; }
interface Horse extends Animal { neigh; }

let x: Animal;
if(...) {
  x = { move: 'doggy paddle', woof: 'bark' };
} else if(...) {
  x = { move: 'catwalk', meow: 'mrar' };
} else {
  x = { move: 'gallop', neigh: 'wilbur' };
}

Two good solutions come to mind here

Specify a closed set for x

// Removes all errors
let x: Dog|Cat|Horse;

or Type assert each thing

// For each initialization
  x = { move: 'doggy paddle', woof: 'bark' } as Dog;

This type is sometimes open and sometimes not

A clean solution to the "data model" problem using intersection types:

interface DataModelOptions {
  name?: string;
  id?: number;
}
interface UserProperties {
  [key: string]: any;
}
function createDataModel(model: DataModelOptions & UserProperties) {
 /* ... */
}
// findDataModel can only look up by name or id
function findDataModel(model: DataModelOptions) {
 /* ... */
}
// OK
createDataModel({name: 'my model', favoriteAnimal: 'cat' });
// Error, 'ID' is not correct (should be 'id')
findDataModel({ ID: 32 });

See also https://github.com/Microsoft/TypeScript/issues/3755

IOError: [Errno 32] Broken pipe: Python

To bring Alex L.'s helpful answer, akhan's helpful answer, and Blckknght's helpful answer together with some additional information:

  • Standard Unix signal SIGPIPE is sent to a process writing to a pipe when there's no process reading from the pipe (anymore).

    • This is not necessarily an error condition; some Unix utilities such as head by design stop reading prematurely from a pipe, once they've received enough data.
  • By default - i.e., if the writing process does not explicitly trap SIGPIPE - the writing process is simply terminated, and its exit code is set to 141, which is calculated as 128 (to signal termination by signal in general) + 13 (SIGPIPE's specific signal number).

  • By design, however, Python itself traps SIGPIPE and translates it into a Python IOError instance with errno value errno.EPIPE, so that a Python script can catch it, if it so chooses - see Alex L.'s answer for how to do that.

  • If a Python script does not catch it, Python outputs error message IOError: [Errno 32] Broken pipe and terminates the script with exit code 1 - this is the symptom the OP saw.

  • In many cases this is more disruptive than helpful, so reverting to the default behavior is desirable:

    • Using the signal module allows just that, as stated in akhan's answer; signal.signal() takes a signal to handle as the 1st argument and a handler as the 2nd; special handler value SIG_DFL represents the system's default behavior:

      from signal import signal, SIGPIPE, SIG_DFL
      signal(SIGPIPE, SIG_DFL) 
      

Angular 5 Service to read local .json file

Try This

Write code in your service

import {Observable, of} from 'rxjs';

import json file

import Product  from "./database/product.json";

getProduct(): Observable<any> {
   return of(Product).pipe(delay(1000));
}

In component

get_products(){
    this.sharedService.getProduct().subscribe(res=>{
        console.log(res);
    })        
}

Add image in pdf using jspdf

I find it useful.

var imgData = 'data:image/jpeg;base64,verylongbase64;'

var doc = new jsPDF();

doc.setFontSize(40);
doc.text(35, 25, "Octonyan loves jsPDF");
doc.addImage(imgData, 'JPEG', 15, 40, 180, 180);

http://mrrio.github.io/jsPDF/

Are arrays passed by value or passed by reference in Java?

The definitive discussion of arrays is at http://docs.oracle.com/javase/specs/jls/se5.0/html/arrays.html#27803 . This makes clear that Java arrays are objects. The class of these objects is defined in 10.8.

Section 8.4.1 of the language spec, http://docs.oracle.com/javase/specs/jls/se5.0/html/classes.html#40420 , describe how arguments are passed to methods. Since Java syntax is derived from C and C++, the behavior is similar. Primitive types are passed by value, as with C. When an object is passed, an object reference (pointer) is passed by value, mirroring the C syntax of passing a pointer by value. See 4.3.1, http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#4.3 ,

In practical terms, this means that modifying the contents of an array within a method is reflected in the array object in the calling scope, but reassigning a new value to the reference within the method has no effect on the reference in the calling scope, which is exactly the behavior you would expect of a pointer to a struct in C or an object in C++.

At least part of the confusion in terminology stems from the history of high level languages prior to the common use of C. In prior, popular, high level languages, directly referencing memory by address was something to be avoided to the extent possible, and it was considered the job of the language to provide a layer of abstraction. This made it necessary for the language to explicitly support a mechanism for returning values from subroutines (not necessarily functions). This mechanism is what is formally meant when referring to 'pass by reference'.

When C was introduced, it came with a stripped down notion of procedure calling, where all arguments are input-only, and the only value returned to the caller is a function result. However, the purpose of passing references could be achieved through the explicit and broad use of pointers. Since it serves the same purpose, the practice of passing a pointer as a reference to a value is often colloquially referred to a passing by reference. If the semantics of a routine call for a parameter to be passed by reference, the syntax of C requires the programmer to explicitly pass a pointer. Passing a pointer by value is the design pattern for implementing pass by reference semantics in C.

Since it can often seem like the sole purpose of raw pointers in C is to create crashing bugs, subsequent developments, especially Java, have sought to return to safer means to pass parameters. However, the dominance of C made it incumbent on the developers to mimic the familiar style of C coding. The result is references that are passed similarly to pointers, but are implemented with more protections to make them safer. An alternative would have been the rich syntax of a language like Ada, but this would have presented the appearance of an unwelcome learning curve, and lessened the likely adoption of Java.

In short, the design of parameter passing for objects, including arrays, in Java,is esentially to serve the semantic intent of pass by reference, but is imlemented with the syntax of passing a reference by value.

How to set <Text> text to upper case in react native

@Cherniv Thanks for the answer

<Text style={{}}> {'Test'.toUpperCase()} </Text>

Compiling an application for use in highly radioactive environments

Perhaps it would help to know does it mean for the hardware to be "designed for this environment". How does it correct and/or indicates the presence of SEU errors ?

At one space exploration related project, we had a custom MCU, which would raise an exception/interrupt on SEU errors, but with some delay, i.e. some cycles may pass/instructions be executed after the one insn which caused the SEU exception.

Particularly vulnerable was the data cache, so a handler would invalidate the offending cache line and restart the program. Only that, due to the imprecise nature of the exception, the sequence of insns headed by the exception raising insn may not be restartable.

We identified the hazardous (not restartable) sequences (like lw $3, 0x0($2), followed by an insn, which modifies $2 and is not data-dependent on $3), and I made modifications to GCC, so such sequences do not occur (e.g. as a last resort, separating the two insns by a nop).

Just something to consider ...

What is setContentView(R.layout.main)?

As per the documentation :

Set the activity content from a layout resource. The resource will be inflated, adding all top-level views to the activity.

Your Launcher activity in the manifest first gets called and it set the layout view as specified in respective java files setContentView(R.layout.main);. Now this activity uses setContentView(R.layout.main) to set xml layout to that activity which will actually render as the UI of your activity.

Why do Sublime Text 3 Themes not affect the sidebar?

You are looking for a Sublime UI Theme, which modifies Sublime's User Interface (e.g.: side bar). It's different from a Color Theme/Scheme, which modifies only the code part of Sublime's window. I tested a lot of UI Themes and the one I liked the most was Theme - Soda. You can install it using Sublime's Package Control. To enable it, go to Preferences >> Settings - User and add this line:

"theme": "Soda Dark 3.sublime-theme",

Here is a printscreen of my Sublime Text 3 with Soda Dark UI Theme and Twilight default Color Scheme:

enter image description here

Can promises have multiple arguments to onFulfilled?

I'm following the spec here and I'm not sure whether it allows onFulfilled to be called with multiple arguments.

Nope, just the first parameter will be treated as resolution value in the promise constructor. You can resolve with a composite value like an object or array.

I don't care about how any specific promises implementation does it, I wish to follow the w3c spec for promises closely.

That's where I believe you're wrong. The specification is designed to be minimal and is built for interoperating between promise libraries. The idea is to have a subset which DOM futures for example can reliably use and libraries can consume. Promise implementations do what you ask with .spread for a while now. For example:

Promise.try(function(){
    return ["Hello","World","!"];
}).spread(function(a,b,c){
    console.log(a,b+c); // "Hello World!";
});

With Bluebird. One solution if you want this functionality is to polyfill it.

if (!Promise.prototype.spread) {
    Promise.prototype.spread = function (fn) {
        return this.then(function (args) {
            return Promise.all(args); // wait for all
        }).then(function(args){
         //this is always undefined in A+ complaint, but just in case
            return fn.apply(this, args); 
        });
    };
}

This lets you do:

Promise.resolve(null).then(function(){
    return ["Hello","World","!"]; 
}).spread(function(a,b,c){
    console.log(a,b+c);    
});

With native promises at ease fiddle. Or use spread which is now (2018) commonplace in browsers:

Promise.resolve(["Hello","World","!"]).then(([a,b,c]) => {
  console.log(a,b+c);    
});

Or with await:

let [a, b, c] = await Promise.resolve(['hello', 'world', '!']);

Find distance between two points on map using Google Map API V2

In Google Map API V2 You have LatLng objects so you can't use distanceTo (yet).

You can then use the following code considering oldPosition and newPosition are LatLng objects :

// The computed distance is stored in results[0].
//If results has length 2 or greater, the initial bearing is stored in results[1].
//If results has length 3 or greater, the final bearing is stored in results[2].
float[] results = new float[1];
Location.distanceBetween(oldPosition.latitude, oldPosition.longitude,
                newPosition.latitude, newPosition.longitude, results);

For more informations about the Location class see this link

How can I generate random number in specific range in Android?

int min = 65;
int max = 80;

Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;

Note that nextInt(int max) returns an int between 0 inclusive and max exclusive. Hence the +1.

Is Visual Studio Community a 30 day trial?

Remember, if you are inside of private red with some proxy, you must be logout and relogin with an external WIFI for example.

Iptables setting multiple multiports in one rule

You need to use multiple rules to implement OR-like semantics, since matches are always AND-ed together within a rule. Alternatively, you can do matching against port-indexing ipsets (ipset create blah bitmap:port).

C char* to int conversion

Use atoi() from <stdlib.h>

http://linux.die.net/man/3/atoi

Or, write your own atoi() function which will convert char* to int

int a2i(const char *s)
{
  int sign=1;
  if(*s == '-'){
    sign = -1;
    s++;
  }
  int num=0;
  while(*s){
    num=((*s)-'0')+num*10;
    s++;   
  }
  return num*sign;
}

Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g

You need to merge the remote branch into your current branch by running git pull.

If your local branch is already up-to-date, you may also need to run git pull --rebase.

A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.

How to determine programmatically the current active profile using Spring boot

It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment to your bean.

@Autowired
private Environment environment;
....

this.environment.getActiveProfiles();

Increase number of axis ticks

Based on Daniel Krizian's comment, you can also use the pretty_breaks function from the scales library, which is imported automatically:

ggplot(dat, aes(x,y)) + geom_point() +
scale_x_continuous(breaks = scales::pretty_breaks(n = 10)) +
scale_y_continuous(breaks = scales::pretty_breaks(n = 10))

All you have to do is insert the number of ticks wanted for n.


A slightly less useful solution (since you have to specify the data variable again), you can use the built-in pretty function:

ggplot(dat, aes(x,y)) + geom_point() +
scale_x_continuous(breaks = pretty(dat$x, n = 10)) +
scale_y_continuous(breaks = pretty(dat$y, n = 10))

How to get Wikipedia content using Wikipedia's API?

<script>    
    function dowiki(place) {
        var URL = 'https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=';

        URL += "&titles=" + place;
        URL += "&rvprop=content";
        URL += "&callback=?";
        $.getJSON(URL, function (data) {
            var obj = data.query.pages;
            var ob = Object.keys(obj)[0];
            console.log(obj[ob]["extract"]);
            try{
                document.getElementById('Label11').textContent = obj[ob]["extract"];
            }
            catch (err) {
                document.getElementById('Label11').textContent = err.message;
            }

        });
    }
</script>

Convert numpy array to tuple

If you like long cuts, here is another way tuple(tuple(a_m.tolist()) for a_m in a )

from numpy import array
a = array([[1, 2],
           [3, 4]])
tuple(tuple(a_m.tolist()) for a_m in a )

The output is ((1, 2), (3, 4))

Note just (tuple(a_m.tolist()) for a_m in a ) will give a generator expresssion. Sort of inspired by @norok2's comment to Greg von Winckel's answer

adb uninstall failed

Just run ADB and use the following command:

adb shell pm uninstall -k --user 0 <package name>

And you should get this return:

successful

Changing the git user inside Visual Studio Code

There is a conflict between Visual Studio 2015 and Visual Studio Code for the git credentials. When i changed my credentials on VS 2015 VS Code let me push with the correct git ID.

What is a quick way to force CRLF in C# / .NET?

input.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\r\n")

This will work if the input contains only one type of line breaks - either CR, or LF, or CR+LF.

Label word wrapping

Change your maximum size,

label1.MaximumSize = new Size(100, 0);

And set your autosize to true.

label1.AutoSize = true;

That's it!

CSS transition with visibility not working

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

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

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

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

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

Semi-transparent color layer over background-image?

You need then a wrapping element with the bg image and in it the content element with the bg color:

<div id="Wrapper">
  <div id="Content">
    <!-- content here -->
  </div>
</div>

and the css:

#Wrapper{
    background:url(../img/bg/diagonalnoise.png); 
    width:300px; 
    height:300px;
}

#Content{
    background-color:rgba(248,247,216,0.7); 
    width:100%; 
    height:100%;
}

Rails: How can I set default values in ActiveRecord?

I've found that using a validation method provides a lot of control over setting defaults. You can even set defaults (or fail validation) for updates. You even set a different default value for inserts vs updates if you really wanted to. Note that the default won't be set until #valid? is called.

class MyModel
  validate :init_defaults

  private
  def init_defaults
    if new_record?
      self.some_int ||= 1
    elsif some_int.nil?
      errors.add(:some_int, "can't be blank on update")
    end
  end
end

Regarding defining an after_initialize method, there could be performance issues because after_initialize is also called by each object returned by :find : http://guides.rubyonrails.org/active_record_validations_callbacks.html#after_initialize-and-after_find

"webxml attribute is required" error in Maven

As per the documentation, it says : Whether or not to fail the build if the web.xml file is missing. Set to false if you want you WAR built without a web.xml file. This may be useful if you are building an overlay that has no web.xml file. Default value is: true. User property is: failOnMissingWebXml.

<plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.1.1</version>
    <extensions>false</extensions>
    <configuration>
        <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
</plugin>

Hope it makes more clear

Can I calculate z-score with R?

if x is a vector with raw scores then scale(x) is a vector with standardized scores.

Or manually: (x-mean(x))/sd(x)

Add 10 seconds to a Date

timeObject.setSeconds(timeObject.getSeconds() + 10)

How to create a stopwatch using JavaScript?

Please see stopwatch.js for a very clean and simple Vanilla Javascript ES6 solution.

How to match a line not containing a word

This should work:

/^((?!PART).)*$/

If you only wanted to exclude it from the beginning of the line (I know you don't, but just FYI), you could use this:

/^(?!PART)/

Edit (by request): Why this pattern works

The (?!...) syntax is a negative lookahead, which I've always found tough to explain. Basically, it means "whatever follows this point must not match the regular expression /PART/." The site I've linked explains this far better than I can, but I'll try to break this down:

^         #Start matching from the beginning of the string.    
(?!PART)  #This position must not be followed by the string "PART".
.         #Matches any character except line breaks (it will include those in single-line mode).
$         #Match all the way until the end of the string.

The ((?!xxx).)* idiom is probably hardest to understand. As we saw, (?!PART) looks at the string ahead and says that whatever comes next can't match the subpattern /PART/. So what we're doing with ((?!xxx).)* is going through the string letter by letter and applying the rule to all of them. Each character can be anything, but if you take that character and the next few characters after it, you'd better not get the word PART.

The ^ and $ anchors are there to demand that the rule be applied to the entire string, from beginning to end. Without those anchors, any piece of the string that didn't begin with PART would be a match. Even PART itself would have matches in it, because (for example) the letter A isn't followed by the exact string PART.

Since we do have ^ and $, if PART were anywhere in the string, one of the characters would match (?=PART). and the overall match would fail. Hope that's clear enough to be helpful.

PHP - remove all non-numeric characters from a string

Use \D to match non-digit characters.

preg_replace('~\D~', '', $str);

How to set background color of an Activity to white programmatically?

Get a handle to the root layout used, then set the background color on that. The root layout is whatever you called setContentView with.

 setContentView(R.layout.main);

  // Now get a handle to any View contained 
  // within the main layout you are using
  View someView = findViewById(R.id.randomViewInMainLayout);

  // Find the root view
  View root = someView.getRootView();

  // Set the color
  root.setBackgroundColor(getResources().getColor(android.R.color.red));

Set div height equal to screen size

try this

$(document).ready(function(){
    $('#content').height($(window).height());
});

How to split large text file in windows?

you can split using a third party software http://www.hjsplit.org/, for example give yours input that could be upto 9GB and then split, in my case I split 10 MB each enter image description here

Selecting one row from MySQL using mysql_* API

Though mysql_fetch_array will output numbers, its used to handle a large chunk. To echo the content of the row, use

echo $row['option_value'];

JSON.Parse,'Uncaught SyntaxError: Unexpected token o

Maybe what comes from the server is already evaluated as JSON object? For example, using jQuery get method:

$.get('/service', function(data) {  
  var obj = data;

      /* 
         "obj" is evaluated at this point if server responded 
         with "application/json" or similar.
       */
      for (var i = 0; i < obj.length; i++) {
        console.log(obj[i].Name);
      }
    });

Alternatively, if you need to turn JSON object into JSON string literal, you can use JSON.stringify:

var json = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];
var jsonString = JSON.stringify(json);

But in this case I don't understand why you can't just take the json variable and refer to it instead of stringifying and parsing.

Whoops, looks like something went wrong. Laravel 5.0

Please, try to find something like:

./website/config/app.php and set 'debug' => env('APP_DEBUG', false) as 'true' 'debug' => env('APP_DEBUG', true)

Twitter Bootstrap 3: how to use media queries?

:)

In latest bootstrap (4.3.1), using SCSS(SASS) you can use one of @mixin from /bootstrap/scss/mixins/_breakpoints.scss

Media of at least the minimum breakpoint width. No query for the smallest breakpoint. Makes the @content apply to the given breakpoint and wider.

@mixin media-breakpoint-up($name, $breakpoints: $grid-breakpoints)

Media of at most the maximum breakpoint width. No query for the largest breakpoint. Makes the @content apply to the given breakpoint and narrower.

@mixin media-breakpoint-down($name, $breakpoints: $grid-breakpoints)

Media that spans multiple breakpoint widths. Makes the @content apply between the min and max breakpoints

@mixin media-breakpoint-between($lower, $upper, $breakpoints: $grid-breakpoints)

Media between the breakpoint's minimum and maximum widths. No minimum for the smallest breakpoint, and no maximum for the largest one. Makes the @content apply only to the given breakpoint, not viewports any wider or narrower.

@mixin media-breakpoint-only($name, $breakpoints: $grid-breakpoints)

For example:

.content__extra {
  height: 100%;

  img {
    margin-right: 0.5rem;
  }

  @include media-breakpoint-down(xs) {
    margin-bottom: 1rem;
  }
}

Documentation:

Happy coding ;)

Core dumped, but core file is not in the current directory?

My efforts in WSL have been unsuccessful.

For those running on Windows Subsystem for Linux (WSL) there seems to be an open issue at this time for missing core dump files.

The comments indicate that

This is a known issue that we are aware of, it is something we are investigating.

Github issue

Windows Developer Feedback

How can I represent a range in Java?

You will have an if-check no matter how efficient you try to optimize this not-so-intensive computation :) You can subtract the upper bound from the number and if it's positive you know you are out of range. You can perhaps perform some boolean bit-shift logic to figure it out and you can even use Fermat's theorem if you want (kidding :) But the point is "why" do you need to optimize this comparison? What's the purpose?

Best way to alphanumeric check in JavaScript

    // On keypress event call the following method
    function AlphaNumCheck(e) {
        var charCode = (e.which) ? e.which : e.keyCode;
        if (charCode == 8) return true;

        var keynum;
        var keychar;
        var charcheck = /[a-zA-Z0-9]/;
        if (window.event) // IE
        {
            keynum = e.keyCode;
        }
        else {
            if (e.which) // Netscape/Firefox/Opera
            {
                keynum = e.which;
            }
            else return true;
        }

        keychar = String.fromCharCode(keynum);
        return charcheck.test(keychar);
    }

Further, this article also helps to understand JavaScript alphanumeric validation.

Static extension methods

specifically I want to overload Boolean.Parse to allow an int argument.

Would an extension for int work?

public static bool ToBoolean(this int source){
    // do it
    // return it
}

Then you can call it like this:

int x = 1;

bool y = x.ToBoolean();

Laravel Eloquent ORM Transactions

If you want to use Eloquent, you also can use this

This is just sample code from my project

        /* 
         * Saving Question
         */
        $question = new Question;
        $questionCategory = new QuestionCategory;

        /*
         * Insert new record for question
         */
        $question->title = $title;
        $question->user_id = Auth::user()->user_id;
        $question->description = $description;
        $question->time_post = date('Y-m-d H:i:s');

        if(Input::has('expiredtime'))
            $question->expired_time = Input::get('expiredtime');

        $questionCategory->category_id = $category;
        $questionCategory->time_added = date('Y-m-d H:i:s');

        DB::transaction(function() use ($question, $questionCategory) {

            $question->save();

            /*
             * insert new record for question category
             */
            $questionCategory->question_id = $question->id;
            $questionCategory->save();
        });

Set background color of WPF Textbox in C# code

You can use hex colors:

your_contorl.Color = DirectCast(ColorConverter.ConvertFromString("#D8E0A627"), Color)

C pass int array pointer as parameter into a function

Make use of *(B) instead of *B[0]. Here, *(B+i) implies B[i] and *(B) implies B[0], that is
*(B+0)=*(B)=B[0].

#include <stdio.h>

int func(int *B){
    *B = 5;     
    // if you want to modify ith index element in the array just do *(B+i)=<value>
}

int main(void){

    int B[10] = {};
    printf("b[0] = %d\n\n", B[0]);
    func(B);
    printf("b[0] = %d\n\n", B[0]);
    return 0;
}

How to print binary number via printf

Although ANSI C does not have this mechanism, it is possible to use itoa() as a shortcut:

  char buffer [33];
  itoa (i,buffer,2);
  printf ("binary: %s\n",buffer);

Here's the origin:

itoa in cplusplus reference

It is non-standard C, but K&R mentioned the implementation in the C book, so it should be quite common. It should be in stdlib.h.

Relative paths based on file location instead of current working directory

Just one line will be OK.

cat "`dirname $0`"/../some.txt

What is AF_INET, and why do I need it?

The primary purpose of AF_INET was to allow for other possible network protocols or address families (AF is for address family; PF_INET is for the (IPv4) internet protocol family). For example, there probably are a few Netware SPX/IPX networks around still; there were other network systems like DECNet, StarLAN and SNA, not to mention the ill-begotten ISO OSI (Open Systems Interconnection), and these did not necessarily use the now ubiquitous IP address to identify the peer host in network connections.

The ubiquitous alternative to AF_INET (which, in retrospect, should have been named AF_INET4) is AF_INET6, for the IPv6 address family. IPv4 uses 32-bit addresses; IPv6 uses 128-bit addresses.

You may see some other values - but they are unusual. It is there to allow for alternatives and future directions. The sockets interface is actually very general indeed - which is one of the reasons it has thrived where other networking interfaces have withered.

Life has (mostly) gotten simpler - be grateful.

What are the "standard unambiguous date" formats for string-to-date conversion in R?

This is documented behavior. From ?as.Date:

format: A character string. If not specified, it will try '"%Y-%m-%d"' then '"%Y/%m/%d"' on the first non-'NA' element, and give an error if neither works.

as.Date("01 Jan 2000") yields an error because the format isn't one of the two listed above. as.Date("01/01/2000") yields an incorrect answer because the date isn't in one of the two formats listed above.

I take "standard unambiguous" to mean "ISO-8601" (even though as.Date isn't that strict, as "%m/%d/%Y" isn't ISO-8601).

If you receive this error, the solution is to specify the format your date (or datetimes) are in, using the formats described in ?strptime. Be sure to use particular care if your data contain day/month names and/or abbreviations, as the conversion will depend on your locale (see the examples in ?strptime and read ?LC_TIME).

How can I delete a query string parameter in JavaScript?

function removeParamInAddressBar(parameter) {
    var url = document.location.href;
    var urlparts = url.split('?');

    if (urlparts.length >= 2) {
        var urlBase = urlparts.shift();
        var queryString = urlparts.join("?");

        var prefix = encodeURIComponent(parameter) + '=';
        var pars = queryString.split(/[&;]/g);
        for (var i = pars.length; i-- > 0;) {
            if (pars[i].lastIndexOf(prefix, 0) !== -1) {
                pars.splice(i, 1);
            }
        }

        if (pars.length == 0) {
            url = urlBase;
        } else {
            url = urlBase + '?' + pars.join('&');
        }

        window.history.pushState('', document.title, url); // push the new url in address bar
    }
    return url;
}

In Python, can I call the main() of an imported module?

It depends. If the main code is protected by an if as in:

if __name__ == '__main__':
    ...main code...

then no, you can't make Python execute that because you can't influence the automatic variable __name__.

But when all the code is in a function, then might be able to. Try

import myModule

myModule.main()

This works even when the module protects itself with a __all__.

from myModule import * might not make main visible to you, so you really need to import the module itself.

Header div stays at top, vertical scrolling div below with scrollbar only attached to that div

HTML:

?<div class="header">This is the header</div>
<div class="content">This is the content</div>?????????????????????????????????

CSS:

?.header
{
    height:50px;
}
.content
{
    position:absolute;
    top: 50px;
    left:0px;
    right:0px;
    bottom:0px;
    overflow-y:scroll;        
}?

PuTTY scripting to log onto host

I want to suggest a common solution for those requirements, maybe it is a use for you: AutoIt. With that program, you can write scripts on top of any window like Putty and execute all commands you want to (like button pressing or mouse clicking in textboxes or buttons).

This way you can emulate all steps you are always doing with Putty.

How can I inspect the file system of a failed `docker build`?

Debugging build step failures is indeed very annoying.

The best solution I have found is to make sure that each step that does real work succeeds, and adding a check after those that fails. That way you get a committed layer that contains the outputs of the failed step that you can inspect.

A Dockerfile, with an example after the # Run DB2 silent installer line:

#
# DB2 10.5 Client Dockerfile (Part 1)
#
# Requires
#   - DB2 10.5 Client for 64bit Linux ibm_data_server_runtime_client_linuxx64_v10.5.tar.gz
#   - Response file for DB2 10.5 Client for 64bit Linux db2rtcl_nr.rsp 
#
#
# Using Ubuntu 14.04 base image as the starting point.
FROM ubuntu:14.04

MAINTAINER David Carew <[email protected]>

# DB2 prereqs (also installing sharutils package as we use the utility uuencode to generate password - all others are required for the DB2 Client) 
RUN dpkg --add-architecture i386 && apt-get update && apt-get install -y sharutils binutils libstdc++6:i386 libpam0g:i386 && ln -s /lib/i386-linux-gnu/libpam.so.0 /lib/libpam.so.0
RUN apt-get install -y libxml2


# Create user db2clnt
# Generate strong random password and allow sudo to root w/o password
#
RUN  \
   adduser --quiet --disabled-password -shell /bin/bash -home /home/db2clnt --gecos "DB2 Client" db2clnt && \
   echo db2clnt:`dd if=/dev/urandom bs=16 count=1 2>/dev/null | uuencode -| head -n 2 | grep -v begin | cut -b 2-10` | chgpasswd && \
   adduser db2clnt sudo && \
   echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers

# Install DB2
RUN mkdir /install
# Copy DB2 tarball - ADD command will expand it automatically
ADD v10.5fp9_linuxx64_rtcl.tar.gz /install/
# Copy response file
COPY  db2rtcl_nr.rsp /install/
# Run  DB2 silent installer
RUN mkdir /logs
RUN (/install/rtcl/db2setup -t /logs/trace -l /logs/log -u /install/db2rtcl_nr.rsp && touch /install/done) || /bin/true
RUN test -f /install/done || (echo ERROR-------; echo install failed, see files in container /logs directory of the last container layer; echo run docker run '<last image id>' /bin/cat /logs/trace; echo ----------)
RUN test -f /install/done

# Clean up unwanted files
RUN rm -fr /install/rtcl

# Login as db2clnt user
CMD su - db2clnt

How do I do logging in C# without using 3rd party libraries?

public void Logger(string lines)
{
  //Write the string to a file.append mode is enabled so that the log
  //lines get appended to  test.txt than wiping content and writing the log

  using(System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt", true))
  {
    file.WriteLine(lines);
  }
}

For more information MSDN

javascript find and remove object in array based on key value

I agree with the answers, a simple way if you want to find an object by id and remove it is simply like below code.

   var obj = JSON.parse(data);
   var newObj = obj.filter(item=>item.Id!=88);
       

How do I remove quotes from a string?

str_replace('"', "", $string);
str_replace("'", "", $string);

I assume you mean quotation marks?

Otherwise, go for some regex, this will work for html quotes for example:

preg_replace("/<!--.*?-->/", "", $string);

C-style quotes:

preg_replace("/\/\/.*?\n/", "\n", $string);

CSS-style quotes:

preg_replace("/\/*.*?\*\//", "", $string);

bash-style quotes:

preg-replace("/#.*?\n/", "\n", $string);

Etc etc...

Add values to app.config and retrieve them

I hope this works:

System.Configuration.Configuration config= ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

config.AppSettings.Settings["Yourkey"].Value = "YourValue";
config.Save(ConfigurationSaveMode.Modified);

What is the difference between instanceof and Class.isAssignableFrom(...)?

There is also another difference:

null instanceof X is false no matter what X is

null.getClass().isAssignableFrom(X) will throw a NullPointerException

Android button with different background colors

In the URL you pointed to, the button_text.xml is being used to set the textColor attribute.That it is reason they had the button_text.xml in res/color folder and therefore they used @color/button_text.xml

But you are trying to use it for background attribute. The background attribute looks for something in res/drawable folder.

check this i got this selector custom button from the internet.I dont have the link.but i thank the poster for this.It helped me.have this in the drawable folder

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape>
            <gradient
                android:startColor="@color/yellow1"
                android:endColor="@color/yellow2"
                android:angle="270" />
            <stroke
                android:width="3dp"
                android:color="@color/grey05" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>

    <item android:state_focused="true" >
        <shape>
            <gradient
                android:endColor="@color/orange4"
                android:startColor="@color/orange5"
                android:angle="270" />
            <stroke
                android:width="3dp"
                android:color="@color/grey05" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>

    <item>        
        <shape>
            <gradient
                android:endColor="@color/white1"
                android:startColor="@color/white2"
                android:angle="270" />
            <stroke
                android:width="3dp"
                android:color="@color/grey05" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>

</selector>

And i used in my main.xml layout like this

<Button android:id="@+id/button1"
            android:layout_alignParentLeft="true"
            android:layout_marginTop="150dip"
            android:layout_marginLeft="45dip"
            android:textSize="7pt"
            android:layout_height="wrap_content"
            android:layout_width="230dip"
            android:text="@string/welcomebtntitle1"
            android:background="@drawable/custombutton"/>

Hope this helps. Vik is correct.

EDIT : Here is the colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <color name="yellow1">#F9E60E</color>
   <color name="yellow2">#F9F89D</color>
   <color name="orange4">#F7BE45</color>
   <color name="orange5">#F7D896</color>
   <color name="blue2">#19FCDA</color>
   <color name="blue25">#D9F7F2</color>
   <color name="grey05">#ACA899</color>
   <color name="white1">#FFFFFF</color>
   <color name="white2">#DDDDDD</color>
</resources>

PHP's array_map including keys

I see it's missing the obvious answer:

function array_map_assoc(){
    if(func_num_args() < 2) throw new \BadFuncionCallException('Missing parameters');

    $args = func_get_args();
    $callback = $args[0];

    if(!is_callable($callback)) throw new \InvalidArgumentException('First parameter musst be callable');

    $arrays = array_slice($args, 1);

    array_walk($arrays, function(&$a){
        $a = (array)$a;
        reset($a);
    });

    $results = array();
    $max_length = max(array_map('count', $arrays));

    $arrays = array_map(function($pole) use ($max_length){
        return array_pad($pole, $max_length, null);
    }, $arrays);

    for($i=0; $i < $max_length; $i++){
        $elements = array();
        foreach($arrays as &$v){
            $elements[] = each($v);
        }
        unset($v);

        $out = call_user_func_array($callback, $elements);

        if($out === null) continue;

        $val = isset($out[1]) ? $out[1] : null;

        if(isset($out[0])){
            $results[$out[0]] = $val;
        }else{
            $results[] = $val;
        }
    }

    return $results;
}

Works exactly like array_map. Almost.

Actually, it's not pure map as you know it from other languages. Php is very weird, so it requires some very weird user functions, for we don't want to unbreak our precisely broken worse is better approach.

Really, it's not actually map at all. Yet, it's still very useful.

  • First obvious difference from array_map, is that the callback takes outputs of each() from every input array instead of value alone. You can still iterate through more arrays at once.

  • Second difference is the way the key is handled after it's returned from callback; the return value from callback function should be array('new_key', 'new_value'). Keys can and will be changed, same keys can even cause previous value being overwritten, if same key was returned. This is not common map behavior, yet it allows you to rewrite keys.

  • Third weird thing is, if you omit key in return value (either by array(1 => 'value') or array(null, 'value')), new key is going to be assigned, as if $array[] = $value was used. That isn't map's common behavior either, yet it comes handy sometimes, I guess.

  • Fourth weird thing is, if callback function doesn't return a value, or returns null, the whole set of current keys and values is omitted from the output, it's simply skipped. This feature is totally unmappy, yet it would make this function excellent stunt double for array_filter_assoc, if there was such function.

  • If you omit second element (1 => ...) (the value part) in callback's return, null is used instead of real value.

  • Any other elements except those with keys 0 and 1 in callback's return are ignored.

  • And finally, if lambda returns any value except of null or array, it's treated as if both key and value were omitted, so:

    1. new key for element is assigned
    2. null is used as it's value
WARNING:
Bear in mind, that this last feature is just a residue of previous features and it is probably completely useless. Relying on this feature is highly discouraged, as this feature is going to be randomly deprecated and changed unexpectedly in future releases.

NOTE:
Unlike in array_map, all non-array parameters passed to array_map_assoc, with the exception of first callback parameter, are silently casted to arrays.

EXAMPLES:
// TODO: examples, anyone?

Python Image Library fails with message "decoder JPEG not available" - PIL

For those on OSX, I used the following binary to get libpng and libjpeg installed systemwide:

libpng & libjpeg for OSX

Because I already had PIL installed (via pip on a virtualenv), I ran:

pip uninstall PIL
pip install PIL --upgrade

This resolved the decoder JPEG not available error for me.

UPDATE (4/24/14):

Newer versions of pip require additional flags to download libraries (including PIL) from external sources. Try the following:

pip install PIL --allow-external PIL --allow-unverified PIL

See the following answer for additional info: pip install PIL dont install into virtualenv

UPDATE 2:

If on OSX Mavericks, you'll want to set the ARCHFLAGS flag as @RicardoGonzales comments below:

ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install PIL --allow-external PIL --allow-unverified PIL

Why do we need middleware for async flow in Redux?

The short answer: seems like a totally reasonable approach to the asynchrony problem to me. With a couple caveats.

I had a very similar line of thought when working on a new project we just started at my job. I was a big fan of vanilla Redux's elegant system for updating the store and rerendering components in a way that stays out of the guts of a React component tree. It seemed weird to me to hook into that elegant dispatch mechanism to handle asynchrony.

I ended up going with a really similar approach to what you have there in a library I factored out of our project, which we called react-redux-controller.

I ended up not going with the exact approach you have above for a couple reasons:

  1. The way you have it written, those dispatching functions don't have access to the store. You can somewhat get around that by having your UI components pass in all of the info the dispatching function needs. But I'd argue that this couples those UI components to the dispatching logic unnecessarily. And more problematically, there's no obvious way for the dispatching function to access updated state in async continuations.
  2. The dispatching functions have access to dispatch itself via lexical scope. This limits the options for refactoring once that connect statement gets out of hand -- and it's looking pretty unwieldy with just that one update method. So you need some system for letting you compose those dispatcher functions if you break them up into separate modules.

Take together, you have to rig up some system to allow dispatch and the store to be injected into your dispatching functions, along with the parameters of the event. I know of three reasonable approaches to this dependency injection:

  • redux-thunk does this in a functional way, by passing them into your thunks (making them not exactly thunks at all, by dome definitions). I haven't worked with the other dispatch middleware approaches, but I assume they're basically the same.
  • react-redux-controller does this with a coroutine. As a bonus, it also gives you access to the "selectors", which are the functions you may have passed in as the first argument to connect, rather than having to work directly with the raw, normalized store.
  • You could also do it the object-oriented way by injecting them into the this context, through a variety of possible mechanisms.

Update

It occurs to me that part of this conundrum is a limitation of react-redux. The first argument to connect gets a state snapshot, but not dispatch. The second argument gets dispatch but not the state. Neither argument gets a thunk that closes over the current state, for being able to see updated state at the time of a continuation/callback.

Python in Xcode 4+?

This thread is old, but to chime in for Xcode Version 8.3.3, Tyler Crompton's method in the accepted answer still works (some of the names are very slightly different, but not enough to matter).

2 points where I struggled slightly:

Step 16: If the python executable you want is greyed out, right click it and select quick look. Then close the quick look window, and it should now be selectable.

Step 19: If this isn’t working for you, you can enter the name of just the python file in the Arguments tab, and then enter the project root directory explicitly in the Options tab under Working Directory--check the “Use custom working directory” box, and type in your project root directory in the field below it.

redirect COPY of stdout to log file from within bash script itself

Solution for busybox, macOS bash, and non-bash shells

The accepted answer is certainly the best choice for bash. I'm working in a Busybox environment without access to bash, and it does not understand the exec > >(tee log.txt) syntax. It also does not do exec >$PIPE properly, trying to create an ordinary file with the same name as the named pipe, which fails and hangs.

Hopefully this would be useful to someone else who doesn't have bash.

Also, for anyone using a named pipe, it is safe to rm $PIPE, because that unlinks the pipe from the VFS, but the processes that use it still maintain a reference count on it until they are finished.

Note the use of $* is not necessarily safe.

#!/bin/sh

if [ "$SELF_LOGGING" != "1" ]
then
    # The parent process will enter this branch and set up logging

    # Create a named piped for logging the child's output
    PIPE=tmp.fifo
    mkfifo $PIPE

    # Launch the child process with stdout redirected to the named pipe
    SELF_LOGGING=1 sh $0 $* >$PIPE &

    # Save PID of child process
    PID=$!

    # Launch tee in a separate process
    tee logfile <$PIPE &

    # Unlink $PIPE because the parent process no longer needs it
    rm $PIPE    

    # Wait for child process, which is running the rest of this script
    wait $PID

    # Return the error code from the child process
    exit $?
fi

# The rest of the script goes here

Best way to get application folder path

Note that not all of these methods will return the same value. In some cases, they can return the same value, but be careful, their purposes are different:

Application.StartupPath

returns the StartupPath parameter (can be set when run the application)

System.IO.Directory.GetCurrentDirectory()

returns the current directory, which may or may not be the folder where the application is located. The same goes for Environment.CurrentDirectory. In case you are using this in a DLL file, it will return the path of where the process is running (this is especially true in ASP.NET).

Determine if map contains a value for a key?

You can create your getValue function with the following code:

bool getValue(const std::map<int, Bar>& input, int key, Bar& out)
{
   std::map<int, Bar>::iterator foundIter = input.find(key);
   if (foundIter != input.end())
   {
      out = foundIter->second;
      return true;
   }
   return false;
}

Jboss server error : Failed to start service jboss.deployment.unit."jbpm-console.war"

I had a similar issue, my error was:

Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: java.lang.ClassNotFoundException:org.glassfish.jersey.servlet.ServletContainer from [Module "deployment.RESTful_Services_CRUD.war:main" from Service Module Loader]

I use jboss and glassfish so I changed the web.xml to the following:

<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>

Instead of:

<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>

Hope this work for you.

How to post query parameters with Axios?

As of 2021 insted of null i had to add {} in order to make it work!

axios.post(
        url,
        {},
        {
          params: {
            key,
            checksum
          }
        }
      )
      .then(response => {
        return success(response);
      })
      .catch(error => {
        return fail(error);
      });

Escaping a forward slash in a regular expression

Here are a few options:

  • In Perl, you can choose alternate delimiters. You're not confined to m//. You could choose another, such as m{}. Then escaping isn't necessary. As a matter of fact, Damian Conway in "Perl Best Practices" asserts that m{} is the only alternate delimiter that ought to be used, and this is reinforced by Perl::Critic (on CPAN). While you can get away with using a variety of alternate delimiter characters, // and {} seem to be the clearest to decipher later on. However, if either of those choices result in too much escaping, choose whichever one lends itself best to legibility. Common examples are m(...), m[...], and m!...!.

  • In cases where you either cannot or prefer not to use alternate delimiters, you can escape the forward slashes with a backslash: m/\/[^/]+$/ for example (using an alternate delimiter that could become m{/[^/]+$}, which may read more clearly). Escaping the slash with a backslash is common enough to have earned a name and a wikipedia page: Leaning Toothpick Syndrome. In regular expressions where there's just a single instance, escaping a slash might not rise to the level of being considered a hindrance to legibility, but if it starts to get out of hand, and if your language permits alternate delimiters as Perl does, that would be the preferred solution.

Return index of highest value in an array

My solution to get the higher key is as follows:

max(array_keys($values['Users']));

URL encode sees “&” (ampersand) as “&amp;” HTML entity

Without seeing your code, it's hard to answer other than a stab in the dark. I would guess that the string you're passing to encodeURIComponent(), which is the correct method to use, is coming from the result of accessing the innerHTML property. The solution is to get the innerText/textContent property value instead:

var str, 
    el = document.getElementById("myUrl");

if ("textContent" in el)
    str = encodeURIComponent(el.textContent);
else
    str = encodeURIComponent(el.innerText);

If that isn't the case, you can use the replace() method to replace the HTML entity:

encodeURIComponent(str.replace(/&amp;/g, "&"));

Get 2 Digit Number For The Month

Another simple trick:

SELECT CONVERT(char(2), cast('2015-01-01' as datetime), 101) -- month with 2 digits
SELECT CONVERT(char(6), cast('2015-01-01' as datetime), 112) -- year (yyyy) and month (mm)

Outputs:

01
201501

Returning anonymous type in C#

You can use the Tuple class as a substitute for an anonymous types when returning is necessary:

Note: Tuple can have up to 8 parameters.

return Tuple.Create(variable1, variable2);

Or, for the example from the original post:

public List<Tuple<SomeType, AnotherType>> TheMethod(SomeParameter)
{
  using (MyDC TheDC = new MyDC())
  {
     var TheQueryFromDB = (....
                           select Tuple.Create(..., ...)
                           ).ToList();

      return TheQueryFromDB.ToList();
    }
}

http://msdn.microsoft.com/en-us/library/system.tuple(v=vs.110).aspx

Removing first x characters from string?

Example to show last 3 digits of account number.

x = '1234567890'   
x.replace(x[:7], '')

o/p: '890'

Android: adbd cannot run as root in production builds

The problem is that, even though your phone is rooted, the 'adbd' server on the phone does not use root permissions. You can try to bypass these checks or install a different adbd on your phone or install a custom kernel/distribution that includes a patched adbd.

Or, a much easier solution is to use 'adbd insecure' from chainfire which will patch your adbd on the fly. It's not permanent, so you have to run it before starting up the adb server (or else set it to run every boot). You can get the app from the google play store for a couple bucks:

https://play.google.com/store/apps/details?id=eu.chainfire.adbd&hl=en

Or you can get it for free, the author has posted a free version on xda-developers:

http://forum.xda-developers.com/showthread.php?t=1687590

Install it to your device (copy it to the device and open the apk file with a file manager), run adb insecure on the device, and finally kill the adb server on your computer:

% adb kill-server

And then restart the server and it should already be root.

linq query to return distinct field values from a list of objects

I think this is what your looking for:

    var objs= (from c in List_Objects 
orderby c.TypeID  select c).GroupBy(g=>g.TypeID).Select(x=>x.FirstOrDefault());      

Similar to this Returning a Distinct IQueryable with LINQ?

Read whole ASCII file into C++ std::string

If you happen to use glibmm you can try Glib::file_get_contents.

#include <iostream>
#include <glibmm.h>

int main() {
    auto filename = "my-file.txt";
    try {
        std::string contents = Glib::file_get_contents(filename);
        std::cout << "File data:\n" << contents << std::endl;
    catch (const Glib::FileError& e) {
        std::cout << "Oops, an error occurred:\n" << e.what() << std::endl;
    }

    return 0;
}

How do you create a Marker with a custom icon for google maps API v3?

LatLng hello = new LatLng(X, Y);          // whereX & Y are coordinates

Bitmap icon = BitmapFactory.decodeResource(getApplicationContext().getResources(),
                R.drawable.university);   // where university is the icon name that is used as a marker.

mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(icon)).position(hello).title("Hello World!"));

mMap.moveCamera(CameraUpdateFactory.newLatLng(hello));

What is the role of "Flatten" in Keras?

Here I would like to present another alternative to Flatten function. This may help to understand what is going on internally. The alternative method adds three more code lines. Instead of using

#==========================================Build a Model
model = tf.keras.models.Sequential()

model.add(keras.layers.Flatten(input_shape=(28, 28, 3)))#reshapes to (2352)=28x28x3
model.add(layers.experimental.preprocessing.Rescaling(1./255))#normalize
model.add(keras.layers.Dense(128,activation=tf.nn.relu))
model.add(keras.layers.Dense(2,activation=tf.nn.softmax))

model.build()
model.summary()# summary of the model

we can use

    #==========================================Build a Model
    tensor = tf.keras.backend.placeholder(dtype=tf.float32, shape=(None, 28, 28, 3))
    
    model = tf.keras.models.Sequential()
    
    model.add(keras.layers.InputLayer(input_tensor=tensor))
    model.add(keras.layers.Reshape([2352]))
model.add(layers.experimental.preprocessing.Rescaling(1./255))#normalize
    model.add(keras.layers.Dense(128,activation=tf.nn.relu))
    model.add(keras.layers.Dense(2,activation=tf.nn.softmax))
    
    model.build()
    model.summary()# summary of the model

In the second case, we first create a tensor (using a placeholder) and then create an Input layer. After, we reshape the tensor to flat form. So basically,

Create tensor->Create InputLayer->Reshape == Flatten

Flatten is a convenient function, doing all this automatically. Of course both ways has its specific use cases. Keras provides enough flexibility to manipulate the way you want to create a model.

Does React Native styles support gradients?

U can try this JS code.. https://snack.expo.io/r1v0LwZFb

import React, { Component } from 'react';
import { View } from 'react-native';

export default class App extends Component {
  render() {
    const gradientHeight=500;
    const gradientBackground  = 'purple';
        const data = Array.from({ length: gradientHeight });
        return (
            <View style={{flex:1}}>
                {data.map((_, i) => (
                    <View
                        key={i}
                        style={{
                            position: 'absolute',
                            backgroundColor: gradientBackground,
                            height: 1,
                            bottom: (gradientHeight - i),
                            right: 0,
                            left: 0,
                            zIndex: 2,
                            opacity: (1 / gradientHeight) * (i + 1)
                        }}
                    />
                ))}
            </View>
        );
  }
}

How to convert a char array back to a string?

1 alternate way is to do:

String b = a + "";

Java ArrayList - Check if list is empty

You should use method listName.isEmpty()

How to overlay density plots in R?

use lines for the second one:

plot(density(MyData$Column1))
lines(density(MyData$Column2))

make sure the limits of the first plot are suitable, though.

Why does this SQL code give error 1066 (Not unique table/alias: 'user')?

Your error is because you have:

     JOIN user ON article.author_id = user.id
LEFT JOIN user ON article.modified_by = user.id

You have two instances of the same table, but the database can't determine which is which. To fix this, you need to use table aliases:

     JOIN USER u ON article.author_id = u.id
LEFT JOIN USER u2 ON article.modified_by = u2.id

It's good habit to always alias your tables, unless you like writing the full table name all the time when you don't have situations like these.

The next issues to address will be:

SELECT article.* , section.title, category.title, user.name, user.name

1) Never use SELECT * - always spell out the columns you want, even if it is the entire table. Read this SO Question to understand why.

2) You'll get ambiguous column errors relating to the user.name columns because again, the database can't tell which table instance to pull data from. Using table aliases fixes the issue:

SELECT article.* , section.title, category.title, u.name, u2.name

Angular.js: How does $eval work and why is it different from vanilla eval?

I think one of the original questions here was not answered. I believe that vanilla eval() is not used because then angular apps would not work as Chrome apps, which explicitly prevent eval() from being used for security reasons.

macro - open all files in a folder

You have to add this line just before loop

    MyFile = Dir
Loop

Serializing/deserializing with memory stream

Use Method to Serialize and Deserialize Collection object from memory. This works on Collection Data Types. This Method will Serialize collection of any type to a byte stream. Create a Seperate Class SerilizeDeserialize and add following two methods:

public class SerilizeDeserialize
{

    // Serialize collection of any type to a byte stream

    public static byte[] Serialize<T>(T obj)
    {
        using (MemoryStream memStream = new MemoryStream())
        {
            BinaryFormatter binSerializer = new BinaryFormatter();
            binSerializer.Serialize(memStream, obj);
            return memStream.ToArray();
        }
    }

    // DSerialize collection of any type to a byte stream

    public static T Deserialize<T>(byte[] serializedObj)
    {
        T obj = default(T);
        using (MemoryStream memStream = new MemoryStream(serializedObj))
        {
            BinaryFormatter binSerializer = new BinaryFormatter();
            obj = (T)binSerializer.Deserialize(memStream);
        }
        return obj;
    }

}

How To use these method in your Class:

ArrayList arrayListMem = new ArrayList() { "One", "Two", "Three", "Four", "Five", "Six", "Seven" };
Console.WriteLine("Serializing to Memory : arrayListMem");
byte[] stream = SerilizeDeserialize.Serialize(arrayListMem);

ArrayList arrayListMemDes = new ArrayList();

arrayListMemDes = SerilizeDeserialize.Deserialize<ArrayList>(stream);

Console.WriteLine("DSerializing From Memory : arrayListMemDes");
foreach (var item in arrayListMemDes)
{
    Console.WriteLine(item);
}

How to reset Jenkins security settings from the command line?

To very simply disable both security and the startup wizard, use the JAVA property:

-Djenkins.install.runSetupWizard=false

The nice thing about this is that you can use it in a Docker image such that your container will always start up immediately with no login screen:

# Dockerfile
FROM jenkins/jenkins:lts
ENV JAVA_OPTS -Djenkins.install.runSetupWizard=false

Note that, as mentioned by others, the Jenkins config.xml is in /var/jenkins_home in the image, but using sed to modify it from the Dockerfile fails, because (presumably) the config.xml doesn't exist until the server starts.

Equivalent function for DATEADD() in Oracle

Equivalent will be

ADD_MONTHS( SYSDATE, -6 )

What does '&' do in a C++ declaration?

string * and string& differ in a couple of ways. First of all, the pointer points to the address location of the data. The reference points to the data. If you had the following function:

int foo(string *param1);

You would have to check in the function declaration to make sure that param1 pointed to a valid location. Comparatively:

int foo(string &param1);

Here, it is the caller's responsibility to make sure the pointed to data is valid. You can't pass a "NULL" value, for example, int he second function above.

With regards to your second question, about the method return values being a reference, consider the following three functions:

string &foo();
string *foo();
string foo();

In the first case, you would be returning a reference to the data. If your function declaration looked like this:

string &foo()
{
    string localString = "Hello!";
    return localString;
}

You would probably get some compiler errors, since you are returning a reference to a string that was initialized in the stack for that function. On the function return, that data location is no longer valid. Typically, you would want to return a reference to a class member or something like that.

The second function above returns a pointer in actual memory, so it would stay the same. You would have to check for NULL-pointers, though.

Finally, in the third case, the data returned would be copied into the return value for the caller. So if your function was like this:

string foo()
{
    string localString = "Hello!";
    return localString;
}

You'd be okay, since the string "Hello" would be copied into the return value for that function, accessible in the caller's memory space.

How do I compare two strings in python?

open both of the files then compare them by splitting its word contents;

log_file_A='file_A.txt'

log_file_B='file_B.txt'

read_A=open(log_file_A,'r')
read_A=read_A.read()
print read_A

read_B=open(log_file_B,'r')
read_B=read_B.read()
print read_B

File_A_set = set(read_A.split(' '))
File_A_set = set(read_B.split(' '))
print File_A_set == File_B_set

JPA or JDBC, how are they different?

JDBC is the predecessor of JPA.

JDBC is a bridge between the Java world and the databases world. In JDBC you need to expose all dirty details needed for CRUD operations, such as table names, column names, while in JPA (which is using JDBC underneath), you also specify those details of database metadata, but with the use of Java annotations.

So JPA creates update queries for you and manages the entities that you looked up or created/updated (it does more as well).

If you want to do JPA without a Java EE container, then Spring and its libraries may be used with the very same Java annotations.

Is a DIV inside a TD a bad idea?

No. Not necessarily.

If you need to place a DIV within a TD, be sure you're using the TD properly. If you don't care about tabular-data, and semantics, then you ultimately won't care about DIVs in TDs. I don't think there's a problem though - if you have to do it, you're fine.

According to the HTML Specification

A <div> can be placed where flow content is expected1, which is the <td> content model2.

How to set focus to a button widget programmatically?

Yeah it's possible.

Button myBtn = (Button)findViewById(R.id.myButtonId);
myBtn.requestFocus();

or in XML

<Button ...><requestFocus /></Button>

Important Note: The button widget needs to be focusable and focusableInTouchMode. Most widgets are focusable but not focusableInTouchMode by default. So make sure to either set it in code

myBtn.setFocusableInTouchMode(true);

or in XML

android:focusableInTouchMode="true"

CSS to make table 100% of max-width

Use this :

<div style="width:700px; background:#F2F2F2">
    <table style="width:100%;padding: 25px; margin: 0 auto; font-family:'Open Sans', 'Helvetica', 'Arial';">
        <tr align="center" style="margin: 0; padding: 0;">
            <td>
                <table style="width:100%;border-style:solid; border-width:2px; border-color: #c3d2d9;" cellspacing="0">
                    <tr style="background-color: white;">
                        <td style=" padding: 10px 15px 10px 15px; color: #000000;">
                            <p>Some content here</p>
                            <span style="font-weight: bold;">My Signature</span><br/>
                            My Title<br/>
                            My Company<br/>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</div>

How to add a title to a html select tag

<select>
    <option selected disabled>Choose one</option>
    <option value="sydney">Sydney</option>
    <option value="melbourne">Melbourne</option>
    <option value="cromwell">Cromwell</option>
    <option value="queenstown">Queenstown</option>
</select>

Using selected and disabled will make "Choose one" be the default selected value, but also make it impossible for the user to actually select the item, like so:

Dropdown menu

Single selection in RecyclerView

I want to share the similar thing I have achieved, may be it will help someone. below code is from the application to select an address from a list of addresses that are displayed in cardview(cvAddress), so that on click of particular item(cardview) the imageView inside the item should set to different resource(select/unselect)

    @Override
public void onBindViewHolder(final AddressHolder holder, final int position)
{
    holderList.add(holder);
    holder.tvAddress.setText(addresses.get(position).getAddress());
    holder.cvAddress.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            selectCurrItem(position);
        }
    });
}

private void selectCurrItem(int position)
{
    int size = holderList.size();
    for(int i = 0; i<size; i++)
    {
        if(i==position)
            holderList.get(i).ivSelect.setImageResource(R.drawable.select);
        else
            holderList.get(i).ivSelect.setImageResource(R.drawable.unselect);
    }
}

I don't know this is best solution or not but this worked for me.

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

The most simple way is to use Record type Record<number, productDetails >

interface productDetails {
   productId : number , 
   price : number , 
   discount : number
};

const myVar : Record<number, productDetails> = {
   1: {
       productId : number , 
       price : number , 
       discount : number
   }
}

Using global variables in a function

Globals are fine - Except with Multiprocessing

Globals in connection with multiprocessing on different platforms/envrionments as Windows/Mac OS on the one side and Linux on the other are troublesome.

I will show you this with a simple example pointing out a problem which I run into some time ago.

If you want to understand, why things are different on Windows/MacOs and Linux you need to know that, the default mechanism to start a new process on ...

  • Windows/MacOs is 'spawn'
  • Linux is 'fork'

They are different in Memory allocation an initialisation ... (but I don't go into this here).

Let's have a look at the problem/example ...

import multiprocessing

counter = 0

def do(task_id):
    global counter
    counter +=1
    print(f'task {task_id}: counter = {counter}')

if __name__ == '__main__':

    pool = multiprocessing.Pool(processes=4)
    task_ids = list(range(4))
    pool.map(do, task_ids)

Windows

If you run this on Windows (And I suppose on MacOS too), you get the following output ...

task 0: counter = 1
task 1: counter = 2
task 2: counter = 3
task 3: counter = 4

Linux

If you run this on Linux, you get the following instead.

task 0: counter = 1
task 1: counter = 1
task 2: counter = 1
task 3: counter = 1

How to read until end of file (EOF) using BufferedReader in Java?

You are consuming a line at, which is discarded

while((str=input.readLine())!=null && str.length()!=0)

and reading a bigint at

BigInteger n = new BigInteger(input.readLine());

so try getting the bigint from string which is read as

BigInteger n = new BigInteger(str);

   Constructor used: BigInteger(String val)

Aslo change while((str=input.readLine())!=null && str.length()!=0) to

while((str=input.readLine())!=null)

see related post string to bigint

readLine()
Returns:
    A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached 

see javadocs

How to write an inline IF statement in JavaScript?

To add to this you can also use inline if condition with && and || operators. Like this

var a = 2;
var b = 0;

var c = (a > b || b == 0)? "do something" : "do something else";

Remote Linux server to remote linux server dir copy. How?

I like to pipe tar through ssh.

tar cf - [directory] | ssh [username]@[hostname] tar xf - -C [destination on remote box]

This method gives you lots of options. Since you should have root ssh disabled copying files for multiple user accounts is hard since you are logging into the remote server as a normal user. To get around this you can create a tar file on the remote box that still hold that preserves ownership.

tar cf - [directory] | ssh [username]@[hostname] "cat > output.tar"

For slow connections you can add compression, z for gzip or j for bzip2.

tar cjf - [directory] | ssh [username]@[hostname] "cat > output.tar.bz2"

tar czf - [directory] | ssh [username]@[hostname] "cat > output.tar.gz"

tar czf - [directory] | ssh [username]@[hostname] tar xzf - -C [destination on remote box]

String comparison: InvariantCultureIgnoreCase vs OrdinalIgnoreCase?

FXCop typically prefers OrdinalIgnoreCase. But your requirements may vary.

For English there is very little difference. It is when you wander into languages that have different written language constructs that this becomes an issue. I am not experienced enough to give you more than that.

OrdinalIgnoreCase

The StringComparer returned by the OrdinalIgnoreCase property treats the characters in the strings to compare as if they were converted to uppercase using the conventions of the invariant culture, and then performs a simple byte comparison that is independent of language. This is most appropriate when comparing strings that are generated programmatically or when comparing case-insensitive resources such as paths and filenames. http://msdn.microsoft.com/en-us/library/system.stringcomparer.ordinalignorecase.aspx

InvariantCultureIgnoreCase

The StringComparer returned by the InvariantCultureIgnoreCase property compares strings in a linguistically relevant manner that ignores case, but it is not suitable for display in any particular culture. Its major application is to order strings in a way that will be identical across cultures. http://msdn.microsoft.com/en-us/library/system.stringcomparer.invariantcultureignorecase.aspx

The invariant culture is the CultureInfo object returned by the InvariantCulture property.

The InvariantCultureIgnoreCase property actually returns an instance of an anonymous class derived from the StringComparer class.

UIView with rounded corners and drop shadow?

You need to use two UIViews to achieve this. One UIView will work like shadow and other one will work for rounded border.

Here is a code snippet a Class Method with a help of a protocol:

@implementation UIMethods

+ (UIView *)genComposeButton:(UIViewController <UIComposeButtonDelegate> *)observer;
{
    UIView *shadow = [[UIView alloc]init];
    shadow.layer.cornerRadius = 5.0;
    shadow.layer.shadowColor = [[UIColor blackColor] CGColor];
    shadow.layer.shadowOpacity = 1.0;
    shadow.layer.shadowRadius = 10.0;
    shadow.layer.shadowOffset = CGSizeMake(0.0f, -0.5f);

    UIButton *btnCompose = [[UIButton alloc]initWithFrame:CGRectMake(0, 0,60, 60)];
    [btnCompose setUserInteractionEnabled:YES];
    btnCompose.layer.cornerRadius = 30;
    btnCompose.layer.masksToBounds = YES;
    [btnCompose setImage:[UIImage imageNamed:@"60x60"] forState:UIControlStateNormal];
    [btnCompose addTarget:observer action:@selector(btnCompose_click:) forControlEvents:UIControlEventTouchUpInside];
    [shadow addSubview:btnCompose];
    return shadow;
}

In the code above btnCompose_click: will become a @required delegate method which will fire on the button click.

And here I added a button to my UIViewController like this:

UIView *btnCompose = [UIMethods genComposeButton:self];
btnCompose.frame = CGRectMake(self.view.frame.size.width - 75,
                          self.view.frame.size.height - 75,
                          60, 60);
[self.view addSubview:btnCompose];

The result will look like this:

enter image description here

MVC Razor view nested foreach's model

You could add a Category partial and a Product partial, each would take a smaller part of the main model as it's own model, i.e. Category's model type might be an IEnumerable, you would pass in Model.Theme to it. The Product's partial might be an IEnumerable that you pass Model.Products into (from within the Category partial).

I'm not sure if that would be the right way forward, but would be interested in knowing.

EDIT

Since posting this answer, I've used EditorTemplates and find this the easiest way to handle repeating input groups or items. It handles all your validation message problems and form submission/model binding woes automatically.

How can I store JavaScript variable output into a PHP variable?

The ideal method would be to pass it with an AJAX call, but for a quick and dirty method, all you'd have to do is reload the page with this variable in a $_GET parameter -

<script>
  var a="Hello";
  window.location.href = window.location.href+'?a='+a;
</script>

Your page will reload and now in your PHP, you'll have access to the $_GET['a'] variable.

<?php 
  $variable = $_GET['a'];
?>

wamp server does not start: Windows 7, 64Bit

I solved the problem this way:

  • On the orange WAMP icon, click Apache > Service > Test Port 80. Came back with "Port 80 not accessible -- (could be Skype)"
  • Sign out from Skype and close program.
  • Click orange icon and hit Apache > Service > Install Service
  • Click orange icon and hit Apache > Service > Start Service
  • Click orange icon and hit Put Online
  • Icon turns green and service is started and online

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

Change Copy Pods Resources for the target from:

"${SRCROOT}/Pods/Target Support Files/Pods-Wishlist/Pods-Wishlist-resources.sh"

to:

"${SRCROOT}/Pods/Target Support Files/Pods-Wishlist/Pods-Wishlist-frameworks.sh"

Which is better: <script type="text/javascript">...</script> or <script>...</script>

Do you need a type attribute at all? If you're using HTML5, no. Otherwise, yes. HTML 4.01 and XHTML 1.0 specifies the type attribute as required while HTML5 has it as optional, defaulting to text/javascript. HTML5 is now widely implemented, so if you use the HTML5 doctype, <script>...</script> is valid and a good choice.

As to what should go in the type attribute, the MIME type application/javascript registered in 2006 is intended to replace text/javascript and is supported by current versions of all the major browsers (including Internet Explorer 9). A quote from the relevant RFC:

This document thus defines text/javascript and text/ecmascript but marks them as "obsolete". Use of experimental and unregistered media types, as listed in part above, is discouraged. The media types,

  * application/javascript
  * application/ecmascript

which are also defined in this document, are intended for common use and should be used instead.

However, IE up to and including version 8 doesn't execute script inside a <script> element with a type attribute of either application/javascript or application/ecmascript, so if you need to support old IE, you're stuck with text/javascript.

PHP: Count a stdClass object

Count Normal arrya or object

count($object_or_array); 

Count multidimensional arrya or object

count($object_or_array, 1); // 1 for  multidimensional array count, 0 for Default

Link to "pin it" on pinterest without generating a button

For such cases, I found very useful the Share Link Generator, it helps creating Facebook, Google+, Twitter, Pinterest, LinkedIn share buttons.

How can I tell jackson to ignore a property for which I don't have control over the source code?

One other possibility is, if you want to ignore all unknown properties, you can configure the mapper as follows:

mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

How do I get first element rather than using [0] in jQuery?

You can use .get(0) as well but...you shouldn't need to do that with an element found by ID, that should always be unique. I'm hoping this is just an oversight in the example...if this is the case on your actual page, you'll need to fix it so your IDs are unique, and use a class (or another attribute) instead.

.get() (like [0]) gets the DOM element, if you want a jQuery object use .eq(0) or .first() instead :)

how to select rows based on distinct values of A COLUMN only

I am not sure about your DBMS. So, I created a temporary table in Redshift and from my experience, I think this query should return what you are looking for:

select min(Id), distinct MailId, EmailAddress, Name
    from yourTableName
    group by MailId, EmailAddress, Name

I see that I am using a GROUP BY clause but you still won't have two rows against any particular MailId.

Clean out Eclipse workspace metadata

In my case eclipse is not showing parent class function on $this, so I perform below mention points and it starts works:-

I go to my /var/www/ folder and check for .metadata folder (Here check the .log file and it shows) Resource is out of sync with the file system: 1. Go to Eclipse --> Project --> Clean 2. Windows -- preferences --> General --> Workspace --> And set it to "Refresh Automatically"

After that boom - things gets start working :)

If you want to load variables from other files too then ado this :- Eclipse-->Windows-->Preferences-->Php-->Editor-->Content Assist --> and check "show variable from other files"

Then it will show element , variables and other functions also.

Margin on child element moves parent element

add style display:inline-block to child element

All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"?

try this.. i had the same issue, below implementation worked for me

Reader reader = Files.newBufferedReader(Paths.get(<yourfilewithpath>), StandardCharsets.ISO_8859_1);

then use Reader where ever you want.

foreg:

CsvToBean<anyPojo> csvToBean = null;
    try {
        Reader reader = Files.newBufferedReader(Paths.get(csvFilePath), 
                        StandardCharsets.ISO_8859_1);
        csvToBean = new CsvToBeanBuilder(reader)
                .withType(anyPojo.class)
                .withIgnoreLeadingWhiteSpace(true)
                .withSkipLines(1)
                .build();

    } catch (IOException e) {
        e.printStackTrace();
    }

Parse strings to double with comma and point

Use this overload of double.TryParse to specify allowed formats:

Double.TryParse Method (String, NumberStyles, IFormatProvider, Double%)

By default, double.TryParse will parse based on current culture specific formats.

Angularjs - simple form submit

Sending data to some service page.

<form class="form-horizontal" role="form" ng-submit="submit_form()">
    <input type="text" name="user_id" ng-model = "formAdata.user_id">
    <input type="text" id="name" name="name" ng-model = "formAdata.name">
</form>

$scope.submit_form = function()
            {
                $http({
                        url: "http://localhost/services/test.php",
                        method: "POST",
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        data: $.param($scope.formAdata)
                    }).success(function(data, status, headers, config) {
                        $scope.status = status;
                    }).error(function(data, status, headers, config) {
                        $scope.status = status;
                    });
            }

Number of days in particular month of particular year?

String date = "11-02-2000";
String[] input = date.split("-");
int day = Integer.valueOf(input[0]);
int month = Integer.valueOf(input[1]);
int year = Integer.valueOf(input[2]);
Calendar cal=Calendar.getInstance();
cal.set(Calendar.YEAR,year);
cal.set(Calendar.MONTH,month-1);
cal.set(Calendar.DATE, day);
//since month number starts from 0 (i.e jan 0, feb 1), 
//we are subtracting original month by 1
int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println(days);

Starting ssh-agent on Windows 10 fails: "unable to start ssh-agent service, error :1058"

I get the same error in Cygwin. I had to install the openssh package in Cygwin Setup.

(The strange thing was that all ssh-* commands were valid, (bash could execute as program) but the openssh package wasn't installed.)

align right in a table cell with CSS

Don't forget about CSS3's 'nth-child' selector. If you know the index of the column you wish to align text to the right on, you can just specify

table tr td:nth-child(2) {
    text-align: right;
}

In cases with large tables this can save you a lot of extra markup!

here's a fiddle for ya.... https://jsfiddle.net/w16c2nad/

You should not use <Link> outside a <Router>

I was getting this error because I was importing a reusable component from an npm library and the versions of react-router-dom did not match.

So make sure you use the same version in both places!

How do I raise an exception in Rails so it behaves like other Rails exceptions?

You can do it like this:

class UsersController < ApplicationController
  ## Exception Handling
  class NotActivated < StandardError
  end

  rescue_from NotActivated, :with => :not_activated

  def not_activated(exception)
    flash[:notice] = "This user is not activated."
    Event.new_event "Exception: #{exception.message}", current_user, request.remote_ip
    redirect_to "/"
  end

  def show
      // Do something that fails..
      raise NotActivated unless @user.is_activated?
  end
end

What you're doing here is creating a class "NotActivated" that will serve as Exception. Using raise, you can throw "NotActivated" as an Exception. rescue_from is the way of catching an Exception with a specified method (not_activated in this case). Quite a long example, but it should show you how it works.

Best wishes,
Fabian

Remove all html tags from php string

use strip_tags

$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);   //output Test paragraph. Other text

<?php echo substr(strip_tags($row_get_Business['business_description']),0,110) . "..."; ?>

Where to place JavaScript in an HTML file?

Putting the javascript at the top would seem neater, but functionally, its better to go after the HTML. That way, your javascript won't run and try to reference HTML elements before they are loaded. This sort of problem often only becomes apparent when you load the page over an actual internet connection, especially a slow one.

You could also try to dynamically load the javascript by adding a header element from other javascript code, although that only makes sense if you aren't using all of the code all the time.

PostgreSQL naming conventions

There isn't really a formal manual, because there's no single style or standard.

So long as you understand the rules of identifier naming you can use whatever you like.

In practice, I find it easier to use lower_case_underscore_separated_identifiers because it isn't necessary to "Double Quote" them everywhere to preserve case, spaces, etc.

If you wanted to name your tables and functions "@MyA??! ""betty"" Shard$42" you'd be free to do that, though it'd be pain to type everywhere.

The main things to understand are:

  • Unless double-quoted, identifiers are case-folded to lower-case, so MyTable, MYTABLE and mytable are all the same thing, but "MYTABLE" and "MyTable" are different;

  • Unless double-quoted:

    SQL identifiers and key words must begin with a letter (a-z, but also letters with diacritical marks and non-Latin letters) or an underscore (_). Subsequent characters in an identifier or key word can be letters, underscores, digits (0-9), or dollar signs ($).

  • You must double-quote keywords if you wish to use them as identifiers.

In practice I strongly recommend that you do not use keywords as identifiers. At least avoid reserved words. Just because you can name a table "with" doesn't mean you should.

Python: download a file from an FTP server

If you want to take advantage of recent Python versions' async features, you can use aioftp (from the same family of libraries and developers as the more popular aiohttp library). Here is a code example taken from their client tutorial:

client = aioftp.Client()
await client.connect("ftp.server.com")
await client.login("user", "pass")
await client.download("tmp/test.py", "foo.py", write_into=True)

Deploying Maven project throws java.util.zip.ZipException: invalid LOC header (bad signature)

Looks like problem of configuration for maven compiler in your pom file. Default version java source and target is 1.5, even used JDK has higher version.

To fix, add maven compiler plugin configuration section with higher java version, example:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>3.6.1</version>
  <configuration>
    <source>1.6</source>
    <target>1.6</target>
  </configuration>
</plugin>

For more info check these links:

maven compiler

bug report

Load local images in React.js

Best approach is to import image in js file and use it. Adding images in public folder have some downside:

  • Files inside public folder not get minified or post-processed,

  • You can't use hashed name (need to set in webpack config) for images , if you do then you have to change names again and again,

  • Can't find files at runtime (compilation), result in 404 error at client side.

How to set the custom border color of UIView programmatically?

We can create method for it. Simply use it.

public func createBorderForView(color: UIColor, radius: CGFloat, width: CGFloat = 0.7) {
    self.layer.borderWidth = width
    self.layer.cornerRadius = radius
    self.layer.shouldRasterize = false
    self.layer.rasterizationScale = 2
    self.clipsToBounds = true
    self.layer.masksToBounds = true
    let cgColor: CGColor = color.cgColor
    self.layer.borderColor = cgColor
}

Android ListView Text Color

I cloned the simple_list_item_1(Alt + Click) and placed the copy on my res/layout folder, renamed it to list_white_text.xml with this contents:

<?xml version="1.0" encoding="utf-8"?>    
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:gravity="center_vertical"
    android:textColor="@color/abc_primary_text_material_dark"
    android:minHeight="?android:attr/listPreferredItemHeightSmall" />

The android:textColor="@color/abc_primary_text_material_dark" translates to white on my device.

then in the java code:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_white_text, myList);

Use :hover to modify the css of another class?

It's not possible in CSS at the moment, unless you want to select a child or sibling element (trivial and described in other answers here).

For all other cases you'll need JavaScript. jQuery and frameworks like Angular can tackle this problem with relative ease.

[Edit]

With the new CSS (4) selector :has(), you'll be able to target parent elements/classes, making a CSS-Only solution viable in the near future!

How to rename a file using Python

If you are Using Windows and you want to rename your 1000s of files in a folder then: You can use the below code. (Python3)

import os

path = os.chdir(input("Enter the path of the Your Image Folder :  ")) #Here put the path of your folder where your images are stored

image_name = input("Enter your Image name : ") #Here, enter the name you want your images to have

i = 0

for file in os.listdir(path):

    new_file_name = image_name+"_" + str(i) + ".jpg" #here you can change the extention of your renmamed file.
    os.rename(file,new_file_name)

    i = i + 1

input("Renamed all Images!!")

CSS Margin: 0 is not setting to 0

After reading this and troubleshooting the same issues, I agree that it is related to headings (h1 for sure, havent played with any others), also browser styles adding margins and paddings with clever rules that are hard to find and over-ride.

I have adapted a technique used to apply the box-sizing property properly to margins and paddings. the original article for box-sizing is located at CSS-Tricks :

html {
margin: 0;
padding: 0;
}
*, *:before, *:after {
margin: inherit;
padding: inherit;
}

So far it is exactly the trick for not using complex resets and makes applying a design much easier for myself anyways. Hope it helps.

What is the use of "using namespace std"?

When you make a call to using namespace <some_namespace>; all symbols in that namespace will become visible without adding the namespace prefix. A symbol may be for instance a function, class or a variable.

E.g. if you add using namespace std; you can write just cout instead of std::cout when calling the operator cout defined in the namespace std.

This is somewhat dangerous because namespaces are meant to be used to avoid name collisions and by writing using namespace you spare some code, but loose this advantage. A better alternative is to use just specific symbols thus making them visible without the namespace prefix. Eg:

#include <iostream>
using std::cout;

int main() {
  cout << "Hello world!";
  return 0;
}

MySQL error #1054 - Unknown column in 'Field List'

You have an error in your OrderQuantity column. It is named "OrderQuantity" in the INSERT statement and "OrderQantity" in the table definition.

Also, I don't think you can use NOW() as default value in OrderDate. Try to use the following:

 OrderDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP

Example Fiddle

How to solve "Connection reset by peer: socket write error"?

It seems like your problem may be arising at

while(in.read(outputByte,0,4096)!=-1){

where it might go into an infinite loop for not advancing the offset (which is 0 always in the call). Try

while(in.read(outputByte)!=-1){

which will by default try to read upto outputByte.length into the byte[]. This way you dont have to worry about the offset. See FileInputStrem's read method

Adding elements to object

This is an old question, anyway today the best practice is by using Object.defineProperty

const object1 = {};

Object.defineProperty(object1, 'property1', {
  value: 42,
  writable: false
});

object1.property1 = 77;
// throws an error in strict mode

console.log(object1.property1);
// expected output: 42

Change Circle color of radio button

@jh314 is correct. In AndroidManifest.xml,

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

In style.xml

  <!-- Application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorAccent">@color/red</item>
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>

the item name must be colorAccent,it decides the application's widgets default color.

But if you want to change the color in code,Maybe @aknay's answer is correct.

How to skip a iteration/loop in while-loop

While you could use a continue, why not just inverse the logic in your if?

while(rs.next())
{
    if(!f.exists() || f.isDirectory()){
    //proceed
    }
}

You don't even need an else {continue;} as it will continue anyway if the if conditions are not satisfied.

Error inflating class android.support.design.widget.NavigationView

I was also having this same issue, after looking nearly 3 hours I find out that the problem was in my drawable_menu.xml file, it was wrongly written :D

Escape Character in SQL Server

You need to just replace ' with '' inside your string

SELECT colA, colB, colC
FROM tableD
WHERE colA = 'John''s Mobile'

You can also use REPLACE(@name, '''', '''''') if generating the SQL dynamically

If you want to escape inside a like statement then you need to use the ESCAPE syntax

It's also worth mentioning that you're leaving yourself open to SQL injection attacks if you don't consider it. More info at Google or: http://it.toolbox.com/wiki/index.php/How_do_I_escape_single_quotes_in_SQL_queries%3F

Print Combining Strings and Numbers

Yes there is. The preferred syntax is to favor str.format over the deprecated % operator.

print "First number is {} and second number is {}".format(first, second)

Change a column type from Date to DateTime during ROR migration

Also, if you're using Rails 3 or newer you don't have to use the up and down methods. You can just use change:

class ChangeFormatInMyTable < ActiveRecord::Migration
  def change
    change_column :my_table, :my_column, :my_new_type
  end
end

In Maven how to exclude resources from the generated jar?

When I create an executable jar with dependencies (using this guide), all properties files are packaged into that jar too. How to stop it from happening? Thanks.

Properties files from where? Your main jar? Dependencies?

In the former case, putting resources under src/test/resources as suggested is probably the most straight forward and simplest option.

In the later case, you'll have to create a custom assembly descriptor with special excludes/exclude in the unpackOptions.

How to make jQuery UI nav menu horizontal?

changing:

.ui-menu .ui-menu-item { 
    margin: 0; 
    padding: 0; 
    zoom: 1; 
    width: 100%; 
}

to:

.ui-menu .ui-menu-item { 
    margin: 0; 
    padding: 0; 
    zoom: 1; 
    width: auto; 
    float:left; 
 }

should start you off.

Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

See if you can recreate the issue in an Incognito tab. If you find that the problem no longer occurs then I would recommend you go through your extensions, perhaps disabling them one at a time. This is commonly the cause as touched on by Nikola

Changing iframe src with Javascript

This should also work, although the src will remain intact:

document.getElementById("myIFrame").contentWindow.document.location.href="http://myLink.com";

How do I see what character set a MySQL database / table / column is?

Here's how I'd do it -

For Schemas (or Databases - they are synonyms):

SELECT default_character_set_name FROM information_schema.SCHEMATA 
WHERE schema_name = "schemaname";

For Tables:

SELECT CCSA.character_set_name FROM information_schema.`TABLES` T,
       information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA
WHERE CCSA.collation_name = T.table_collation
  AND T.table_schema = "schemaname"
  AND T.table_name = "tablename";

For Columns:

SELECT character_set_name FROM information_schema.`COLUMNS` 
WHERE table_schema = "schemaname"
  AND table_name = "tablename"
  AND column_name = "columnname";

Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded

Only changing the settings with the following command did not work in my environment:

curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'

I had to also ran the Force Merge API command:

curl -X POST "localhost:9200/my-index-000001/_forcemerge?pretty"

ref: Force Merge API

'mat-form-field' is not a known element - Angular 5 & Material2

Check the namespace from where we are importing

import { MatDialogModule } from **"@angular/material/dialog";**
import { MatCardModule } from **"@angular/material/card";**
import { MatButtonModule } from **"@angular/material/button";**

How to Validate a DateTime in C#?

    protected bool ValidateBirthday(String date)
    {
        DateTime Temp;

        if (DateTime.TryParse(date, out Temp) == true &&
      Temp.Hour == 0 &&
      Temp.Minute == 0 &&
      Temp.Second == 0 &&
      Temp.Millisecond == 0 &&
      Temp > DateTime.MinValue)
            return true;
        else
            return false;
    }

//suppose that input string is short date format.
e.g. "2013/7/5" returns true or
"2013/2/31" returns false.
http://forums.asp.net/t/1250332.aspx/1
//bool booleanValue = ValidateBirthday("12:55"); returns false

Cannot catch toolbar home button click event

This is how I do it to return to the right fragment otherwise if you have several fragments on the same level it would return to the first one if you don´t override the toolbar back button behavior.

toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            finish();
        }
    });

How do I find which program is using port 80 in Windows?

Start menu → Accessories → right click on "Command prompt". In the menu, click "Run as Administrator" (on Windows XP you can just run it as usual), run netstat -anb, and then look through output for your program.

BTW, Skype by default tries to use ports 80 and 443 for incoming connections.

You can also run netstat -anb >%USERPROFILE%\ports.txt followed by start %USERPROFILE%\ports.txt to open the port and process list in a text editor, where you can search for the information you want.

You can also use PowerShell to parse netstat output and present it in a better way (or process it any way you want):

$proc = @{};
Get-Process | ForEach-Object { $proc.Add($_.Id, $_) };
netstat -aon | Select-String "\s*([^\s]+)\s+([^\s]+):([^\s]+)\s+([^\s]+):([^\s]+)\s+([^\s]+)?\s+([^\s]+)" | ForEach-Object {
    $g = $_.Matches[0].Groups;
    New-Object PSObject |
        Add-Member @{ Protocol =           $g[1].Value  } -PassThru |
        Add-Member @{ LocalAddress =       $g[2].Value  } -PassThru |
        Add-Member @{ LocalPort =     [int]$g[3].Value  } -PassThru |
        Add-Member @{ RemoteAddress =      $g[4].Value  } -PassThru |
        Add-Member @{ RemotePort =         $g[5].Value  } -PassThru |
        Add-Member @{ State =              $g[6].Value  } -PassThru |
        Add-Member @{ PID =           [int]$g[7].Value  } -PassThru |
        Add-Member @{ Process = $proc[[int]$g[7].Value] } -PassThru;
#} | Format-Table Protocol,LocalAddress,LocalPort,RemoteAddress,RemotePort,State -GroupBy @{Name='Process';Expression={$p=$_.Process;@{$True=$p.ProcessName; $False=$p.MainModule.FileName}[$p.MainModule -eq $Null] + ' PID: ' + $p.Id}} -AutoSize
} | Sort-Object PID | Out-GridView

Also it does not require elevation to run.

What is difference between XML Schema and DTD?

DTD is pretty much deprecated because it is limited in its usefulness as a schema language, doesn't support namespace, and does not support data type. In addition, DTD's syntax is quite complicated, making it difficult to understand and maintain..

How to get an element by its href in jquery?

var myElement = $("a[href='http://www.stackoverflow.com']");

http://api.jquery.com/attribute-equals-selector/

Extract elements of list at odd positions

I like List comprehensions because of their Math (Set) syntax. So how about this:

L = [1, 2, 3, 4, 5, 6, 7]
odd_numbers = [y for x,y in enumerate(L) if x%2 != 0]
even_numbers = [y for x,y in enumerate(L) if x%2 == 0]

Basically, if you enumerate over a list, you'll get the index x and the value y. What I'm doing here is putting the value y into the output list (even or odd) and using the index x to find out if that point is odd (x%2 != 0).

javax.naming.NameNotFoundException: Name is not bound in this Context. Unable to find

ugh, just to iterate over my own case, which gave out approximately the same error - in the Resource declaration (server.xml) make sure to NOT omit driverClassName, and that e.g. for Oracle it is "oracle.jdbc.OracleDriver", and that the right JAR file (e.g. ojdbc14.jar) exists in %CATALINA_HOME%/lib

Store output of subprocess.Popen call in a string

In Python 2.7 or Python 3

Instead of making a Popen object directly, you can use the subprocess.check_output() function to store output of a command in a string:

from subprocess import check_output
out = check_output(["ntpq", "-p"])

In Python 2.4-2.6

Use the communicate method.

import subprocess
p = subprocess.Popen(["ntpq", "-p"], stdout=subprocess.PIPE)
out, err = p.communicate()

out is what you want.

Important note about the other answers

Note how I passed in the command. The "ntpq -p" example brings up another matter. Since Popen does not invoke the shell, you would use a list of the command and options—["ntpq", "-p"].

How to create named and latest tag in Docker?

Variation of Aaron's answer. Using sed without temporary files

#!/bin/bash
VERSION=1.0.0
IMAGE=company/image
ID=$(docker build  -t ${IMAGE}  .  | tail -1 | sed 's/.*Successfully built \(.*\)$/\1/')

docker tag ${ID} ${IMAGE}:${VERSION}
docker tag -f ${ID} ${IMAGE}:latest

Solution for "Fatal error: Maximum function nesting level of '100' reached, aborting!" in PHP

Rather than going for a recursive function calls, work with a queue model to flatten the structure.

$queue = array('http://example.com/first/url');
while (count($queue)) {
    $url = array_shift($queue);

    $queue = array_merge($queue, find_urls($url));
}

function find_urls($url)
{
    $urls = array();

    // Some logic filling the variable

    return $urls;
}

There are different ways to handle it. You can keep track of more information if you need some insight about the origin or paths traversed. There are also distributed queues that can work off a similar model.