Programs & Examples On #Sqlbuilder

Is there any good dynamic SQL builder library in Java?

You can use the following library:

https://github.com/pnowy/NativeCriteria

The library is built on the top of the Hibernate "create sql query" so it supports all databases supported by Hibernate (the Hibernate session and JPA providers are supported). The builder patter is available and so on (object mappers, result mappers).

You can find the examples on github page, the library is available at Maven central of course.

NativeCriteria c = new NativeCriteria(new HibernateQueryProvider(hibernateSession), "table_name", "alias");
c.addJoin(NativeExps.innerJoin("table_name_to_join", "alias2", "alias.left_column", "alias2.right_column"));
c.setProjection(NativeExps.projection().addProjection(Lists.newArrayList("alias.table_column","alias2.table_column")));

How can you check for a #hash in a URL using JavaScript?

Here is a simple function that returns true or false (has / doesn't have a hashtag):

var urlToCheck = 'http://www.domain.com/#hashtag';

function hasHashtag(url) {
    return (url.indexOf("#") != -1) ? true : false;
}

// Condition
if(hasHashtag(urlToCheck)) {
    // Do something if has
}
else {
    // Do something if doesn't
}

Returns true in this case.

Based on @jon-skeet's comment.

Remove all elements contained in another array

var myArray = [
  {name: 'deepak', place: 'bangalore'}, 
  {name: 'chirag', place: 'bangalore'}, 
  {name: 'alok', place: 'berhampur'}, 
  {name: 'chandan', place: 'mumbai'}
];
var toRemove = [
  {name: 'deepak', place: 'bangalore'},
  {name: 'alok', place: 'berhampur'}
];



myArray = myArray.filter(ar => !toRemove.find(rm => (rm.name === ar.name && ar.place === rm.place) ))

Specifying colClasses in the read.csv

If you want to refer to names from the header rather than column numbers, you can use something like this:

fname <- "test.csv"
headset <- read.csv(fname, header = TRUE, nrows = 10)
classes <- sapply(headset, class)
classes[names(classes) %in% c("time")] <- "character"
dataset <- read.csv(fname, header = TRUE, colClasses = classes)

How can I update NodeJS and NPM to the next versions?

Install npm => sudo apt-get install npm

Install n => sudo npm install n -g

latest version of node => sudo n latest

Specific version of node you can

List available node versions => n ls

Install a specific version => sudo n 4.5.0

Use string value from a cell to access worksheet of same name

You can use the formula INDIRECT().

This basically takes a string and treats it as a reference. In your case, you would use:

=INDIRECT("'"&A5&"'!G7")

The double quotes are to show that what's inside are strings, and only A5 here is a reference.

How to set image to UIImage

may be:

UIImage *img = [[UIImage alloc] init];

and when you want to change the image:

img = [UIImage imageNamed:@"nameOfPng.png"];

but the object wasn't in the same place in the memory, but if you use the pointer, the same pointer will be point to the last image loaded.

Select all DIV text with single mouse click

This snippet provides the functionality you require. What you need to do is add an event to that div that which activates fnSelect in it. A quick hack that you totally shouldn't do and possibly might not work, would look like this:

document.getElementById("selectable").onclick(function(){
    fnSelect("selectable");
});

Obviously assuming that the linked to snippet had been included.

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

Perhaps it is indirect to gdb (because it's an IDE), but my recommendations would be KDevelop. Being quite spoiled with Visual Studio's debugger (professionally at work for many years), I've so far felt the most comfortable debugging in KDevelop (as hobby at home, because I could not afford Visual Studio for personal use - until Express Edition came out). It does "look something similar to" Visual Studio compared to other IDE's I've experimented with (including Eclipse CDT) when it comes to debugging step-through, step-in, etc (placing break points is a bit awkward because I don't like to use mouse too much when coding, but it's not difficult).

Node.js: socket.io close client connection

Just try socket.disconnect(true) on the server side by emitting any event from the client side.

change the date format in laravel view page

Sometimes changing the date format doesn't work properly, especially in Laravel. So in that case, it's better to use:

$date1 = strtr($_REQUEST['date'], '/', '-');
echo date('Y-m-d', strtotime($date1));

Then you can avoid error like "1970-01-01"!

How to change indentation in Visual Studio Code?

Setting the indentation in preferences isn't allways the solution. Most of the time the indentation is right except you happen to copy some code code from other sources or your collegue make something for you and has different settings. Then you want to just quickly convert the indentation from 2 to 4 or the other way round.

That's what this vscode extension is doing for you

enter image description here

Reading/Writing a MS Word file in PHP

2007 might be a bit complicated as well.

The .docx format is a zip file that contains a few folders with other files in them for formatting and other stuff.

Rename a .docx file to .zip and you'll see what I mean.

So if you can work within zip files in PHP, you should be on the right path.

What is the behavior difference between return-path, reply-to and from?

for those who got here because the title of the question:

I use Reply-To: address with webforms. when someone fills out the form, the webpage sends an automatic email to the page's owner. the From: is the automatic mail sender's address, so the owner knows it is from the webform. but the Reply-To: address is the one filled in in the form by the user, so the owner can just hit reply to contact them.

Using G++ to compile multiple .cpp and .h files

To compile separately without linking you need to add -c option:

g++ -c myclass.cpp
g++ -c main.cpp
g++ myclass.o main.o
./a.out

Index inside map() function

  • suppose you have an array like

_x000D_
_x000D_
   const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    
    arr.map((myArr, index) => {
      console.log(`your index is -> ${index} AND value is ${myArr}`);
    })
_x000D_
_x000D_
_x000D_

> output will be
 index is -> 0 AND value is 1
 index is -> 1 AND value is 2
 index is -> 2 AND value is 3
 index is -> 3 AND value is 4
 index is -> 4 AND value is 5
 index is -> 5 AND value is 6
 index is -> 6 AND value is 7
 index is -> 7 AND value is 8
 index is -> 8 AND value is 9

Removing items from a ListBox in VB.net

This worked for me.

Private Sub listbox_MouseDoubleClick(sender As Object, e As MouseEventArgs) 
        Handles listbox.MouseDoubleClick
        listbox.Items.RemoveAt(listbox.SelectedIndex.ToString())
    End Sub

How to align flexbox columns left and right?

You could add justify-content: space-between to the parent element. In doing so, the children flexbox items will be aligned to opposite sides with space between them.

Updated Example

#container {
    width: 500px;
    border: solid 1px #000;
    display: flex;
    justify-content: space-between;
}

_x000D_
_x000D_
#container {_x000D_
    width: 500px;_x000D_
    border: solid 1px #000;_x000D_
    display: flex;_x000D_
    justify-content: space-between;_x000D_
}_x000D_
_x000D_
#a {_x000D_
    width: 20%;_x000D_
    border: solid 1px #000;_x000D_
}_x000D_
_x000D_
#b {_x000D_
    width: 20%;_x000D_
    border: solid 1px #000;_x000D_
    height: 200px;_x000D_
}
_x000D_
<div id="container">_x000D_
    <div id="a">_x000D_
        a_x000D_
    </div>_x000D_
    <div id="b">_x000D_
        b_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


You could also add margin-left: auto to the second element in order to align it to the right.

Updated Example

#b {
    width: 20%;
    border: solid 1px #000;
    height: 200px;
    margin-left: auto;
}

_x000D_
_x000D_
#container {_x000D_
    width: 500px;_x000D_
    border: solid 1px #000;_x000D_
    display: flex;_x000D_
}_x000D_
_x000D_
#a {_x000D_
    width: 20%;_x000D_
    border: solid 1px #000;_x000D_
    margin-right: auto;_x000D_
}_x000D_
_x000D_
#b {_x000D_
    width: 20%;_x000D_
    border: solid 1px #000;_x000D_
    height: 200px;_x000D_
    margin-left: auto;_x000D_
}
_x000D_
<div id="container">_x000D_
    <div id="a">_x000D_
        a_x000D_
    </div>_x000D_
    <div id="b">_x000D_
        b_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Installing SciPy with pip

In my case, it wasn't working until I also installed the following package : libatlas-base-dev, gfortran

 sudo apt-get install libatlas-base-dev gfortran

Then run pip install scipy

Install MySQL on Ubuntu without a password prompt

This should do the trick

export DEBIAN_FRONTEND=noninteractive
sudo -E apt-get -q -y install mysql-server

Of course, it leaves you with a blank root password - so you'll want to run something like

mysqladmin -u root password mysecretpasswordgoeshere

Afterwards to add a password to the account.

SQL Server Case Statement when IS NULL

You can use IIF (I think from SQL Server 2012)

SELECT IIF(B.[STAT] IS NULL, C.[EVENT DATE]+10, '-') AS [DATE]

How to get store information in Magento?

In Magento 1.9.4.0 and maybe all versions in 1.x use:

Mage::getStoreConfig('general/store_information/address');

and the following params, it depends what you want to get:

  • general/store_information/name
  • general/store_information/phone
  • general/store_information/merchant_country
  • general/store_information/address
  • general/store_information/merchant_vat_number

How To have Dynamic SQL in MySQL Stored Procedure

After 5.0.13, in stored procedures, you can use dynamic SQL:

delimiter // 
CREATE PROCEDURE dynamic(IN tbl CHAR(64), IN col CHAR(64))
BEGIN
    SET @s = CONCAT('SELECT ',col,' FROM ',tbl );
    PREPARE stmt FROM @s;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END
//
delimiter ;

Dynamic SQL does not work in functions or triggers. See the MySQL documentation for more uses.

Windows batch command(s) to read first line from text file

Note, the batch file approaches will be limited to the line limit for the DOS command processor - see What is the command line length limit?.

So if trying to process a file that has any lines more that 8192 characters the script will just skip them as the value can't be held.

How Best to Compare Two Collections in Java and Act on Them?

I think the easiest way to do that is by using apache collections api - CollectionUtils.subtract(list1,list2) as long the lists are of the same type.

PostgreSQL: Why psql can't connect to server?

Solved it! Although I don't know what happened, but I just deleted all the stuff and reinstalled it. This is the command I used to delete it sudo apt-get --purge remove postgresql\* and dpkg -l | grep postgres. The latter one is to find all the packets in case it is not clean.

How to hide reference counts in VS2013?

Workaround....

In VS 2015 Professional (and probably other versions). Go to Tools / Options / Environment / Fonts and Colours. In the "Show Settings For" drop-down, select "CodeLens" Choose the smallest font you can find e.g. Calibri 6. Change the foreground colour to your editor foreground colour (say "White") Click OK.

Is it possible to start activity through adb shell?

I run it like AndroidStudio does:

am start -n "com.example.app.dev/com.example.app.phonebook.PhoneBookActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER

If you have product flavour like dev, it should occur only in application package name but shouldn't occur in activity package name.

For emulator, it works without android:exported="true" flag on activity in AndroidManifest.xml but I found it useful to add it for unrooted physical device to make it work.

For a boolean field, what is the naming convention for its getter/setter?

http://geosoft.no/development/javastyle.html#Specific

  1. is prefix should be used for boolean variables and methods.

    isSet, isVisible, isFinished, isFound, isOpen

This is the naming convention for boolean methods and variables used by Sun for the Java core packages. Using the is prefix solves a common problem of choosing bad boolean names like status or flag. isStatus or isFlag simply doesn't fit, and the programmer is forced to chose more meaningful names.

Setter methods for boolean variables must have set prefix as in:

void setFound(boolean isFound);

There are a few alternatives to the is prefix that fits better in some situations. These are has, can and should prefixes:

boolean hasLicense(); 
boolean canEvaluate(); 
boolean shouldAbort = false;

HTML form action and onsubmit issues

You should stop the submit procedure by returning false on the onsubmit callback.

<script>
    function checkRegistration(){
        if(!form_valid){
            alert('Given data is not correct');
            return false;
        }
        return true;
    }
</script>

<form onsubmit="return checkRegistration()"...

Here you have a fully working example. The form will submit only when you write google into input, otherwise it will return an error:

<script>
    function checkRegistration(){
        var form_valid = (document.getElementById('some_input').value == 'google');
        if(!form_valid){
            alert('Given data is incorrect');
            return false;
        }
        return true;
    }
</script>

<form onsubmit="return checkRegistration()" method="get" action="http://google.com">
    Write google to go to google...<br/>
    <input type="text" id="some_input" value=""/>
    <input type="submit" value="google it"/>
</form>

Calling a function in jQuery with click()

$("#closeLink").click(closeIt);

Let's say you want to call your function passing some args to it i.e., closeIt(1, false). Then, you should build an anonymous function and call closeIt from it.

$("#closeLink").click(function() {
    closeIt(1, false);
});

Checking letter case (Upper/Lower) within a string in Java

package passwordValidator;

import java.util.Scanner;

public class Main {
    /**
     * @author felipe mello.
     */

    private static Scanner scanner = new Scanner(System.in);

     /*
     * Create a password validator(from an input string) via TDD
     * The validator should return true if
     *  The Password is at least 8 characters long
     *  The Password contains uppercase Letters(atLeastOne)
     *  The Password contains digits(at least one)
     *  The Password contains symbols(at least one)
     */


    public static void main(String[] args) {
        System.out.println("Please enter a password");
        String password = scanner.nextLine();   

        checkPassword(password);
    }
    /**
     * 
     * @param checkPassword the method check password is validating the input from the the user and check if it matches the password requirements
     * @return
     */
    public static boolean checkPassword(String password){
        boolean upperCase = !password.equals(password.toLowerCase()); //check if the input has a lower case letter
        boolean lowerCase = !password.equals(password.toUpperCase()); //check if the input has a CAPITAL case letter
        boolean isAtLeast8 = password.length()>=8;                    //check if the input is greater than 8 characters
        boolean hasSpecial = !password.matches("[A-Za-z0-9]*");       // check if the input has a special characters
        boolean hasNumber = !password.matches(".*\\d+.*");            //check if the input contains a digit
        if(!isAtLeast8){
            System.out.println("Your Password is not big enough\n please enter a password with minimun of 8 characters");
            return true;
        }else if(!upperCase){
            System.out.println("Password must contain at least one UPPERCASE letter");
            return true;
        }else if(!lowerCase){
            System.out.println("Password must contain at least one lower case letter");
            return true;
        }else if(!hasSpecial){
            System.out.println("Password must contain a special character");
            return true;
        }else if(hasNumber){
            System.out.println("Password must contain at least one number");
            return true;
        }else{
            System.out.println("Your password: "+password+", sucessfully match the requirements");
            return true;
        }

    }
}

What's the difference between session.persist() and session.save() in Hibernate?

I have done good research on the save() vs. persist() including running it on my local machine several times. All the previous explanations are confusing and incorrect. I compare save() and persist() methods below after a thorough research.

Save()

  1. Returns generated Id after saving. Its return type is Serializable;
  2. Saves the changes to the database outside of the transaction;
  3. Assigns the generated id to the entity you are persisting;
  4. session.save() for a detached object will create a new row in the table.

Persist()

  1. Does not return generated Id after saving. Its return type is void;
  2. Does not save the changes to the database outside of the transaction;
  3. Assigns the generated Id to the entity you are persisting;
  4. session.persist() for a detached object will throw a PersistentObjectException, as it is not allowed.

All these are tried/tested on Hibernate v4.0.1.

XML to CSV Using XSLT

This xsl:stylesheet can use a specified list of column headers and will ensure that the rows will be ordered correctly.

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:csv="csv:csv">
    <xsl:output method="text" encoding="utf-8" />
    <xsl:strip-space elements="*" />

    <xsl:variable name="delimiter" select="','" />

    <csv:columns>
        <column>name</column>
        <column>sublease</column>
        <column>addressBookID</column>
        <column>boundAmount</column>
        <column>rentalAmount</column>
        <column>rentalPeriod</column>
        <column>rentalBillingCycle</column>
        <column>tenureIncome</column>
        <column>tenureBalance</column>
        <column>totalIncome</column>
        <column>balance</column>
        <column>available</column>
    </csv:columns>

    <xsl:template match="/property-manager/properties">
        <!-- Output the CSV header -->
        <xsl:for-each select="document('')/*/csv:columns/*">
                <xsl:value-of select="."/>
                <xsl:if test="position() != last()">
                    <xsl:value-of select="$delimiter"/>
                </xsl:if>
        </xsl:for-each>
        <xsl:text>&#xa;</xsl:text>

        <!-- Output rows for each matched property -->
        <xsl:apply-templates select="property" />
    </xsl:template>

    <xsl:template match="property">
        <xsl:variable name="property" select="." />

        <!-- Loop through the columns in order -->
        <xsl:for-each select="document('')/*/csv:columns/*">
            <!-- Extract the column name and value -->
            <xsl:variable name="column" select="." />
            <xsl:variable name="value" select="$property/*[name() = $column]" />

            <!-- Quote the value if required -->
            <xsl:choose>
                <xsl:when test="contains($value, '&quot;')">
                    <xsl:variable name="x" select="replace($value, '&quot;',  '&quot;&quot;')"/>
                    <xsl:value-of select="concat('&quot;', $x, '&quot;')"/>
                </xsl:when>
                <xsl:when test="contains($value, $delimiter)">
                    <xsl:value-of select="concat('&quot;', $value, '&quot;')"/>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:value-of select="$value"/>
                </xsl:otherwise>
            </xsl:choose>

            <!-- Add the delimiter unless we are the last expression -->
            <xsl:if test="position() != last()">
                <xsl:value-of select="$delimiter"/>
            </xsl:if>
        </xsl:for-each>

        <!-- Add a newline at the end of the record -->
        <xsl:text>&#xa;</xsl:text>
    </xsl:template>

</xsl:stylesheet>

Is iterating ConcurrentHashMap values thread safe?

What does it mean?

It means that you should not try to use the same iterator in two threads. If you have two threads that need to iterate over the keys, values or entries, then they each should create and use their own iterators.

What happens if I try to iterate the map with two threads at the same time?

It is not entirely clear what would happen if you broke this rule. You could just get confusing behavior, in the same way that you do if (for example) two threads try to read from standard input without synchronizing. You could also get non-thread-safe behavior.

But if the two threads used different iterators, you should be fine.

What happens if I put or remove a value from the map while iterating it?

That's a separate issue, but the javadoc section that you quoted adequately answers it. Basically, the iterators are thread-safe, but it is not defined whether you will see the effects of any concurrent insertions, updates or deletions reflected in the sequence of objects returned by the iterator. In practice, it probably depends on where in the map the updates occur.

Leave menu bar fixed on top when scrolled

try with sticky jquery plugin

https://github.com/garand/sticky

_x000D_
_x000D_
<script src="jquery.js"></script>_x000D_
<script src="jquery.sticky.js"></script>_x000D_
<script>_x000D_
  $(document).ready(function(){_x000D_
    $("#sticker").sticky({topSpacing:0});_x000D_
  });_x000D_
</script>
_x000D_
_x000D_
_x000D_

Bootstrap Modal sitting behind backdrop

I was fighting with the same problem some days... I found three posible solutions, but i dont know, which is the most optimal, if somebody tell me, i will be grateful.

the modifications will be in bootstrap.css

Option 1:

.modal-backdrop {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1040; <- DELETE THIS LINE
  background-color: #000000;
}

Option 2:

.modal-backdrop {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: -1; <- MODIFY THIS VALUE BY -1
  background-color: #000000;
}

Option 3:

/*ADD THIS*/
.modal-backdrop.fade.in {
    z-index: -1;
}

I used the option 2.

C++ STL Vectors: Get iterator from index?

Also; auto it = std::next(v.begin(), index);

Update: Needs a C++11x compliant compiler

Get all directories within directory nodejs

This answer does not use blocking functions like readdirSync or statSync. It does not use external dependencies nor find itself in the depths of callback hell.

Instead we use modern JavaScript conveniences like Promises and and async-await syntaxes. And asynchronous results are processed in parallel; not sequentially -

const { readdir, stat } =
  require ("fs") .promises

const { join } =
  require ("path")

const dirs = async (path = ".") =>
  (await stat (path)) .isDirectory ()
    ? Promise
        .all
          ( (await readdir (path))
              .map (p => dirs (join (path, p)))
          )
        .then
          ( results =>
              [] .concat (path, ...results)
          )
    : []

I'll install an example package, and then test our function -

$ npm install ramda
$ node

Let's see it work -

> dirs (".") .then (console.log, console.error)

[ '.'
, 'node_modules'
, 'node_modules/ramda'
, 'node_modules/ramda/dist'
, 'node_modules/ramda/es'
, 'node_modules/ramda/es/internal'
, 'node_modules/ramda/src'
, 'node_modules/ramda/src/internal'
]

Using a generalised module, Parallel, we can simplify the definition of dirs -

const Parallel =
  require ("./Parallel")

const dirs = async (path = ".") =>
  (await stat (path)) .isDirectory ()
    ? Parallel (readdir (path))
        .flatMap (f => dirs (join (path, f)))
        .then (results => [ path, ...results ])
    : []

The Parallel module used above was a pattern that was extracted from a set of functions designed to solve a similar problem. For more explanation, see this related Q&A.

How to use Typescript with native ES6 Promises

This the most recent way to do this, the above answer is outdated:

typings install --global es6-promise

Android: ListView elements with multiple clickable buttons

This is sort of an appendage @znq's answer...

There are many cases where you want to know the row position for a clicked item AND you want to know which view in the row was tapped. This is going to be a lot more important in tablet UIs.

You can do this with the following custom adapter:

private static class CustomCursorAdapter extends CursorAdapter {

    protected ListView mListView;

    protected static class RowViewHolder {
        public TextView mTitle;
        public TextView mText;
    }

    public CustomCursorAdapter(Activity activity) {
        super();
        mListView = activity.getListView();
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        // do what you need to do
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View view = View.inflate(context, R.layout.row_layout, null);

        RowViewHolder holder = new RowViewHolder();
        holder.mTitle = (TextView) view.findViewById(R.id.Title);
        holder.mText = (TextView) view.findViewById(R.id.Text);

        holder.mTitle.setOnClickListener(mOnTitleClickListener);
        holder.mText.setOnClickListener(mOnTextClickListener);

        view.setTag(holder);

        return view;
    }

    private OnClickListener mOnTitleClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            final int position = mListView.getPositionForView((View) v.getParent());
            Log.v(TAG, "Title clicked, row %d", position);
        }
    };

    private OnClickListener mOnTextClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            final int position = mListView.getPositionForView((View) v.getParent());
            Log.v(TAG, "Text clicked, row %d", position);
        }
    };
}

Head and tail in one line

>>> mylist = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> head, tail = mylist[0], mylist[1:]
>>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]

How can I uninstall Ruby on ubuntu?

I have tried many include sudo apt-get purge ruby , sudo apt-get remove ruby and sudo aptitude purpe ruby, both with and without '*' at the end. But none of them worked, it's may be I've installed more than one version ruby.

Finally, when I triedsudo apt-get purge ruby1.9(with the version), then it works.

Make text wrap in a cell with FPDF?

Text Wrap:

The MultiCell is used for print text with multiple lines. It has the same atributes of Cell except for ln and link.

$pdf->MultiCell( 200, 40, $reportSubtitle, 1);

Line Height:

What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).

MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])

You can read the full documentation here.

Setting a max height on a table

In Tables, For minimum table cells height or rows height use css height: in place of min-height:

AND

For Limiting max-height of all cells or rows in table with Javascript:

This script is good for horizontal overflow tables.

This script increase the table width 300px each time (maximum 4000px) until rows shrinks to max-height(160px) , and you can also edit numbers as your need.

var i = 0, row, table = document.getElementsByTagName('table')[0], j = table.offsetWidth;
while (row = table.rows[i++]) {
    while (row.offsetHeight > 160 && j < 4000) {
        j += 300;
        table.style.width = j + 'px';
    }
}

Source: HTML Table Solution Max Height Limit For Rows Or Cells By Increasing Table Width, Javascript

How can I get the last day of the month in C#?

DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)

RS256 vs HS256: What's the difference?

short answer, specific to OAuth2,

  • HS256 user client secret to generate the token signature and same secret is required to validate the token in back-end. So you should have a copy of that secret in your back-end server to verify the signature.
  • RS256 use public key encryption to sign the token.Signature(hash) will create using private key and it can verify using public key. So, no need of private key or client secret to store in back-end server, but back-end server will fetch the public key from openid configuration url in your tenant (https://[tenant]/.well-known/openid-configuration) to verify the token. KID parameter inside the access_toekn will use to detect the correct key(public) from openid-configuration.

How to get value from form field in django framework?

Take your pick:

def my_view(request):

    if request.method == 'POST':
        print request.POST.get('my_field')

        form = MyForm(request.POST)

        print form['my_field'].value()
        print form.data['my_field']

        if form.is_valid():

            print form.cleaned_data['my_field']
            print form.instance.my_field

            form.save()
            print form.instance.id  # now this one can access id/pk

Note: the field is accessed as soon as it's available.

How can I count the occurrences of a list item?

Why not using Pandas?

import pandas as pd

l = ['a', 'b', 'c', 'd', 'a', 'd', 'a']

# converting the list to a Series and counting the values
my_count = pd.Series(l).value_counts()
my_count

Output:

a    3
d    2
b    1
c    1
dtype: int64

If you are looking for a count of a particular element, say a, try:

my_count['a']

Output:

3

Executing a shell script from a PHP script

I was struggling with this exact issue for three days. I had set permissions on the script to 755. I had been calling my script as follows.

<?php
   $outcome = shell_exec('/tmp/clearUp.sh');
   echo $outcome;
?>

My script was as follows.

#!bin/bash
find . -maxdepth 1 -name "search*.csv" -mmin +0 -exec rm {} \;

I was getting no output or feedback. The change I made to get the script to run was to add a cd to tmp inside the script:

#!bin/bash
cd /tmp;
find . -maxdepth 1 -name "search*.csv" -mmin +0 -exec rm {} \;

This was more by luck than judgement but it is now working perfectly. I hope this helps.

How to trim whitespace from a Bash variable?

This is the simplest method I've seen. It only uses Bash, it's only a few lines, the regexp is simple, and it matches all forms of whitespace:

if [[ "$test" =~ ^[[:space:]]*([^[:space:]].*[^[:space:]])[[:space:]]*$ ]]
then 
    test=${BASH_REMATCH[1]}
fi

Here is a sample script to test it with:

test=$(echo -e "\n \t Spaces and tabs and newlines be gone! \t  \n ")

echo "Let's see if this works:"
echo
echo "----------"
echo -e "Testing:${test} :Tested"  # Ugh!
echo "----------"
echo
echo "Ugh!  Let's fix that..."

if [[ "$test" =~ ^[[:space:]]*([^[:space:]].*[^[:space:]])[[:space:]]*$ ]]
then 
    test=${BASH_REMATCH[1]}
fi

echo
echo "----------"
echo -e "Testing:${test}:Tested"  # "Testing:Spaces and tabs and newlines be gone!"
echo "----------"
echo
echo "Ah, much better."

How to change Rails 3 server default port in develoment?

I like to append the following to config/boot.rb:

require 'rails/commands/server'

module Rails
  class Server
    alias :default_options_alias :default_options
    def default_options
      default_options_alias.merge!(:Port => 3333)
    end    
  end
end

Combine Multiple child rows into one row MYSQL

If you really need multiple columns in your result, and the amount of options is limited, you can even do this:

select
  ordered_item.id as `Id`,
  ordered_item.Item_Name as `ItemName`,
  if(ordered_options.id=1,Ordered_Options.Value,null) as `Option1`,
  if(ordered_options.id=2,Ordered_Options.Value,null) as `Option2`,
  if(ordered_options.id=43,Ordered_Options.Value,null) as `Option43`,
  if(ordered_options.id=44,Ordered_Options.Value,null) as `Option44`,
  GROUP_CONCAT(if(ordered_options.id not in (1,2,43,44),Ordered_Options.Value,null)) as `OtherOptions`
from
  ordered_item,
  ordered_options
where
  ordered_item.id=ordered_options.ordered_item_id
group by
  ordered_item.id

Should I Dispose() DataSet and DataTable?

Datasets implement IDisposable thorough MarshalByValueComponent, which implements IDisposable. Since datasets are managed there is no real benefit to calling dispose.

How do I create a comma delimited string from an ArrayList?

foo.ToArray().Aggregate((a, b) => (a + "," + b)).ToString()

or

string.Concat(foo.ToArray().Select(a => a += ",").ToArray())

Updating, as this is extremely old. You should, of course, use string.Join now. It didn't exist as an option at the time of writing.

Selecting between two dates within a DateTime field - SQL Server

SELECT * 
FROM tbl 
WHERE myDate BETWEEN #date one# AND #date two#;

How to print out a variable in makefile

This can be done in a generic way and can be very useful when debugging a complex makefile. Following the same technique as described in another answer, you can insert the following into any makefile:

# if the first command line argument is "print"
ifeq ($(firstword $(MAKECMDGOALS)),print)

  # take the rest of the arguments as variable names
  VAR_NAMES := $(wordlist 2,$(words $(MAKECMDGOALS)),$(MAKECMDGOALS))

  # turn them into do-nothing targets
  $(eval $(VAR_NAMES):;@:))

  # then print them
  .PHONY: print
  print:
          @$(foreach var,$(VAR_NAMES),\
            echo '$(var) = $($(var))';)
endif

Then you can just do "make print" to dump the value of any variable:

$ make print CXXFLAGS
CXXFLAGS = -g -Wall

How to put scroll bar only for modal-body?

Optional: If you don't want the modal to exceed the window height and use a scrollbar in the .modal-body, you can use this responsive solution. See a working demo here: http://codepen.io/dimbslmh/full/mKfCc/

function setModalMaxHeight(element) {
  this.$element     = $(element);
  this.$content     = this.$element.find('.modal-content');
  var borderWidth   = this.$content.outerHeight() - this.$content.innerHeight();
  var dialogMargin  = $(window).width() > 767 ? 60 : 20;
  var contentHeight = $(window).height() - (dialogMargin + borderWidth);
  var headerHeight  = this.$element.find('.modal-header').outerHeight() || 0;
  var footerHeight  = this.$element.find('.modal-footer').outerHeight() || 0;
  var maxHeight     = contentHeight - (headerHeight + footerHeight);

  this.$content.css({
      'overflow': 'hidden'
  });

  this.$element
    .find('.modal-body').css({
      'max-height': maxHeight,
      'overflow-y': 'auto'
  });
}

$('.modal').on('show.bs.modal', function() {
  $(this).show();
  setModalMaxHeight(this);
});

$(window).resize(function() {
  if ($('.modal.in').length != 0) {
    setModalMaxHeight($('.modal.in'));
  }
});

Anaconda Installed but Cannot Launch Navigator

Open up a command terminal (CTRL+ALT+T) and try running this command:

anaconda-navigator

When I installed Anaconda, and read the website docs, they said that they tend to not add a file or menu path to run the navigator because there are so many different versions of different systems, instead they give the above terminal command to start the navigator GUI and advise on setting up a shortcut to do this process manually - if that works for you it shouldn't be too much trouble to do it this way - I do it like this personally

Getting IP address of client

I do like this,you can have a try

public String getIpAddr(HttpServletRequest request) {      
   String ip = request.getHeader("x-forwarded-for");      
   if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {      
       ip = request.getHeader("Proxy-Client-IP");      
   }      
   if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {      
       ip = request.getHeader("WL-Proxy-Client-IP");      
   }      
   if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {      
       ip = request.getRemoteAddr();      
   }      
   return ip;      
}   

Switch case on type c#

Here's an option that stays as true I could make it to the OP's requirement to be able to switch on type. If you squint hard enough it almost looks like a real switch statement.

The calling code looks like this:

var @switch = this.Switch(new []
{
    this.Case<WebControl>(x => { /* WebControl code here */ }),
    this.Case<TextBox>(x => { /* TextBox code here */ }),
    this.Case<ComboBox>(x => { /* ComboBox code here */ }),
});

@switch(obj);

The x in each lambda above is strongly-typed. No casting required.

And to make this magic work you need these two methods:

private Action<object> Switch(params Func<object, Action>[] tests)
{
    return o =>
    {
        var @case = tests
            .Select(f => f(o))
            .FirstOrDefault(a => a != null);

        if (@case != null)
        {
            @case();
        }
    };
}

private Func<object, Action> Case<T>(Action<T> action)
{
    return o => o is T ? (Action)(() => action((T)o)) : (Action)null;
}

Almost brings tears to your eyes, right?

Nonetheless, it works. Enjoy.

Socket File "/var/pgsql_socket/.s.PGSQL.5432" Missing In Mountain Lion (OS X Server)

i make in word by doing this:

dpkg-reconfigure locales

and choose your preferred locales

pg_createcluster 9.5 main --start

(9.5 is my version of postgresql)

/etc/init.d/postgresql start

and then it word!

sudo su - postgres
psql

What are best practices that you use when writing Objective-C and Cocoa?

Only release a property in dealloc method. If you want to release memory that the property is holding, just set it as nil:

self.<property> = nil;

jQuery - get all divs inside a div with class ".container"

To get all divs under 'container', use the following:

$(".container>div")  //or
$(".container").children("div");

You can stipulate a specific #id instead of div to get a particular one.

You say you want a div with an 'undefined' id. if I understand you right, the following would achieve this:

$(".container>div[id=]")

A 'for' loop to iterate over an enum in Java

If you don't care about the order this should work:

Set<Direction> directions = EnumSet.allOf(Direction.class);
for(Direction direction : directions) {
    // do stuff
}

How can I change the Java Runtime Version on Windows (7)?

All you need to do is set the PATH environment variable in Windows to point to where your java6 bin directory is instead of the java7 directory.

Right click My Computer > Advanced System Settings > Advanced > Environmental Variables

If there is a JAVA_HOME environment variable set this to point to the correct directory as well.

How can I do an UPDATE statement with JOIN in SQL Server?

Try this one, I think this will works for you

update ud

set ud.assid = sale.assid

from ud 

Inner join sale on ud.id = sale.udid

where sale.udid is not null

How to get all registered routes in Express?

Just use this npm package, it will give the web-output as well as terminal output in nice formatted table view.

enter image description here

https://www.npmjs.com/package/express-routes-catalogue

appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

I have encountered this issue with play-services:5.0.89. Upgrading to 6.1.11 solved problem.

What is the difference between a generative and a discriminative algorithm?

A generative algorithm models how the data was generated in order to categorize a signal. It asks the question: based on my generation assumptions, which category is most likely to generate this signal?

A discriminative algorithm does not care about how the data was generated, it simply categorizes a given signal.

How does one sum only those rows in excel not filtered out?

You need to use the SUBTOTAL function. The SUBTOTAL function ignores rows that have been excluded by a filter.

The formula would look like this:

=SUBTOTAL(9,B1:B20)

The function number 9, tells it to use the SUM function on the data range B1:B20.

If you are 'filtering' by hiding rows, the function number should be updated to 109.

=SUBTOTAL(109,B1:B20)

The function number 109 is for the SUM function as well, but hidden rows are ignored.

CSS to hide INPUT BUTTON value text

Use conditional statements at the top of the HTML document:

<!--[if lt IE 7 ]> <html lang="en" class="no-js ie6"> <![endif]-->
<!--[if IE 7 ]>    <html lang="en" class="no-js ie7"> <![endif]-->
<!--[if IE 8 ]>    <html lang="en" class="no-js ie8"> <![endif]-->
<!--[if IE 9 ]>    <html lang="en" class="no-js ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html lang="en" class="no-js"> <!--<![endif]-->

Then in the CSS add

.ie7 button { font-size:0;display:block;line-height:0 }

Taken from HTML5 Boilerplate - more specifically paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/

WPF: Setting the Width (and Height) as a Percentage Value

For anybody who is getting an error like : '2*' string cannot be converted to Length.

<Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="2*" /><!--This will make any control in this column of grid take 2/5 of total width-->
        <ColumnDefinition Width="3*" /><!--This will make any control in this column of grid take 3/5 of total width-->
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition MinHeight="30" />
    </Grid.RowDefinitions>

    <TextBlock Grid.Column="0" Grid.Row="0">Your text block a:</TextBlock>
    <TextBlock Grid.Column="1" Grid.Row="0">Your text block b:</TextBlock>
</Grid>

git rm - fatal: pathspec did not match any files

To remove the tracked and old committed file from git you can use the below command. Here in my case, I want to untrack and remove all the file from dist directory.

git filter-branch --force --index-filter 'git rm -r --cached --ignore-unmatch dist' --tag-name-filter cat -- --all

Then, you need to add it into your .gitignore so it won't be tracked further.

Open file with associated application

This is an old thread but just in case anyone comes across it like I did. pi.FileName needs to be set to the file name (and possibly full path to file ) of the executable you want to use to open your file. The below code works for me to open a video file with VLC.

var path = files[currentIndex].fileName;
var pi = new ProcessStartInfo(path)
{
    Arguments = Path.GetFileName(path),
    UseShellExecute = true,
    WorkingDirectory = Path.GetDirectoryName(path),
    FileName = "C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe",
    Verb = "OPEN"
};
Process.Start(pi)

Tigran's answer works but will use windows' default application to open your file, so using ProcessStartInfo may be useful if you want to open the file with an application that is not the default.

ASP.NET MVC Custom Error Handling Application_Error Global.asax?

I have problem with this error handling approach: In case of web.config:

<customErrors mode="On"/>

The error handler is searching view Error.shtml and the control flow step in to Application_Error global.asax only after exception

System.InvalidOperationException: The view 'Error' or its master was not found or no view engine supports the searched locations. The following locations were searched: ~/Views/home/Error.aspx ~/Views/home/Error.ascx ~/Views/Shared/Error.aspx ~/Views/Shared/Error.ascx ~/Views/home/Error.cshtml ~/Views/home/Error.vbhtml ~/Views/Shared/Error.cshtml ~/Views/Shared/Error.vbhtml at System.Web.Mvc.ViewResult.FindView(ControllerContext context) ....................

So

 Exception exception = Server.GetLastError();
  Response.Clear();
  HttpException httpException = exception as HttpException;

httpException is always null then customErrors mode="On" :( It is misleading Then <customErrors mode="Off"/> or <customErrors mode="RemoteOnly"/> the users see customErrors html, Then customErrors mode="On" this code is wrong too


Another problem of this code that

Response.Redirect(String.Format("~/Error/{0}/?message={1}", action, exception.Message));

Return page with code 302 instead real error code(402,403 etc)

Eclipse: Enable autocomplete / content assist

  1. window->preferences->java->Editor->Contest Assist
  2. Enter in Auto activation triggers for java:
    abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ._
  3. Apply and Close

other method:
type initial letter then ctrl+spacebar for auto-complete options.

How do I detect when someone shakes an iPhone?

I finally made it work using code examples from this Undo/Redo Manager Tutorial.
This is exactly what you need to do:

  • Set the applicationSupportsShakeToEdit property in the App's Delegate:
  • 
        - (void)applicationDidFinishLaunching:(UIApplication *)application {
    
            application.applicationSupportsShakeToEdit = YES;
    
            [window addSubview:viewController.view];
            [window makeKeyAndVisible];
    }
    

  • Add/Override canBecomeFirstResponder, viewDidAppear: and viewWillDisappear: methods in your View Controller:
  • 
    -(BOOL)canBecomeFirstResponder {
        return YES;
    }
    
    -(void)viewDidAppear:(BOOL)animated {
        [super viewDidAppear:animated];
        [self becomeFirstResponder];
    }
    
    - (void)viewWillDisappear:(BOOL)animated {
        [self resignFirstResponder];
        [super viewWillDisappear:animated];
    }
    

  • Add the motionEnded method to your View Controller:
  • 
    - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
    {
        if (motion == UIEventSubtypeMotionShake)
        {
            // your code
        }
    }
    

    Given final block not properly padded

    If you try to decrypt PKCS5-padded data with the wrong key, and then unpad it (which is done by the Cipher class automatically), you most likely will get the BadPaddingException (with probably of slightly less than 255/256, around 99.61%), because the padding has a special structure which is validated during unpad and very few keys would produce a valid padding.

    So, if you get this exception, catch it and treat it as "wrong key".

    This also can happen when you provide a wrong password, which then is used to get the key from a keystore, or which is converted into a key using a key generation function.

    Of course, bad padding can also happen if your data is corrupted in transport.

    That said, there are some security remarks about your scheme:

    • For password-based encryption, you should use a SecretKeyFactory and PBEKeySpec instead of using a SecureRandom with KeyGenerator. The reason is that the SecureRandom could be a different algorithm on each Java implementation, giving you a different key. The SecretKeyFactory does the key derivation in a defined manner (and a manner which is deemed secure, if you select the right algorithm).

    • Don't use ECB-mode. It encrypts each block independently, which means that identical plain text blocks also give always identical ciphertext blocks.

      Preferably use a secure mode of operation, like CBC (Cipher block chaining) or CTR (Counter). Alternatively, use a mode which also includes authentication, like GCM (Galois-Counter mode) or CCM (Counter with CBC-MAC), see next point.

    • You normally don't want only confidentiality, but also authentication, which makes sure the message is not tampered with. (This also prevents chosen-ciphertext attacks on your cipher, i.e. helps for confidentiality.) So, add a MAC (message authentication code) to your message, or use a cipher mode which includes authentication (see previous point).

    • DES has an effective key size of only 56 bits. This key space is quite small, it can be brute-forced in some hours by a dedicated attacker. If you generate your key by a password, this will get even faster. Also, DES has a block size of only 64 bits, which adds some more weaknesses in chaining modes. Use a modern algorithm like AES instead, which has a block size of 128 bits, and a key size of 128 bits (for the standard variant).

    How to use the DropDownList's SelectedIndexChanged event

    You should add AutoPostBack="true" to DropDownList1

                    <asp:DropDownList ID="ddmanu" runat="server" AutoPostBack="true"
                        DataSourceID="Sql_fur_model_manu"    
                        DataTextField="manufacturer" DataValueField="manufacturer" 
                        onselectedindexchanged="ddmanu_SelectedIndexChanged">
                    </asp:DropDownList>
    

    How can I see CakePHP's SQL dump in the controller?

    What worked finally for me and also compatible with 2.0 is to add in my layout (or in model)

    <?php echo $this->element('sql_dump');?>
    

    It is also depending on debug variable setted into Config/core.php

    How to convert numpy arrays to standard TensorFlow format?

    You can use placeholders and feed_dict.

    Suppose we have numpy arrays like these:

    trX = np.linspace(-1, 1, 101) 
    trY = 2 * trX + np.random.randn(*trX.shape) * 0.33 
    

    You can declare two placeholders:

    X = tf.placeholder("float") 
    Y = tf.placeholder("float")
    

    Then, use these placeholders (X, and Y) in your model, cost, etc.: model = tf.mul(X, w) ... Y ... ...

    Finally, when you run the model/cost, feed the numpy arrays using feed_dict:

    with tf.Session() as sess:
    .... 
        sess.run(model, feed_dict={X: trY, Y: trY})
    

    How to change the timeout on a .NET WebClient object

    'CORRECTED VERSION OF LAST FUNCTION IN VISUAL BASIC BY GLENNG
    
    Protected Overrides Function GetWebRequest(ByVal address As System.Uri) As System.Net.WebRequest
                Dim w As System.Net.WebRequest = MyBase.GetWebRequest(address)
                If _TimeoutMS <> 0 Then
                    w.Timeout = _TimeoutMS
                End If
                Return w  '<<< NOTICE: MyBase.GetWebRequest(address) DOES NOT WORK >>>
            End Function
    

    How do I read from parameters.yml in a controller in symfony2?

    You can use:

    public function indexAction()
    {
       dump( $this->getParameter('api_user'));
    }
    

    For more information I recommend you read the doc :

    http://symfony.com/doc/2.8/service_container/parameters.html

    What does `m_` variable prefix mean?

    It is common practice in C++. This is because in C++ you can't have same name for the member function and member variable, and getter functions are often named without "get" prefix.

    class Person
    {
       public:
          std::string name() const;
    
       private:
          std::string name; // This would lead to a compilation error.
          std::string m_name; // OK.
    };
    

    main.cpp:9:19: error: duplicate member 'name'
          std::string name;
                      ^
    main.cpp:6:19: note: previous declaration is here
          std::string name() const;
                      ^
    1 error generated.
    

    http://coliru.stacked-crooked.com/a/f38e7dbb047687ad

    "m_" states for the "member". Prefix "_" is also common.

    You shouldn't use it in programming languages that solve this problem by using different conventions/grammar.

    How to make Apache serve index.php instead of index.html?

    As others have noted, most likely you don't have .html set up to handle php code.

    Having said that, if all you're doing is using index.html to include index.php, your question should probably be 'how do I use index.php as index document?

    In which case, for Apache (httpd.conf), search for DirectoryIndex and replace the line with this (will only work if you have dir_module enabled, but that's default on most installs):

    DirectoryIndex index.php
    

    If you use other directory indexes, list them in order of preference i.e.

    DirectoryIndex index.php index.phtml index.html index.htm
    

    How do I call REST API from an android app?

    1. If you want to integrate Retrofit (all steps defined here):

    Goto my blog : retrofit with kotlin

    1. Please use android-async-http library.

    the link below explains everything step by step.

    http://loopj.com/android-async-http/

    Here are sample apps:

    1. http://www.techrepublic.com/blog/software-engineer/calling-restful-services-from-your-android-app/

    2. http://blog.strikeiron.com/bid/73189/Integrate-a-REST-API-into-Android-Application-in-less-than-15-minutes

    Create a class :

    public class HttpUtils {
      private static final String BASE_URL = "http://api.twitter.com/1/";
     
      private static AsyncHttpClient client = new AsyncHttpClient();
    
      public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
          client.get(getAbsoluteUrl(url), params, responseHandler);
      }
    
      public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
          client.post(getAbsoluteUrl(url), params, responseHandler);
      }
          
      public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
          client.get(url, params, responseHandler);
      }
    
      public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
          client.post(url, params, responseHandler);
      }
    
      private static String getAbsoluteUrl(String relativeUrl) {
          return BASE_URL + relativeUrl;
      }
    }
    

    Call Method :

        RequestParams rp = new RequestParams();
        rp.add("username", "aaa"); rp.add("password", "aaa@123");
                        
        HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                // If the response is JSONObject instead of expected JSONArray
                Log.d("asd", "---------------- this is response : " + response);
                try {
                    JSONObject serverResp = new JSONObject(response.toString());                                                
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }                   
            }
                
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
                // Pull out the first event on the public timeline
                        
            }
        });
    

    Please grant internet permission in your manifest file.

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

    you can add compile 'com.loopj.android:android-async-http:1.4.9' for Header[] and compile 'org.json:json:20160212' for JSONObject in build.gradle file if required.

    How to append rows in a pandas dataframe in a for loop?

    I have created a data frame in a for loop with the help of a temporary empty data frame. Because for every iteration of for loop, a new data frame will be created thereby overwriting the contents of previous iteration.

    Hence I need to move the contents of the data frame to the empty data frame that was created already. It's as simple as that. We just need to use .append function as shown below :

    temp_df = pd.DataFrame() #Temporary empty dataframe
    for sent in Sentences:
        New_df = pd.DataFrame({'words': sent.words}) #Creates a new dataframe and contains tokenized words of input sentences
        temp_df = temp_df.append(New_df, ignore_index=True) #Moving the contents of newly created dataframe to the temporary dataframe
    

    Outside the for loop, you can copy the contents of the temporary data frame into the master data frame and then delete the temporary data frame if you don't need it

    here-document gives 'unexpected end of file' error

    Here is a flexible way to do deal with multiple indented lines without using heredoc.

      echo 'Hello!'
      sed -e 's:^\s*::' < <(echo '
        Some indented text here.
        Some indented text here.
      ')
      if [[ true ]]; then
        sed -e 's:^\s\{4,4\}::' < <(echo '
          Some indented text here.
            Some extra indented text here.
          Some indented text here.
        ')
      fi
    

    Some notes on this solution:

    • if the content is expected to have simple quotes, either escape them using \ or replace the string delimiters with double quotes. In the latter case, be careful that construction like $(command) will be interpreted. If the string contains both simple and double quotes, you'll have to escape at least of kind.
    • the given example print a trailing empty line, there are numerous way to get rid of it, not included here to keep the proposal to a minimum clutter
    • the flexibility comes from the ease with which you can control how much leading space should stay or go, provided that you know some sed REGEXP of course.

    How to [recursively] Zip a directory in PHP?

    This code works for both windows and linux.

    function Zip($source, $destination)
    {
    if (!extension_loaded('zip') || !file_exists($source)) {
        return false;
    }
    
    $zip = new ZipArchive();
    if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
        return false;
    }
    
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        DEFINE('DS', DIRECTORY_SEPARATOR); //for windows
    } else {
        DEFINE('DS', '/'); //for linux
    }
    
    
    $source = str_replace('\\', DS, realpath($source));
    
    if (is_dir($source) === true)
    {
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
        echo $source;
        foreach ($files as $file)
        {
            $file = str_replace('\\',DS, $file);
            // Ignore "." and ".." folders
            if( in_array(substr($file, strrpos($file, DS)+1), array('.', '..')) )
                continue;
    
            $file = realpath($file);
    
            if (is_dir($file) === true)
            {
                $zip->addEmptyDir(str_replace($source . DS, '', $file . DS));
            }
            else if (is_file($file) === true)
            {
                $zip->addFromString(str_replace($source . DS, '', $file), file_get_contents($file));
            }
            echo $source;
        }
    }
    else if (is_file($source) === true)
    {
        $zip->addFromString(basename($source), file_get_contents($source));
    }
    
    return $zip->close();
    }
    

    How do I get the browser scroll position in jQuery?

    Since it appears you are using jQuery, here is a jQuery solution.

    $(function() {
        $('#Eframe').on("mousewheel", function() {
            alert($(document).scrollTop());
        });
    });
    

    Not much to explain here. If you want, here is the jQuery documentation.

    WCF Error - Could not find default endpoint element that references contract 'UserService.UserService'

    Had to add the service in the calling App.config file to have it work. Make sure that you but it after all . This seemed to work for me.

    Why does NULL = NULL evaluate to false in SQL server

    Maybe it depends, but I thought NULL=NULL evaluates to NULL like most operations with NULL as an operand.

    Do something if screen width is less than 960 px

    // Adds and removes body class depending on screen width.
    function screenClass() {
        if($(window).innerWidth() > 960) {
            $('body').addClass('big-screen').removeClass('small-screen');
        } else {
            $('body').addClass('small-screen').removeClass('big-screen');
        }
    }
    
    // Fire.
    screenClass();
    
    // And recheck when window gets resized.
    $(window).bind('resize',function(){
        screenClass();
    });
    

    How to Call Controller Actions using JQuery in ASP.NET MVC

    You can start reading from here jQuery.ajax()

    Actually Controller Action is a public method which can be accessed through Url. So any call of an Action from an Ajax call, either MicrosoftMvcAjax or jQuery can be made. For me, jQuery is the simplest one. It got a lots of examples in the link I gave above. The typical example for an ajax call is like this.

    $.ajax({
        // edit to add steve's suggestion.
        //url: "/ControllerName/ActionName",
        url: '<%= Url.Action("ActionName", "ControllerName") %>',
        success: function(data) {
             // your data could be a View or Json or what ever you returned in your action method 
             // parse your data here
             alert(data);
        }
    });
    

    More examples can be found in here

    Disable button in jQuery

    Try this code:
    HTML

    <button type='button' id = 'rbutton_'+i onclick="disable(i)">Click me</button>
    

    function

    function disable(i){
        $("#rbutton_"+i).attr("disabled","disabled");
    }
    

    Other solution with jquery

    $('button').click(function(){ 
        $(this).attr("disabled","disabled");
    });
    

    DEMO


    Other solution with pure javascript

    <button type='button' id = 'rbutton_1' onclick="disable(1)">Click me</button>
    
    <script>
    function disable(i){
     document.getElementById("rbutton_"+i).setAttribute("disabled","disabled");
    }
    </script>
    

    DEMO2

    How do I get the coordinates of a mouse click on a canvas element?

    First, as others have said, you need a function to get the position of the canvas element. Here's a method that's a little more elegant than some of the others on this page (IMHO). You can pass it any element and get its position in the document:

    function findPos(obj) {
        var curleft = 0, curtop = 0;
        if (obj.offsetParent) {
            do {
                curleft += obj.offsetLeft;
                curtop += obj.offsetTop;
            } while (obj = obj.offsetParent);
            return { x: curleft, y: curtop };
        }
        return undefined;
    }
    

    Now calculate the current position of the cursor relative to that:

    $('#canvas').mousemove(function(e) {
        var pos = findPos(this);
        var x = e.pageX - pos.x;
        var y = e.pageY - pos.y;
        var coordinateDisplay = "x=" + x + ", y=" + y;
        writeCoordinateDisplay(coordinateDisplay);
    });
    

    Notice that I've separated the generic findPos function from the event handling code. (As it should be. We should try to keep our functions to one task each.)

    The values of offsetLeft and offsetTop are relative to offsetParent, which could be some wrapper div node (or anything else, for that matter). When there is no element wrapping the canvas they're relative to the body, so there is no offset to subtract. This is why we need to determine the position of the canvas before we can do anything else.

    Similary, e.pageX and e.pageY give the position of the cursor relative to the document. That's why we subtract the canvas's offset from those values to arrive at the true position.

    An alternative for positioned elements is to directly use the values of e.layerX and e.layerY. This is less reliable than the method above for two reasons:

    1. These values are also relative to the entire document when the event does not take place inside a positioned element
    2. They are not part of any standard

    Adding CSRFToken to Ajax request

    From JSP

    <form method="post" id="myForm" action="someURL">
        <input name="csrfToken" value="5965f0d244b7d32b334eff840...etc" type="hidden">    
    </form>
    

    This is the simplest way that worked for me after struggling for 3hrs, just get the token from input hidden field like this and while doing the AJAX request to just need to pass this token in header as follows:-

    From Jquery

    var token =  $('input[name="csrfToken"]').attr('value'); 
    

    From plain Javascript

    var token = document.getElementsByName("csrfToken").value;
    

    Final AJAX Request

    $.ajax({
          url: route.url,
          data : JSON.stringify(data),
          method : 'POST',
          headers: {
                        'X-CSRF-Token': token 
                   },
          success: function (data) { ...      },
          error: function (data) { ...  }
    

    });

    Now you don't need to disable crsf security in web config, and also this will not give you 405( Method Not Allowed) error on console.

    Hope this will help people..!!

    Is there a conditional ternary operator in VB.NET?

    If() is the closest equivalent but beware of implicit conversions going on if you have set "Option Strict off"

    For example, if your not careful you may be tempted to try something like:

    Dim foo As Integer? = If(someTrueExpression, Nothing, 2)
    

    Will give "foo" a value of 0!

    I think the '?' operator equivalent in C# would instead fail compilation

    React: Expected an assignment or function call and instead saw an expression

    The return statements should place in one line. Or the other option is to remove the curly brackets that bound the HTML statement.

    example:

    return posts.map((post, index) =>
        <div key={index}>
          <h3>{post.title}</h3>
          <p>{post.body}</p>
        </div>
    );
    

    How do I find the authoritative name-server for a domain name?

    You used the singular in your question but there are typically several authoritative name servers, the RFC 1034 recommends at least two.

    Unless you mean "primary name server" and not "authoritative name server". The secondary name servers are authoritative.

    To find out the name servers of a domain on Unix:

      % dig +short NS stackoverflow.com
     ns52.domaincontrol.com.
     ns51.domaincontrol.com.
    

    To find out the server listed as primary (the notion of "primary" is quite fuzzy these days and typically has no good answer):

    % dig +short  SOA stackoverflow.com | cut -d' ' -f1
    ns51.domaincontrol.com.
    

    To check discrepencies between name servers, my preference goes to the old check_soa tool, described in Liu & Albitz "DNS & BIND" book (O'Reilly editor). The source code is available in http://examples.oreilly.com/dns5/

    % check_soa stackoverflow.com
    ns51.domaincontrol.com has serial number 2008041300
    ns52.domaincontrol.com has serial number 2008041300
    

    Here, the two authoritative name servers have the same serial number. Good.

    How to go from one page to another page using javascript?

    To simply redirect a browser using javascript:

    window.location.href = "http://example.com/new_url";
    

    To redirect AND submit a form (i.e. login details), requires no javascript:

    <form action="/new_url" method="POST">
       <input name="username">
       <input type="password" name="password">
       <button type="submit">Submit</button>
    </form>
    

    MVC Razor view nested foreach's model

    Another much simpler possibility is that one of your property names is wrong (probably one you just changed in the class). This is what it was for me in RazorPages .NET Core 3.

    How do I bind a List<CustomObject> to a WPF DataGrid?

    if you do not expect that your list will be recreated then you can use the same approach as you've used for Asp.Net (instead of DataSource this property in WPF is usually named ItemsSource):

    this.dataGrid1.ItemsSource = list;
    

    But if you would like to replace your list with new collection instance then you should consider using databinding.

    Any way to Invoke a private method?

    If the method accepts non-primitive data type then the following method can be used to invoke a private method of any class:

    public static Object genericInvokeMethod(Object obj, String methodName,
                Object... params) {
            int paramCount = params.length;
            Method method;
            Object requiredObj = null;
            Class<?>[] classArray = new Class<?>[paramCount];
            for (int i = 0; i < paramCount; i++) {
                classArray[i] = params[i].getClass();
            }
            try {
                method = obj.getClass().getDeclaredMethod(methodName, classArray);
                method.setAccessible(true);
                requiredObj = method.invoke(obj, params);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
    
            return requiredObj;
        }
    

    The Parameter accepted are obj, methodName and the parameters. For example

    public class Test {
    private String concatString(String a, String b) {
        return (a+b);
    }
    }
    

    Method concatString can be invoked as

    Test t = new Test();
        String str = (String) genericInvokeMethod(t, "concatString", "Hello", "Mr.x");
    

    Defining a variable with or without export

    Two of the creators of UNIX, Brian Kernighan and Rob Pike, explain this in their book "The UNIX Programming Environment". Google for the title and you'll easily find a pdf version.

    They address shell variables in section 3.6, and focus on the use of the export command at the end of that section:

    When you want to make the value of a variable accessible in sub-shells, the shell's export command should be used. (You might think about why there is no way to export the value of a variable from a sub-shell to its parent).

    Oracle SqlDeveloper JDK path

    For those who use Mac, edit this file:

    /Applications/SQLDeveloper.app/Contents/MacOS/sqldeveloper.sh
    

    Mine had:

    export JAVA_HOME=`/usr/libexec/java_home -v 1.7`
    

    and I changed it to 1.8 and it stopped complaining about java version.

    Is there a limit on how much JSON can hold?

    If you are working with ASP.NET MVC, you can solve the problem by adding the MaxJsonLength to your result:

    var jsonResult = Json(new
    {
        draw = param.Draw,
        recordsTotal = count,
        recordsFiltered = count,
        data = result
    }, JsonRequestBehavior.AllowGet);
    jsonResult.MaxJsonLength = int.MaxValue;
    

    How to "EXPIRE" the "HSET" child key in redis?

    This is not possible, for the sake of keeping Redis simple.

    Quoth Antirez, creator of Redis:

    Hi, it is not possible, either use a different top-level key for that specific field, or store along with the filed another field with an expire time, fetch both, and let the application understand if it is still valid or not based on current time.

    Error java.lang.OutOfMemoryError: GC overhead limit exceeded

    If you are sure there are no memory leaks in your program, try to:

    1. Increase the heap size, for example -Xmx1g.
    2. Enable the concurrent low pause collector -XX:+UseConcMarkSweepGC.
    3. Reuse existing objects when possible to save some memory.

    If necessary, the limit check can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.

    Declaring a python function with an array parameters and passing an array argument to the function call?

    I guess I'm unclear about what the OP was really asking for... Do you want to pass the whole array/list and operate on it inside the function? Or do you want the same thing done on every value/item in the array/list. If the latter is what you wish I have found a method which works well.

    I'm more familiar with programming languages such as Fortran and C, in which you can define elemental functions which operate on each element inside an array. I finally tracked down the python equivalent to this and thought I would repost the solution here. The key is to 'vectorize' the function. Here is an example:

    def myfunc(a,b):
        if (a>b): return a
        else: return b
    vecfunc = np.vectorize(myfunc)
    result=vecfunc([[1,2,3],[5,6,9]],[7,4,5])
    print(result)
    

    Output:

    [[7 4 5]
     [7 6 9]]
    

    Create a custom event in Java

    The following is not exactly the same but similar, I was searching for a snippet to add a call to the interface method, but found this question, so I decided to add this snippet for those who were searching for it like me and found this question:

     public class MyClass
     {
            //... class code goes here
    
            public interface DataLoadFinishedListener {
                public void onDataLoadFinishedListener(int data_type);
            }
    
            private DataLoadFinishedListener m_lDataLoadFinished;
    
            public void setDataLoadFinishedListener(DataLoadFinishedListener dlf){
                this.m_lDataLoadFinished = dlf;
            }
    
    
    
            private void someOtherMethodOfMyClass()
            {
                m_lDataLoadFinished.onDataLoadFinishedListener(1);
            }    
        }
    

    Usage is as follows:

    myClassObj.setDataLoadFinishedListener(new MyClass.DataLoadFinishedListener() {
                @Override
                public void onDataLoadFinishedListener(int data_type) {
                    }
                });
    

    How do I install cURL on Windows?

    You're probably mistaking what PHP.ini you need to edit. first, add a PHPinfo(); to a info.php, and run it from your browser.

    Write down the PHP ini directory path you see in the variables list now! You will probably notice that it's different from your PHP-CLI ini file.

    Enable the extension

    You're done :-)

    How do I compare 2 rows from the same table (SQL Server)?

    You can join a table to itself as many times as you require, it is called a self join.

    An alias is assigned to each instance of the table (as in the example below) to differentiate one from another.

    SELECT a.SelfJoinTableID
    FROM   dbo.SelfJoinTable a
           INNER JOIN dbo.SelfJoinTable b
             ON a.SelfJoinTableID = b.SelfJoinTableID
           INNER JOIN dbo.SelfJoinTable c
             ON a.SelfJoinTableID = c.SelfJoinTableID
    WHERE  a.Status = 'Status to filter a'
           AND b.Status = 'Status to filter b'
           AND c.Status = 'Status to filter c' 
    

    From milliseconds to hour, minutes, seconds and milliseconds

    Maybe can be shorter an more elegant. But I did it.

    public String getHumanTimeFormatFromMilliseconds(String millisecondS){
        String message = "";
        long milliseconds = Long.valueOf(millisecondS);
        if (milliseconds >= 1000){
            int seconds = (int) (milliseconds / 1000) % 60;
            int minutes = (int) ((milliseconds / (1000 * 60)) % 60);
            int hours = (int) ((milliseconds / (1000 * 60 * 60)) % 24);
            int days = (int) (milliseconds / (1000 * 60 * 60 * 24));
            if((days == 0) && (hours != 0)){
                message = String.format("%d hours %d minutes %d seconds ago", hours, minutes, seconds);
            }else if((hours == 0) && (minutes != 0)){
                message = String.format("%d minutes %d seconds ago", minutes, seconds);
            }else if((days == 0) && (hours == 0) && (minutes == 0)){
                message = String.format("%d seconds ago", seconds);
            }else{
                message = String.format("%d days %d hours %d minutes %d seconds ago", days, hours, minutes, seconds);
            }
        } else{
            message = "Less than a second ago.";
        }
        return message;
    }
    

    How to reload current page without losing any form data?

    window.location.reload() // without passing true as argument
    

    works for me.

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

    You can just use the Select() extension method:

    IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
    IEnumerable<string> strings = integers.Select(i => i.ToString());
    

    Or in LINQ syntax:

    IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
    
    var strings = from i in integers
                  select i.ToString();
    

    Display PDF within web browser

    You can also embed using JavaScript through a third-party solution like PDFObject.

    installing apache: no VCRUNTIME140.dll

    I was gone through same problem & I resolved it by following steps.

    1. Uninstall earlier version of wamp server, which you are trying to install.
    2. Install which ever file supports to your configuration (64, 86) from en this link
    3. Restart your computer.
    4. Install wampserver now.

    For Restful API, can GET method use json data?

    To answer your question, yes you may pass JSON in the URI as part of a GET request (provided you URL-encode). However, considering your reason for doing this is due to the length of the URI, using JSON will be self-defeating (introducing more characters than required).

    I suggest you send your parameters in body of a POST request, either in regular CGI style (param1=val1&param2=val2) or JSON (parsed by your API upon receipt)

    I need a Nodejs scheduler that allows for tasks at different intervals

    I think the best ranking is

    1.node-schedule

    2.later

    3.crontab

    and the sample of node-schedule is below:

    var schedule = require("node-schedule");
    var rule = new schedule.RecurrenceRule();
    //rule.minute = 40;
    rule.second = 10;
    var jj = schedule.scheduleJob(rule, function(){
        console.log("execute jj");
    });
    

    Maybe you can find the answer from node modules.

    Casting a variable using a Type variable

    I will never understand why you need up to 50 reputation to leave a comment but I just had to say that @Curt answer is exactly what I was looking and hopefully someone else.

    In my example, I have an ActionFilterAttribute that I was using to update the values of a json patch document. I didn't what the T model was for the patch document to I had to serialize & deserialize it to a plain JsonPatchDocument, modify it, then because I had the type, serialize & deserialize it back to the type again.

    Type originalType = //someType that gets passed in to my constructor.
    
    var objectAsString = JsonConvert.SerializeObject(myObjectWithAGenericType);
    var plainPatchDocument = JsonConvert.DeserializeObject<JsonPatchDocument>(objectAsString);
    
    var plainPatchDocumentAsString= JsonConvert.SerializeObject(plainPatchDocument);
    var modifiedObjectWithGenericType = JsonConvert.DeserializeObject(plainPatchDocumentAsString, originalType );
    

    How do you handle a form change in jQuery?

    You can do this:

    $("form :input").change(function() {
      $(this).closest('form').data('changed', true);
    });
    $('#mybutton').click(function() {
      if($(this).closest('form').data('changed')) {
         //do something
      }
    });
    

    This rigs a change event handler to inputs in the form, if any of them change it uses .data() to set a changed value to true, then we just check for that value on the click, this assumes that #mybutton is inside the form (if not just replace $(this).closest('form') with $('#myForm')), but you could make it even more generic, like this:

    $('.checkChangedbutton').click(function() {
      if($(this).closest('form').data('changed')) {
         //do something
      }
    });
    

    References: Updated

    According to jQuery this is a filter to select all form controls.

    http://api.jquery.com/input-selector/

    The :input selector basically selects all form controls.

    Why maven? What are the benefits?

    Figuring out package dependencies is really not that hard. You rarely do it anyway. Probably once during project setup and few more during upgrades. With maven you'll end up fixing mismatched dependencies, badly written poms, and doing package exclusions anyway.

    Not that hard... for toy projects. But the projects I work on have many, really many, of them, and I'm very glad to get them transitively, to have a standardized naming scheme for them. Managing all this manually by hand would be a nightmare.

    And yes, sometimes you have to work on the convergence of dependencies. But think about it twice, this is not inherent to Maven, this is inherent to any system using dependencies (and I am talking about Java dependencies in general here).

    So with Ant, you have to do the same work except that you have to do everything manually: grabbing some version of project A and its dependencies, grabbing some version of project B and its dependencies, figuring out yourself what exact versions they use, checking that they don't overlap, checking that they are not incompatible, etc. Welcome to hell.

    On the other hand, Maven supports dependency management and will retrieve them transitively for me and gives me the tooling I need to manage the complexity inherent to dependency management: I can analyze a dependency tree, control the versions used in transitive dependencies, exclude some of them if required, control the converge across modules, etc. There is no magic. But at least you have support.

    And don't forget that dependency management is only a small part of what Maven offers, there is much more (not even mentioning the other tools that integrates nicely with Maven, e.g. Sonar).

    Slow FIX-COMPILE-DEPLOY-DEBUG cycle, which kills productivity. This is my main gripe. You make a change, the you have to wait for maven build to kick in and wait for it to deploy. No hot deployment whatsoever.

    First, why do you use Maven like this? I don't. I use my IDE to write tests, code until they pass, refactor, deploy, hot deploy and run a local Maven build when I'm done, before to commit, to make sure I will not break the continuous build.

    Second, I'm not sure using Ant would make things much better. And to my experience, modular Maven builds using binary dependencies gives me faster build time than typical monolithic Ant builds. Anyway, have a look at Maven Shell for a ready to (re)use Maven environment (which is awesome by the way).

    So at end, and I'm sorry to say so, it's not really Maven that is killing your productivity, it's you misusing your tools. And if you're not happy with it, well, what can I say, don't use it. Personally, I'm using Maven since 2003 and I never looked back.

    access denied for user @ 'localhost' to database ''

    Try this: Adding users to MySQL

    You need grant privileges to the user if you want external acess to database(ie. web pages).

    $ is not a function - jQuery error

    That error kicks in when you have forgot to include the jQuery library in your page or there is conflict between libraries - for example you be using any other javascript library on your page.

    Take a look at this for more info:

    Convert from List into IEnumerable format

    You need to

    using System.Linq;
    

    to use IEnumerable options at your List.

    Favicon: .ico or .png / correct tags?

    See here: Cross Browser favicon

    Thats the way to go:

    <link rel="icon" type="image/png" href="http://www.example.com/image.png"><!-- Major Browsers -->
    <!--[if IE]><link rel="SHORTCUT ICON" href="http://www.example.com/alternateimage.ico"/><![endif]--><!-- Internet Explorer-->
    

    Angularjs: Error: [ng:areq] Argument 'HomeController' is not a function, got undefined

    In my case, I was missing the name of the Angular application in the html file. For example, I had included this file to be start of my application code. I had assumed it was being ran, but it wasn't.

    app.module.js

    (function () {
        'use strict';
    
        angular
            .module('app', [
            // Other dependencies here...
            ])
        ;
    
    })();
    

    However, when I declared the app in the html I had this:

    index.html

    <html lang="en" ng-app>
    

    But to reference the Angular application by the name I used, I had to use:

    index.html (Fixed)

    <html lang="en" ng-app="app">
    

    Custom Authentication in ASP.Net-Core

    From what I learned after several days of research, Here is the Guide for ASP .Net Core MVC 2.x Custom User Authentication

    In Startup.cs :

    Add below lines to ConfigureServices method :

    public void ConfigureServices(IServiceCollection services)
    {
    
    services.AddAuthentication(
        CookieAuthenticationDefaults.AuthenticationScheme
    ).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
        options =>
        {
            options.LoginPath = "/Account/Login";
            options.LogoutPath = "/Account/Logout";
        });
    
        services.AddMvc();
    
        // authentication 
        services.AddAuthentication(options =>
        {
           options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        });
    
        services.AddTransient(
            m => new UserManager(
                Configuration
                    .GetValue<string>(
                        DEFAULT_CONNECTIONSTRING //this is a string constant
                    )
                )
            );
         services.AddDistributedMemoryCache();
    }
    

    keep in mind that in above code we said that if any unauthenticated user requests an action which is annotated with [Authorize] , they well force redirect to /Account/Login url.

    Add below lines to Configure method :

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler(ERROR_URL);
        }
         app.UseStaticFiles();
         app.UseAuthentication();
         app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: DEFAULT_ROUTING);
        });
    }
    

    Create your UserManager class that will also manage login and logout. it should look like below snippet (note that i'm using dapper):

    public class UserManager
    {
        string _connectionString;
    
        public UserManager(string connectionString)
        {
            _connectionString = connectionString;
        }
    
        public async void SignIn(HttpContext httpContext, UserDbModel user, bool isPersistent = false)
        {
            using (var con = new SqlConnection(_connectionString))
            {
                var queryString = "sp_user_login";
                var dbUserData = con.Query<UserDbModel>(
                    queryString,
                    new
                    {
                        UserEmail = user.UserEmail,
                        UserPassword = user.UserPassword,
                        UserCellphone = user.UserCellphone
                    },
                    commandType: CommandType.StoredProcedure
                ).FirstOrDefault();
    
                ClaimsIdentity identity = new ClaimsIdentity(this.GetUserClaims(dbUserData), CookieAuthenticationDefaults.AuthenticationScheme);
                ClaimsPrincipal principal = new ClaimsPrincipal(identity);
    
                await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
            }
        }
    
        public async void SignOut(HttpContext httpContext)
        {
            await httpContext.SignOutAsync();
        }
    
        private IEnumerable<Claim> GetUserClaims(UserDbModel user)
        {
            List<Claim> claims = new List<Claim>();
    
            claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id().ToString()));
            claims.Add(new Claim(ClaimTypes.Name, user.UserFirstName));
            claims.Add(new Claim(ClaimTypes.Email, user.UserEmail));
            claims.AddRange(this.GetUserRoleClaims(user));
            return claims;
        }
    
        private IEnumerable<Claim> GetUserRoleClaims(UserDbModel user)
        {
            List<Claim> claims = new List<Claim>();
    
            claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id().ToString()));
            claims.Add(new Claim(ClaimTypes.Role, user.UserPermissionType.ToString()));
            return claims;
        }
    }
    

    Then maybe you have an AccountController which has a Login Action that should look like below :

    public class AccountController : Controller
    {
        UserManager _userManager;
    
        public AccountController(UserManager userManager)
        {
            _userManager = userManager;
        }
    
        [HttpPost]
        public IActionResult LogIn(LogInViewModel form)
        {
            if (!ModelState.IsValid)
                return View(form);
             try
            {
                //authenticate
                var user = new UserDbModel()
                {
                    UserEmail = form.Email,
                    UserCellphone = form.Cellphone,
                    UserPassword = form.Password
                };
                _userManager.SignIn(this.HttpContext, user);
                 return RedirectToAction("Search", "Home", null);
             }
             catch (Exception ex)
             {
                ModelState.AddModelError("summary", ex.Message);
                return View(form);
             }
        }
    }
    

    Now you are able to use [Authorize] annotation on any Action or Controller.

    Feel free to comment any questions or bug's.

    Get unicode value of a character

    char c = 'a';
    String a = Integer.toHexString(c); // gives you---> a = "61"
    

    File upload along with other object in Jersey restful web service

    The request type is multipart/form-data and what you are sending is essentially form fields that go out as bytes with content boundaries separating different form fields.To send an object representation as form field (string), you can send a serialized form from the client that you can then deserialize on the server.

    After all no programming environment object is actually ever traveling on the wire. The programming environment on both side are just doing automatic serialization and deserialization that you can also do. That is the cleanest and programming environment quirks free way to do it.

    As an example, here is a javascript client posting to a Jersey example service,

    submitFile(){
    
        let data = new FormData();
        let account = {
            "name": "test account",
            "location": "Bangalore"
        }
    
        data.append('file', this.file);
        data.append("accountKey", "44c85e59-afed-4fb2-884d-b3d85b051c44");
        data.append("device", "test001");
        data.append("account", JSON.stringify(account));
        
        let url = "http://localhost:9090/sensordb/test/file/multipart/upload";
    
        let config = {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }
    
        axios.post(url, data, config).then(function(data){
            console.log('SUCCESS!!');
            console.log(data.data);
        }).catch(function(){
            console.log('FAILURE!!');
        });
    },
    

    Here the client is sending a file, 2 form fields (strings) and an account object that has been stringified for transport. here is how the form fields look on the wire,

    enter image description here

    On the server, you can just deserialize the form fields the way you see fit. To finish this trivial example,

        @POST
    @Path("/file/multipart/upload")
    @Consumes({MediaType.MULTIPART_FORM_DATA})
    public Response uploadMultiPart(@Context ContainerRequestContext requestContext,
            @FormDataParam("file") InputStream fileInputStream,
            @FormDataParam("file") FormDataContentDisposition cdh,
            @FormDataParam("accountKey") String accountKey,
            @FormDataParam("account") String json)  {
        
    
        
        System.out.println(cdh.getFileName());
        System.out.println(cdh.getName());
        System.out.println(accountKey);
        
        try {
            Account account = Account.deserialize(json);
            System.out.println(account.getLocation());
            System.out.println(account.getName());
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return Response.ok().build();
        
    }
    

    How to call a method with a separate thread in Java?

    To achieve this with RxJava 2.x you can use:

    Completable.fromAction(this::dowork).subscribeOn(Schedulers.io().subscribe();
    

    The subscribeOn() method specifies which scheduler to run the action on - RxJava has several predefined schedulers, including Schedulers.io() which has a thread pool intended for I/O operations, and Schedulers.computation() which is intended for CPU intensive operations.

    Passing parameter via url to sql server reporting service

    Try passing multiple values via url:

    /ReportServer?%2fService+Specific+Reports%2fFilings%2fDrillDown%2f&StartDate=01/01/2010&EndDate=01/05/2010&statuses=1&statuses=2&rs%3AFormat=PDF
    

    This should work.

    jQuery Validation plugin: disable validation for specified submit buttons

    You can use the onsubmit:false option (see documentation) when wiring up validation which will not validate on submission of the form. And then in your asp:button add an OnClientClick= $('#aspnetForm').valid(); to explicitly check if form is valid.

    You could call this the opt-in model, instead of the opt-out described above.

    Note, I am also using jquery validation with ASP.NET WebForms. There are some issues to navigate but once you get through them, the user experience is very good.

    Loading/Downloading image from URL on Swift

    Kingfisher is one of the best library for load image into URL.

    Github URL - https://github.com/onevcat/Kingfisher

    // If you want to use Activity Indicator.
    imageview_pic.kf.indicatorType = .activity
    imageview_pic.kf.setImage(with: URL(string: "Give your url string"))
    
    // If you want to use custom placeholder image.
    imageview_pic.kf.setImage(with: URL(string: "Give your url string"), placeholder: UIImage(named: "placeholder image name"), options: nil, progressBlock: nil, completionHandler: nil)
    

    How to convert milliseconds into a readable date?

    No, you'll need to do it manually.

    _x000D_
    _x000D_
    function prettyDate(date) {_x000D_
      var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',_x000D_
                    'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];_x000D_
    _x000D_
      return months[date.getUTCMonth()] + ' ' + date.getUTCDate() + ', ' + date.getUTCFullYear();_x000D_
    }_x000D_
    _x000D_
    console.log(prettyDate(new Date(1324339200000)));
    _x000D_
    _x000D_
    _x000D_

    Append data frames together in a for loop

    You should try this:

    df_total = data.frame()
    for (i in 1:7){
        # vector output
        model <- #some processing
    
        # add vector to a dataframe
        df <- data.frame(model)
        df_total <- rbind(df_total,df)
    }
    

    How to determine when a Git branch was created?

    This is something that I came up with before I found this thread.

    git reflog show --date=local --all | sed 's!^.*refs/!refs/!' | grep '/master' | tail -1
    git reflog show --date=local --all | sed 's!^.*refs/!refs/!' | grep 'branch:'
    

    How to get the current time in milliseconds in C Programming

    There is no portable way to get resolution of less than a second in standard C So best you can do is, use the POSIX function gettimeofday().

    Making a UITableView scroll when text field is selected

    in viewdidload

    -(void)viewdidload{
    
    [super viewdidload];
    
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    }
    
        -(void)keyboardWillChange:(NSNotification*)sender{
    
            NSLog(@"keyboardwillchange sender %@",sender);
    
    float margin=0  // set your own topmargin
    
    
            CGFloat originY = [[sender.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
    
    
            if (originY >= self.view.frame.size.height){
    
                NSLog(@"keyboardclose");
    
    
    
                [tb_ setFrame:CGRectMake(0, margin, self.view.frame.size.width, self.view.frame.size.height-margin)];
    
            }else{
    
                NSLog(@"keyobard on");
    
                float adjustedHeight = self.view.frame.size.height - margin - (self.view.frame.size.height-originY);
    
                [tb_ setFrame:CGRectMake(0, margin, self.view.frame.size.width, adjustedHeight)];
            }
    
    
    
    
    
    
    
        }
    

    How can I programmatically get the MAC address of an iphone

    To create a uniqueString based on unique identifier of device in iOS 6:

    #import <AdSupport/ASIdentifierManager.h>
    
    NSString *uniqueString = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    NSLog(@"uniqueString: %@", uniqueString);
    

    How do I create a new class in IntelliJ without using the mouse?

    With Esc and Command + 1 you can navigate between project view and editor area - back and forward, in this way you can select the folder/location you need

    With Control +Option + N you can trigger New file menu and select whatever you need, class, interface, file, etc. This works in editor as well in project view and it relates to the current selected location

    // please consider that this is working with standard key mapping

    iOS for VirtualBox

    Additional to the above - the QEMU website has good documentation about setting up an ARM based emulator: http://qemu.weilnetz.de/qemu-doc.html#ARM-System-emulator

    Print commit message of a given commit in git

    I use shortlog for this:

    $ git shortlog master..
    Username (3):
          Write something
          Add something
          Bump to 1.3.8 
    

    TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

    I know this is a Old post, but i would like to share my solution. I have added "ReactiveFormsModule" in imports[] array to resolve this error

    Error: There is no directive with "exportAs" set to "ngForm" ("

    Fix:

    module.ts

    import {FormsModule, ReactiveFormsModule} from '@angular/forms'

     imports: [
        BrowserModule,
        FormsModule , 
        ReactiveFormsModule
      ],
    

    Learning Regular Expressions

    The most important part is the concepts. Once you understand how the building blocks work, differences in syntax amount to little more than mild dialects. A layer on top of your regular expression engine's syntax is the syntax of the programming language you're using. Languages such as Perl remove most of this complication, but you'll have to keep in mind other considerations if you're using regular expressions in a C program.

    If you think of regular expressions as building blocks that you can mix and match as you please, it helps you learn how to write and debug your own patterns but also how to understand patterns written by others.

    Start simple

    Conceptually, the simplest regular expressions are literal characters. The pattern N matches the character 'N'.

    Regular expressions next to each other match sequences. For example, the pattern Nick matches the sequence 'N' followed by 'i' followed by 'c' followed by 'k'.

    If you've ever used grep on Unix—even if only to search for ordinary looking strings—you've already been using regular expressions! (The re in grep refers to regular expressions.)

    Order from the menu

    Adding just a little complexity, you can match either 'Nick' or 'nick' with the pattern [Nn]ick. The part in square brackets is a character class, which means it matches exactly one of the enclosed characters. You can also use ranges in character classes, so [a-c] matches either 'a' or 'b' or 'c'.

    The pattern . is special: rather than matching a literal dot only, it matches any character. It's the same conceptually as the really big character class [-.?+%$A-Za-z0-9...].

    Think of character classes as menus: pick just one.

    Helpful shortcuts

    Using . can save you lots of typing, and there are other shortcuts for common patterns. Say you want to match a digit: one way to write that is [0-9]. Digits are a frequent match target, so you could instead use the shortcut \d. Others are \s (whitespace) and \w (word characters: alphanumerics or underscore).

    The uppercased variants are their complements, so \S matches any non-whitespace character, for example.

    Once is not enough

    From there, you can repeat parts of your pattern with quantifiers. For example, the pattern ab?c matches 'abc' or 'ac' because the ? quantifier makes the subpattern it modifies optional. Other quantifiers are

    • * (zero or more times)
    • + (one or more times)
    • {n} (exactly n times)
    • {n,} (at least n times)
    • {n,m} (at least n times but no more than m times)

    Putting some of these blocks together, the pattern [Nn]*ick matches all of

    • ick
    • Nick
    • nick
    • Nnick
    • nNick
    • nnick
    • (and so on)

    The first match demonstrates an important lesson: * always succeeds! Any pattern can match zero times.

    A few other useful examples:

    • [0-9]+ (and its equivalent \d+) matches any non-negative integer
    • \d{4}-\d{2}-\d{2} matches dates formatted like 2019-01-01

    Grouping

    A quantifier modifies the pattern to its immediate left. You might expect 0abc+0 to match '0abc0', '0abcabc0', and so forth, but the pattern immediately to the left of the plus quantifier is c. This means 0abc+0 matches '0abc0', '0abcc0', '0abccc0', and so on.

    To match one or more sequences of 'abc' with zeros on the ends, use 0(abc)+0. The parentheses denote a subpattern that can be quantified as a unit. It's also common for regular expression engines to save or "capture" the portion of the input text that matches a parenthesized group. Extracting bits this way is much more flexible and less error-prone than counting indices and substr.

    Alternation

    Earlier, we saw one way to match either 'Nick' or 'nick'. Another is with alternation as in Nick|nick. Remember that alternation includes everything to its left and everything to its right. Use grouping parentheses to limit the scope of |, e.g., (Nick|nick).

    For another example, you could equivalently write [a-c] as a|b|c, but this is likely to be suboptimal because many implementations assume alternatives will have lengths greater than 1.

    Escaping

    Although some characters match themselves, others have special meanings. The pattern \d+ doesn't match backslash followed by lowercase D followed by a plus sign: to get that, we'd use \\d\+. A backslash removes the special meaning from the following character.

    Greediness

    Regular expression quantifiers are greedy. This means they match as much text as they possibly can while allowing the entire pattern to match successfully.

    For example, say the input is

    "Hello," she said, "How are you?"

    You might expect ".+" to match only 'Hello,' and will then be surprised when you see that it matched from 'Hello' all the way through 'you?'.

    To switch from greedy to what you might think of as cautious, add an extra ? to the quantifier. Now you understand how \((.+?)\), the example from your question works. It matches the sequence of a literal left-parenthesis, followed by one or more characters, and terminated by a right-parenthesis.

    If your input is '(123) (456)', then the first capture will be '123'. Non-greedy quantifiers want to allow the rest of the pattern to start matching as soon as possible.

    (As to your confusion, I don't know of any regular-expression dialect where ((.+?)) would do the same thing. I suspect something got lost in transmission somewhere along the way.)

    Anchors

    Use the special pattern ^ to match only at the beginning of your input and $ to match only at the end. Making "bookends" with your patterns where you say, "I know what's at the front and back, but give me everything between" is a useful technique.

    Say you want to match comments of the form

    -- This is a comment --

    you'd write ^--\s+(.+)\s+--$.

    Build your own

    Regular expressions are recursive, so now that you understand these basic rules, you can combine them however you like.

    Tools for writing and debugging regexes:

    Books

    Free resources

    Footnote

    †: The statement above that . matches any character is a simplification for pedagogical purposes that is not strictly true. Dot matches any character except newline, "\n", but in practice you rarely expect a pattern such as .+ to cross a newline boundary. Perl regexes have a /s switch and Java Pattern.DOTALL, for example, to make . match any character at all. For languages that don't have such a feature, you can use something like [\s\S] to match "any whitespace or any non-whitespace", in other words anything.

    How to convert String to Date value in SAS?

    As stated above, the simple answer is:

    date = input(monyy,date9.);
    

    with the addition of:

    put date=yymmdd.;
    

    The reason why this works, and what you did doesn't, is because of a common misunderstanding in SAS. DATE9. is an INFORMAT. In an INPUT statement, it provides the SAS interpreter with a set of translation commands it can send to the compiler to turn your text into the right numbers, which will then look like a date once the right FORMAT is applied. FORMATs are just visible representations of numbers (or characters). So by using YYMMDD., you confused the INPUT function by handing it a FORMAT instead of an INFORMAT, and probably got a helpful error that said:

    Invalid argument to INPUT function at line... etc...
    

    Which told you absolutely nothing about what to do next.

    In summary, to represent your character date as a YYMMDD. In SAS you need to:

    1. change the INFORMAT - date = input(monyy,date9.);
    2. apply the FORMAT - put date=YYMMDD10.;

    How to configure Docker port mapping to use Nginx as an upstream proxy?

    @gdbj's answer is a great explanation and the most up to date answer. Here's however a simpler approach.

    So if you want to redirect all traffic from nginx listening to 80 to another container exposing 8080, minimum configuration can be as little as:

    nginx.conf:

    server {
        listen 80;
    
        location / {
            proxy_pass http://client:8080; # this one here
            proxy_redirect off;
        }
    
    }
    

    docker-compose.yml

    version: "2"
    services:
      entrypoint:
        image: some-image-with-nginx
        ports:
          - "80:80"
        links:
          - client  # will use this one here
    
      client:
        image: some-image-with-api
        ports:
          - "8080:8080"
    

    Docker docs

    Convert Pandas Series to DateTime in a DataFrame

    You can't: DataFrame columns are Series, by definition. That said, if you make the dtype (the type of all the elements) datetime-like, then you can access the quantities you want via the .dt accessor (docs):

    >>> df["TimeReviewed"] = pd.to_datetime(df["TimeReviewed"])
    >>> df["TimeReviewed"]
    205  76032930   2015-01-24 00:05:27.513000
    232  76032930   2015-01-24 00:06:46.703000
    233  76032930   2015-01-24 00:06:56.707000
    413  76032930   2015-01-24 00:14:24.957000
    565  76032930   2015-01-24 00:23:07.220000
    Name: TimeReviewed, dtype: datetime64[ns]
    >>> df["TimeReviewed"].dt
    <pandas.tseries.common.DatetimeProperties object at 0xb10da60c>
    >>> df["TimeReviewed"].dt.year
    205  76032930    2015
    232  76032930    2015
    233  76032930    2015
    413  76032930    2015
    565  76032930    2015
    dtype: int64
    >>> df["TimeReviewed"].dt.month
    205  76032930    1
    232  76032930    1
    233  76032930    1
    413  76032930    1
    565  76032930    1
    dtype: int64
    >>> df["TimeReviewed"].dt.minute
    205  76032930     5
    232  76032930     6
    233  76032930     6
    413  76032930    14
    565  76032930    23
    dtype: int64
    

    If you're stuck using an older version of pandas, you can always access the various elements manually (again, after converting it to a datetime-dtyped Series). It'll be slower, but sometimes that isn't an issue:

    >>> df["TimeReviewed"].apply(lambda x: x.year)
    205  76032930    2015
    232  76032930    2015
    233  76032930    2015
    413  76032930    2015
    565  76032930    2015
    Name: TimeReviewed, dtype: int64
    

    How to get all files under a specific directory in MATLAB?

    With little modification but almost similar approach to get the full file path of each sub folder

    dataFolderPath = 'UCR_TS_Archive_2015/';
    
    dirData = dir(dataFolderPath);      %# Get the data for the current directory
    dirIndex = [dirData.isdir];  %# Find the index for directories
    fileList = {dirData(~dirIndex).name}';  %'# Get a list of the files
    if ~isempty(fileList)
        fileList = cellfun(@(x) fullfile(dataFolderPath,x),...  %# Prepend path to files
            fileList,'UniformOutput',false);
    end
    subDirs = {dirData(dirIndex).name};  %# Get a list of the subdirectories
    validIndex = ~ismember(subDirs,{'.','..'});  %# Find index of subdirectories
    %#   that are not '.' or '..'
    for iDir = find(validIndex)                  %# Loop over valid subdirectories
        nextDir = fullfile(dataFolderPath,subDirs{iDir});    %# Get the subdirectory path
        getAllFiles = dir(nextDir);
        for k = 1:1:size(getAllFiles,1)
            validFileIndex = ~ismember(getAllFiles(k,1).name,{'.','..'});
            if(validFileIndex)
                filePathComplete = fullfile(nextDir,getAllFiles(k,1).name);
                fprintf('The Complete File Path: %s\n', filePathComplete);
            end
        end
    end  
    

    Get values from a listbox on a sheet

    To get the value of the selected item of a listbox then use the following.

    For Single Column ListBox: ListBox1.List(ListBox1.ListIndex)

    For Multi Column ListBox: ListBox1.Column(column_number, ListBox1.ListIndex)

    This avoids looping and is extremely more efficient.

    How do I use CMake?

    CMake (Cross platform make) is a build system generator. It doesn't build your source, instead, generates what a build system needs: the build scripts. Doing so you don't need to write or maintain platform specific build files. CMake uses relatively high level CMake language which usually written in CMakeLists.txt files. Your general workflow when consuming third party libraries usually boils down the following commands:

    cmake -S thelibrary -B build
    cmake --build build
    cmake --install build
    

    The first line known as configuration step, this generates the build files on your system. -S(ource) is the library source, and -B(uild) folder. CMake falls back to generate build according to your system. it will be MSBuild on Windows, GNU Makefiles on Linux. You can specify the build using -G(enerator) paramater, like:

    cmake -G Ninja -S libSource -B build
    

    end of the this step, generates build scripts, like Makefile, *.sln files etc. on build directory.

    The second line invokes the actual build command, it's like invoking make on the build folder.

    The third line install the library. If you're on Windows, you can quickly open generated project by, cmake --open build.

    Now you can use the installed library on your project with configured by CMake, writing your own CMakeLists.txt file. To do so, you'll need to create a your target and find the package you installed using find_package command, which will export the library target names, and link them against your own target.

    Splitting templated C++ classes into .hpp/.cpp files--is it possible?

    Only if you #include "stack.cpp at the end of stack.hpp. I'd only recommend this approach if the implementation is relatively large, and if you rename the .cpp file to another extension, as to differentiate it from regular code.

    Auto insert date and time in form input field?

    var date = new Date();
    
    document.getElementById("date").value = date.getFullYear() + "-" + (date.getMonth()<10?'0':'') + (date.getMonth() + 1) + "-" + (date.getDate()<10?'0':'') + date.getDate();
    
    document.getElementById("hour").value = (date.getHours()<10?'0':'') + date.getHours()  + ":" + (date.getMinutes()<10?'0':'') + date.getMinutes();
    

    Remove last commit from remote git repository

    If nobody has pulled it, you can probably do something like

    git push remote +branch^1:remotebranch
    

    which will forcibly update the remote branch to the last but one commit of your branch.

    Java - What does "\n" mean?

    \n 
    

    This means insert a newline in the text at this point.

    Just example

    System.out.println("hello\nworld");
    

    Output:

    hello
    world
    

    How do I calculate someone's age based on a DateTime type birthday?

    === Common Saying (from months to years old) ===

    If you just for common use, here is the code as your information:

    DateTime today = DateTime.Today;
    DateTime bday = DateTime.Parse("2016-2-14");
    int age = today.Year - bday.Year;
    var unit = "";
    
    if (bday > today.AddYears(-age))
    {
        age--;
    }
    if (age == 0)   // Under one year old
    {
        age = today.Month - bday.Month;
    
        age = age <= 0 ? (12 + age) : age;  // The next year before birthday
    
        age = today.Day - bday.Day >= 0 ? age : --age;  // Before the birthday.day
    
        unit = "month";
    }
    else {
        unit = "year";
    }
    
    if (age > 1)
    {
        unit = unit + "s";
    }
    

    The test result as below:

    The birthday: 2016-2-14
    
    2016-2-15 =>  age=0, unit=month;
    2016-5-13 =>  age=2, unit=months;
    2016-5-14 =>  age=3, unit=months; 
    2016-6-13 =>  age=3, unit=months; 
    2016-6-15 =>  age=4, unit=months; 
    2017-1-13 =>  age=10, unit=months; 
    2017-1-14 =>  age=11, unit=months; 
    2017-2-13 =>  age=11, unit=months; 
    2017-2-14 =>  age=1, unit=year; 
    2017-2-15 =>  age=1, unit=year; 
    2017-3-13 =>  age=1, unit=year;
    2018-1-13 =>  age=1, unit=year; 
    2018-1-14 =>  age=1, unit=year; 
    2018-2-13 =>  age=1, unit=year; 
    2018-2-14 =>  age=2, unit=years; 
    

    Which is best data type for phone number in MySQL and what should Java type mapping for it be?

    In MySQL -> INT(10) does not mean a 10-digit number, it means an integer with a display width of 10 digits. The maximum value for an INT in MySQL is 2147483647 (or 4294967295 if unsigned).

    You can use a BIGINT instead of INT to store it as a numeric. Using BIGINT will save you 3 bytes per row over VARCHAR(10).

    If you want to Store "Country + area + number separately". Try using a VARCHAR(20). This allows you the ability to store international phone numbers properly, should that need arise.

    Composer update memory limit

    The best solution for me is

    COMPOSER_MEMORY_LIMIT=-1 composer require <package-name>
    

    mentioned by @realtebo

    Parsing Query String in node.js

    There's also the QueryString module's parse() method:

    var http = require('http'),
        queryString = require('querystring');
    
    http.createServer(function (oRequest, oResponse) {
    
        var oQueryParams;
    
        // get query params as object
        if (oRequest.url.indexOf('?') >= 0) {
            oQueryParams = queryString.parse(oRequest.url.replace(/^.*\?/, ''));
    
            // do stuff
            console.log(oQueryParams);
        }
    
        oResponse.writeHead(200, {'Content-Type': 'text/plain'});
        oResponse.end('Hello world.');
    
    }).listen(1337, '127.0.0.1');
    

    Curl Command to Repeat URL Request

    If you want to add an interval before executing the cron the next time you can add a sleep

    for i in {1..100}; do echo $i && curl "http://URL" >> /tmp/output.log && sleep 120; done

    Spring Boot REST service exception handling

    New answer (2016-04-20)

    Using Spring Boot 1.3.1.RELEASE

    New Step 1 - It is easy and less intrusive to add the following properties to the application.properties:

    spring.mvc.throw-exception-if-no-handler-found=true
    spring.resources.add-mappings=false
    

    Much easier than modifying the existing DispatcherServlet instance (as below)! - JO'

    If working with a full RESTful Application, it is very important to disable the automatic mapping of static resources since if you are using Spring Boot's default configuration for handling static resources then the resource handler will be handling the request (it's ordered last and mapped to /** which means that it picks up any requests that haven't been handled by any other handler in the application) so the dispatcher servlet doesn't get a chance to throw an exception.


    New Answer (2015-12-04)

    Using Spring Boot 1.2.7.RELEASE

    New Step 1 - I found a much less intrusive way of setting the "throExceptionIfNoHandlerFound" flag. Replace the DispatcherServlet replacement code below (Step 1) with this in your application initialization class:

    @ComponentScan()
    @EnableAutoConfiguration
    public class MyApplication extends SpringBootServletInitializer {
        private static Logger LOG = LoggerFactory.getLogger(MyApplication.class);
        public static void main(String[] args) {
            ApplicationContext ctx = SpringApplication.run(MyApplication.class, args);
            DispatcherServlet dispatcherServlet = (DispatcherServlet)ctx.getBean("dispatcherServlet");
            dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
        }
    

    In this case, we're setting the flag on the existing DispatcherServlet, which preserves any auto-configuration by the Spring Boot framework.

    One more thing I've found - the @EnableWebMvc annotation is deadly to Spring Boot. Yes, that annotation enables things like being able to catch all the controller exceptions as described below, but it also kills a LOT of the helpful auto-configuration that Spring Boot would normally provide. Use that annotation with extreme caution when you use Spring Boot.


    Original Answer:

    After a lot more research and following up on the solutions posted here (thanks for the help!) and no small amount of runtime tracing into the Spring code, I finally found a configuration that will handle all Exceptions (not Errors, but read on) including 404s.

    Step 1 - tell SpringBoot to stop using MVC for "handler not found" situations. We want Spring to throw an exception instead of returning to the client a view redirect to "/error". To do this, you need to have an entry in one of your configuration classes:

    // NEW CODE ABOVE REPLACES THIS! (2015-12-04)
    @Configuration
    public class MyAppConfig {
        @Bean  // Magic entry 
        public DispatcherServlet dispatcherServlet() {
            DispatcherServlet ds = new DispatcherServlet();
            ds.setThrowExceptionIfNoHandlerFound(true);
            return ds;
        }
    }
    

    The downside of this is that it replaces the default dispatcher servlet. This hasn't been a problem for us yet, with no side effects or execution problems showing up. If you're going to do anything else with the dispatcher servlet for other reasons, this is the place to do them.

    Step 2 - Now that spring boot will throw an exception when no handler is found, that exception can be handled with any others in a unified exception handler:

    @EnableWebMvc
    @ControllerAdvice
    public class ServiceExceptionHandler extends ResponseEntityExceptionHandler {
    
        @ExceptionHandler(Throwable.class)
        @ResponseBody
        ResponseEntity<Object> handleControllerException(HttpServletRequest req, Throwable ex) {
            ErrorResponse errorResponse = new ErrorResponse(ex);
            if(ex instanceof ServiceException) {
                errorResponse.setDetails(((ServiceException)ex).getDetails());
            }
            if(ex instanceof ServiceHttpException) {
                return new ResponseEntity<Object>(errorResponse,((ServiceHttpException)ex).getStatus());
            } else {
                return new ResponseEntity<Object>(errorResponse,HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
    
        @Override
        protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
            Map<String,String> responseBody = new HashMap<>();
            responseBody.put("path",request.getContextPath());
            responseBody.put("message","The URL you have reached is not in service at this time (404).");
            return new ResponseEntity<Object>(responseBody,HttpStatus.NOT_FOUND);
        }
        ...
    }
    

    Keep in mind that I think the "@EnableWebMvc" annotation is significant here. It seems that none of this works without it. And that's it - your Spring boot app will now catch all exceptions, including 404s, in the above handler class and you may do with them as you please.

    One last point - there doesn't seem to be a way to get this to catch thrown Errors. I have a wacky idea of using aspects to catch errors and turn them into Exceptions that the above code can then deal with, but I have not yet had time to actually try implementing that. Hope this helps someone.

    Any comments/corrections/enhancements will be appreciated.

    Spring 3 RequestMapping: Get path value

    Non-matched part of the URL is exposed as a request attribute named HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE:

    @RequestMapping("/{id}/**")
    public void foo(@PathVariable("id") int id, HttpServletRequest request) {
        String restOfTheUrl = (String) request.getAttribute(
            HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        ...
    }
    

    How to add Active Directory user group as login in SQL Server

    Go to the SQL Server Management Studio, navigate to Security, go to Logins and right click it. A Menu will come up with a button saying "New Login". There you will be able to add users and/or groups from Active Directory to your SQL Server "permissions". Hope this helps

    What does <? php echo ("<pre>"); ..... echo("</pre>"); ?> mean?

    "<pre>" is an HTML tag. If you insert this line of code in your program

    echo "<pre>";

    then you will enable the viewing of multiple spaces and line endings. Without this, all \n, \r and other end line characters wouldn't have any effect in the browser and wherever you had more than 1 space in the code, the output would be shortened to only 1 space. That's the default HTML. In that case only with <br> you would be able to break the line and go to the next one.

    For example,

    the code below would be displayed on multiple lines, due to \n line ending specifier.

    <?php
        echo "<pre>";
        printf("<span style='color:#%X%X%X'>Hello</span>\n", 65, 127, 245);
        printf("Goodbye");
    ?>
    

    However the following code, would be displayed in one line only (line endings are disregarded).

    <?php
        printf("<span style='color:#%X%X%X'>Hello</span>\n", 65, 127, 245);
        printf("Goodbye");
    ?>
    

    Input and output numpy arrays to h5py

    A cleaner way to handle file open/close and avoid memory leaks:

    Prep:

    import numpy as np
    import h5py
    
    data_to_write = np.random.random(size=(100,20)) # or some such
    

    Write:

    with h5py.File('name-of-file.h5', 'w') as hf:
        hf.create_dataset("name-of-dataset",  data=data_to_write)
    

    Read:

    with h5py.File('name-of-file.h5', 'r') as hf:
        data = hf['name-of-dataset'][:]
    

    Java: parse int value from a char

    Using binary AND with 0b1111:

    String element = "el5";
    
    char c = element.charAt(2);
    
    System.out.println(c & 0b1111); // => '5' & 0b1111 => 0b0011_0101 & 0b0000_1111 => 5
    
    // '0' & 0b1111 => 0b0011_0000 & 0b0000_1111 => 0
    // '1' & 0b1111 => 0b0011_0001 & 0b0000_1111 => 1
    // '2' & 0b1111 => 0b0011_0010 & 0b0000_1111 => 2
    // '3' & 0b1111 => 0b0011_0011 & 0b0000_1111 => 3
    // '4' & 0b1111 => 0b0011_0100 & 0b0000_1111 => 4
    // '5' & 0b1111 => 0b0011_0101 & 0b0000_1111 => 5
    // '6' & 0b1111 => 0b0011_0110 & 0b0000_1111 => 6
    // '7' & 0b1111 => 0b0011_0111 & 0b0000_1111 => 7
    // '8' & 0b1111 => 0b0011_1000 & 0b0000_1111 => 8
    // '9' & 0b1111 => 0b0011_1001 & 0b0000_1111 => 9
    

    How to convert int to NSString?

    NSString *string = [NSString stringWithFormat:@"%d", theinteger];
    

    How do you change the value inside of a textfield flutter?

    _mytexteditingcontroller.value = new TextEditingController.fromValue(new TextEditingValue(text: "My String")).value;
    

    This seems to work if anyone has a better way please feel free to let me know.

    How do I kill this tomcat process in Terminal?

    As others already noted, you have seen the grep process. If you want to restrict the output to tomcat itself, you have two alternatives

    • wrap the first searched character in a character class

      ps -ef | grep '[t]omcat'
      

      This searches for tomcat too, but misses the grep [t]omcat entry, because it isn't matched by [t]omcat.

    • use a custom output format with ps

      ps -e -o pid,comm | grep tomcat
      

      This shows only the pid and the name of the process without the process arguments. So, grep is listed as grep and not as grep tomcat.

    Maven Unable to locate the Javac Compiler in:

    For Intellij Idea set everything appropriately (similarly to this):

    JAVA_HOME = C:\Program Files\Java\jdk1.8.0_60
    JRE_HOME = JAVA_HOME\jre
    

    and dont forget to restart Idea. This program picks up variables at start so any changes to environtment variables while the program is running will not have any effect.

    Authorize attribute in ASP.NET MVC

    The tag in web.config is based on paths, whereas MVC works with controller actions and routes.

    It is an architectural decision that might not make a lot of difference if you just want to prevent users that aren't logged in but makes a lot of difference when you try to apply authorization based in Roles and in cases that you want custom handling of types of Unauthorized.

    The first case is covered from the answer of BobRock.

    The user should have at least one of the following Roles to access the Controller or the Action

    [Authorize(Roles = "Admin, Super User")]
    

    The user should have both these roles in order to be able to access the Controller or Action

    [Authorize(Roles = "Super User")]
    [Authorize(Roles = "Admin")]
    

    The users that can access the Controller or the Action are Betty and Johnny

    [Authorize(Users = "Betty, Johnny")]
    

    In ASP.NET Core you can use Claims and Policy principles for authorization through [Authorize].

    options.AddPolicy("ElevatedRights", policy =>
                      policy.RequireRole("Administrator", "PowerUser", "BackupAdministrator"));
    
    [Authorize(Policy = "ElevatedRights")]
    

    The second comes very handy in bigger applications where Authorization might need to be implemented with different restrictions, process and handling according to the case. For this reason we can Extend the AuthorizeAttribute and implement different authorization alternatives for our project.

    public class CustomAuthorizeAttribute: AuthorizeAttribute  
    {  
        public override void OnAuthorization(AuthorizationContext filterContext)  
        {  }
    }
    

    The "correct-completed" way to do authorization in ASP.NET MVC is using the [Authorize] attribute.

    How to stash my previous commit?

    It's works for me;

    1. Checkout on commit that is a origin of current branch.
    2. Create new branch from this commit.
    3. Checkout to new branch.
    4. Merge branch with code for stash in new branch.
    5. Make soft reset in new branch.
    6. Stash your target code.
    7. Remove new branch.

    I recommend use something like a SourceTree for this.

    How to properly set the 100% DIV height to match document/window height?

    simplest way i found is viewport-height in css..

    div {height: 100vh;}
    

    this takes the viewport-height of the browser-window and updates it during resizes.

    see "can i use" for browser compatibility list

    Reading specific columns from a text file in python

    First of all we open the file and as datafile then we apply .read() method reads the file contents and then we split the data which returns something like: ['5', '10', '6', '6', '20', '1', '7', '30', '4', '8', '40', '3', '9', '23', '1', '4', '13', '6'] and the we applied list slicing on this list to start from the element at index position 1 and skip next 3 elements untill it hits the end of the loop.

    with open("sample.txt", "r") as datafile:
        print datafile.read().split()[1::3]
    

    Output:

    ['10', '20', '30', '40', '23', '13']
    

    Get HTML code from website in C#

    Best thing to use is HTMLAgilityPack. You can also look into using Fizzler or CSQuery depending on your needs for selecting the elements from the retrieved page. Using LINQ or Regukar Expressions is just to error prone, especially when the HTML can be malformed, missing closing tags, have nested child elements etc.

    You need to stream the page into an HtmlDocument object and then select your required element.

    // Call the page and get the generated HTML
    var doc = new HtmlAgilityPack.HtmlDocument();
    HtmlAgilityPack.HtmlNode.ElementsFlags["br"] = HtmlAgilityPack.HtmlElementFlag.Empty;
    doc.OptionWriteEmptyNodes = true;
    
    try
    {
        var webRequest = HttpWebRequest.Create(pageUrl);
        Stream stream = webRequest.GetResponse().GetResponseStream();
        doc.Load(stream);
        stream.Close();
    }
    catch (System.UriFormatException uex)
    {
        Log.Fatal("There was an error in the format of the url: " + itemUrl, uex);
        throw;
    }
    catch (System.Net.WebException wex)
    {
        Log.Fatal("There was an error connecting to the url: " + itemUrl, wex);
        throw;
    }
    
    //get the div by id and then get the inner text 
    string testDivSelector = "//div[@id='test']";
    var divString = doc.DocumentNode.SelectSingleNode(testDivSelector).InnerHtml.ToString();
    

    [EDIT] Actually, scrap that. The simplest method is to use FizzlerEx, an updated jQuery/CSS3-selectors implementation of the original Fizzler project.

    Code sample directly from their site:

    using HtmlAgilityPack;
    using Fizzler.Systems.HtmlAgilityPack;
    
    //get the page
    var web = new HtmlWeb();
    var document = web.Load("http://example.com/page.html");
    var page = document.DocumentNode;
    
    //loop through all div tags with item css class
    foreach(var item in page.QuerySelectorAll("div.item"))
    {
        var title = item.QuerySelector("h3:not(.share)").InnerText;
        var date = DateTime.Parse(item.QuerySelector("span:eq(2)").InnerText);
        var description = item.QuerySelector("span:has(b)").InnerHtml;
    }
    

    I don't think it can get any simpler than that.

    How to make an embedded video not autoplay

    I had the same problem and came across this post. Nothing worked. After randomly playing around, I found that <embed ........ play="false"> stopped it from playing automatically. I now have the problem that I can't get a controller to appear, so can't start the movie! :S

    jquery data selector

    If you also use jQueryUI, you get a (simple) version of the :data selector with it that checks for the presence of a data item, so you can do something like $("div:data(view)"), or $( this ).closest(":data(view)").

    See http://api.jqueryui.com/data-selector/ . I don't know for how long they've had it, but it's there now!

    Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

    Try using unbindService() in OnUserLeaveHint(). It prevents the the ServiceConnection leaked scenario and other exceptions.
    I used it in my code and works fine.

    How do I use NSTimer?

    #import "MyViewController.h"
    
    @interface MyViewController ()
    
    @property (strong, nonatomic) NSTimer *timer;
    
    @end
    
    @implementation MyViewController
    
    double timerInterval = 1.0f;
    
    - (NSTimer *) timer {
        if (!_timer) {
            _timer = [NSTimer timerWithTimeInterval:timerInterval target:self selector:@selector(onTick:) userInfo:nil repeats:YES];
        }
        return _timer;
    }
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    }
    
    -(void)onTick:(NSTimer*)timer
    {
        NSLog(@"Tick...");
    }
    
    @end
    

    Is there a program to decompile Delphi?

    Here's a list : http://delphi.about.com/od/devutilities/a/decompiling_3.htm (and this page mentions some more : http://www.program-transformation.org/Transform/DelphiDecompilers )

    I've used DeDe on occasion, but it's not really all that powerfull, and it's not up-to-date with current Delphi versions (latest version it supports is Delphi 7 I believe)

    Android Get Current timestamp?

    java.time

    I should like to contribute the modern answer.

        String ts = String.valueOf(Instant.now().getEpochSecond());
        System.out.println(ts);
    

    Output when running just now:

    1543320466

    While division by 1000 won’t come as a surprise to many, doing your own time conversions can get hard to read pretty fast, so it’s a bad habit to get into when you can avoid it.

    The Instant class that I am using is part of java.time, the modern Java date and time API. It’s built-in on new Android versions, API level 26 and up. If you are programming for older Android, you may get the backport, see below. If you don’t want to do that, understandably, I’d still use a built-in conversion:

        String ts = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));
        System.out.println(ts);
    

    This is the same as the answer by sealskej. Output is the same as before.

    Question: Can I use java.time on Android?

    Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

    • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
    • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
    • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

    Links

    ArrayList or List declaration in Java

    The first declaration has to be an ArrayList, the second can be easily changed to another List type. As such, the second is preferred as it make it clear you don't require a specific implementation. (Sometimes you really do need one implementation, but that is rare)

    View tabular file such as CSV from command line

    There's this short command line script in python: https://github.com/rgrp/csv2ascii/blob/master/csv2ascii.py

    Just download and place in your path. Usage is like

    csv2ascii.py [options] csv-file-path
    

    Convert csv file at csv-file-path to ascii form returning the result on stdout. If csv-file-path = '-' then read from stdin.

    Options:

      -h, --help            show this help message and exit
      -w WIDTH, --width=WIDTH
                            Width of ascii output
      -c COLUMNS, --columns=COLUMNS
                            Only display this number of columns
    

    Enter export password to generate a P12 certificate

    MacOS High Sierra is very crazy to update openssl command suddenly.

    Possible in last month:

    $ openssl pkcs12 -in cert.p12 -out cert.pem -nodes -clcerts
    MAC verified OK
    

    But now:

    $ openssl pkcs12 -in cert.p12 -out cert.pem -nodes -clcerts -password pass:
    MAC verified OK
    

    ASP.NET MVC Bundle not rendering script files on staging server. It works on development server

    I ran into the same problem, and I'm not sure why, but it turned out to be that the script link generated by Scripts.Render did not have a .js extension. Because it also does not have a Type attribute the browser was just unable to use it (chrome and firefox).

    To resolve this, I changed my bundle configuration to generate compiled files with a js extension, e.g.

                var coreScripts = new ScriptBundle("~/bundles/coreAssets.js")
                .Include("~/scripts/jquery.js");
    
            var coreStyles = new StyleBundle("~/bundles/coreStyles.css")
                .Include("~/css/bootstrap.css");
    

    Notice in new StyleBundle(... instead of saying ~/bundles/someBundle, I am saying ~/bundlers/someBundle.js or ~/bundles/someStyles.css..

    This causes the link generated in the src attribute to have .js or .css on it when optimizations are enabled, as such the browsers know based on the file extension what mime/type to use on the get request and everything works.

    If I take off the extension, everything breaks. That's because @Scripts and @Styles doesn't render all the necessary attributes to understand a src to a file with no extension.

    Using psql to connect to PostgreSQL in SSL mode

    psql "sslmode=require host=localhost port=2345 dbname=postgres" --username=some_user

    According to the postgres psql documentation, only the connection parameters should go in the conninfo string(that's why in our example, --username is not inside that string)

    How to add two edit text fields in an alert dialog

     LayoutInflater factory = LayoutInflater.from(this);
    final View textEntryView = factory.inflate(R.layout.text_entry, null);
    //text_entry is an Layout XML file containing two text field to display in alert dialog
    final EditText input1 = (EditText) textEntryView.findViewById(R.id.EditText1);
    final EditText input2 = (EditText) textEntryView.findViewById(R.id.EditText2);             
    input1.setText("DefaultValue", TextView.BufferType.EDITABLE);
    input2.setText("DefaultValue", TextView.BufferType.EDITABLE);
    final AlertDialog.Builder alert = new AlertDialog.Builder(this);
    
    alert.setIcon(R.drawable.icon)
         .setTitle("Enter the Text:")
         .setView(textEntryView)
         .setPositiveButton("Save", 
             new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int whichButton) {
                        Log.i("AlertDialog","TextEntry 1 Entered "+input1.getText().toString());
                        Log.i("AlertDialog","TextEntry 2 Entered "+input2.getText().toString());
                        /* User clicked OK so do some stuff */
                 }
             })
         .setNegativeButton("Cancel",
             new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog,
                        int whichButton) {
                 }
             });
    alert.show();
    

    Set Icon Image in Java

    Your problem is often due to looking in the wrong place for the image, or if your classes and images are in a jar file, then looking for files where files don't exist. I suggest that you use resources to get rid of the second problem.

    e.g.,

    // the path must be relative to your *class* files
    String imagePath = "res/Image.png";
    InputStream imgStream = Game.class.getResourceAsStream(imagePath );
    BufferedImage myImg = ImageIO.read(imgStream);
    // ImageIcon icon = new ImageIcon(myImg);
    
    // use icon here
    game.frame.setIconImage(myImg);
    

    How to retrieve an element from a set without removing it?

    Least code would be:

    >>> s = set([1, 2, 3])
    >>> list(s)[0]
    1
    

    Obviously this would create a new list which contains each member of the set, so not great if your set is very large.

    How to uninstall downloaded Xcode simulator?

    NOTE: This will only remove a device configuration from the Xcode devices list. To remove the simulator files from your hard drive see the previous answer.

    For Xcode 7 just use Window \ Devices menu in Xcode:

    Devices menu

    Then select emulator to delete in the list on the left side and right click on it. Here is Delete option: enter image description here

    That's all.

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

    Select the text, right click on the selection, and select the option "command palette":

    Enter image description here

    A new window opens. Search for "format" and select the option which has formatting as per the requirement.

    Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

    Take a look on your running processes, it seems like your current Tomcat instance did not stop. It's still running and NetBeans tries to start a second Tomcat-instance. Thats the reason for your exception, you just have to stop the first instance, or deploy you code on the current running one

    Delete a single record from Entity Framework?

        [HttpPost]
        public JsonResult DeleteCotnact(int id)
        {
            using (MycasedbEntities dbde = new MycasedbEntities())
            {
                Contact rowcontact = (from c in dbde.Contact
                                         where c.Id == id
                                         select c).FirstOrDefault();
    
                dbde.Contact.Remove(rowcontact);
                dbde.SaveChanges();
    
                return Json(id);
            }
        }
    

    What do you think of this, simple or not, you could also try this:

            var productrow = cnn.Product.Find(id);
            cnn.Product.Remove(productrow);
            cnn.SaveChanges();
    

    Write a mode method in Java to find the most frequently occurring element in an array

    I would use this code. It includes an instancesOf function, and it runs through each number.

    public class MathFunctions {
    
    public static int mode(final int[] n) {
        int maxKey = 0;
        int maxCounts = 0;
    
        for (int i : n) {
            if (instancesOf(i, n) > maxCounts) {
                maxCounts = instancesOf(i, n);
                maxKey = i;
            }
        }
    
        return maxKey;
    }
    
    public static int instancesOf(int n, int[] Array) {
        int occurences = 0;
        for (int j : Array) {
            occurences += j == n ? 1 : 0;
        }
        return occurences;
    }
    
    public static void main (String[] args) {
        //TODO Auto-generated method stub
        System.out.println(mode(new int[] {100,200,2,300,300,300,500}));
    }
    }
    

    I noticed that the code Gubatron posted doesn't work on my computer; it gave me an ArrayIndexOutOfBoundsException.

    Javamail Could not convert socket to TLS GMail

    The first answer from @carlos worked for me:

    session.getProperties().put("mail.smtp.ssl.trust", "smtp.gmail.com");
    

    I have tested the property below and worked perfectly for me too:

    session.getProperties().put("mail.smtp.starttls.enable", "true");
    

    The two properties alone solved this type of problem, but by guarantee I used both.