Programs & Examples On #Minicpan

Selected tab's color in Bottom Navigation View

If you want to change icons' and texts' colors programmatically:

ColorStateList iconsColorStates = new ColorStateList(
            new int[][]{
                    new int[]{-android.R.attr.state_checked},
                    new int[]{android.R.attr.state_checked}
            },
            new int[]{
                    Color.parseColor("#123456"),
                    Color.parseColor("#654321")
            });

    ColorStateList textColorStates = new ColorStateList(
            new int[][]{
                    new int[]{-android.R.attr.state_checked},
                    new int[]{android.R.attr.state_checked}
            },
            new int[]{
                    Color.parseColor("#123456"),
                    Color.parseColor("#654321")
            });

    navigation.setItemIconTintList(iconsColorStates);
    navigation.setItemTextColor(textColorStates);

Check if property has attribute

You can use the Attribute.IsDefined method

https://msdn.microsoft.com/en-us/library/system.attribute.isdefined(v=vs.110).aspx

if(Attribute.IsDefined(YourProperty,typeof(YourAttribute)))
{
    //Conditional execution...
}

You could provide the property you're specifically looking for or you could iterate through all of them using reflection, something like:

PropertyInfo[] props = typeof(YourClass).GetProperties();

What does enumerate() mean?

As other users have mentioned, enumerate is a generator that adds an incremental index next to each item of an iterable.

So if you have a list say l = ["test_1", "test_2", "test_3"], the list(enumerate(l)) will give you something like this: [(0, 'test_1'), (1, 'test_2'), (2, 'test_3')].

Now, when this is useful? A possible use case is when you want to iterate over items, and you want to skip a specific item that you only know its index in the list but not its value (because its value is not known at the time).

for index, value in enumerate(joint_values):
   if index == 3:
       continue

   # Do something with the other `value`

So your code reads better because you could also do a regular for loop with range but then to access the items you need to index them (i.e., joint_values[i]).

Although another user mentioned an implementation of enumerate using zip, I think a more pure (but slightly more complex) way without using itertools is the following:

def enumerate(l, start=0):
    return zip(range(start, len(l) + start), l)

Example:

l = ["test_1", "test_2", "test_3"]
enumerate(l)
enumerate(l, 10)

Output:

[(0, 'test_1'), (1, 'test_2'), (2, 'test_3')]

[(10, 'test_1'), (11, 'test_2'), (12, 'test_3')]

As mentioned in the comments, this approach with range will not work with arbitrary iterables as the original enumerate function does.

How to perform a real time search and filter on a HTML table

I created these examples.

Simple indexOf search

var $rows = $('#table tr');
$('#search').keyup(function() {
    var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();

    $rows.show().filter(function() {
        var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
        return !~text.indexOf(val);
    }).hide();
});

Demo: http://jsfiddle.net/7BUmG/2/

Regular expression search

More advanced functionality using regular expressions will allow you to search words in any order in the row. It will work the same if you type apple green or green apple:

var $rows = $('#table tr');
$('#search').keyup(function() {

    var val = '^(?=.*\\b' + $.trim($(this).val()).split(/\s+/).join('\\b)(?=.*\\b') + ').*$',
        reg = RegExp(val, 'i'),
        text;

    $rows.show().filter(function() {
        text = $(this).text().replace(/\s+/g, ' ');
        return !reg.test(text);
    }).hide();
});

Demo: http://jsfiddle.net/dfsq/7BUmG/1133/

Debounce

When you implement table filtering with search over multiple rows and columns it is very important that you consider performance and search speed/optimisation. Simply saying you should not run search function on every single keystroke, it's not necessary. To prevent filtering to run too often you should debounce it. Above code example will become:

$('#search').keyup(debounce(function() {
    var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
    // etc...
}, 300));

You can pick any debounce implementation, for example from Lodash _.debounce, or you can use something very simple like I use in next demos (debounce from here): http://jsfiddle.net/7BUmG/6230/ and http://jsfiddle.net/7BUmG/6231/.

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

Pretty-print an entire Pandas Series / DataFrame

Try using display() function. This would automatically use Horizontal and vertical scroll bars and with this you can display different datasets easily instead of using print().

display(dataframe)

display() supports proper alignment also.

However if you want to make the dataset more beautiful you can check pd.option_context(). It has lot of options to clearly show the dataframe.

Note - I am using Jupyter Notebooks.

Regular expression to detect semi-colon terminated C++ for & while loops

This is a great example of using the wrong tool for the job. Regular expressions do not handle arbitrarily nested sub-matches very well. What you should do instead is use a real lexer and parser (a grammar for C++ should be easy to find) and look for unexpectedly empty loop bodies.

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

A subtle problem causing even print to fail is having your environment variables set wrong, eg. here LC_ALL set to "C". In Debian they discourage setting it: Debian wiki on Locale

$ echo $LANG
en_US.utf8
$ echo $LC_ALL 
C
$ python -c "print (u'voil\u00e0')"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe0' in position 4: ordinal not in range(128)
$ export LC_ALL='en_US.utf8'
$ python -c "print (u'voil\u00e0')"
voilà
$ unset LC_ALL
$ python -c "print (u'voil\u00e0')"
voilà

Query to select data between two dates with the format m/d/yyyy

$Date3 = date('y-m-d');
$Date2 = date('y-m-d', strtotime("-7 days"));
SELECT * FROM disaster WHERE date BETWEEN '".$Date2."' AND  '".$Date3."'

Get all column names of a DataTable into string array using (LINQ/Predicate)

I'd suggest using such extension method:

public static class DataColumnCollectionExtensions
{
    public static IEnumerable<DataColumn> AsEnumerable(this DataColumnCollection source)
    {
        return source.Cast<DataColumn>();
    }
}

And therefore:

string[] columnNames = dataTable.Columns.AsEnumerable().Select(column => column.Name).ToArray();

You may also implement one more extension method for DataTable class to reduce code:

public static class DataTableExtensions
{
    public static IEnumerable<DataColumn> GetColumns(this DataTable source)
    {
        return source.Columns.AsEnumerable();
    }
}

And use it as follows:

string[] columnNames = dataTable.GetColumns().Select(column => column.Name).ToArray();

Comparing two .jar files

  1. Rename .jar to .zip
  2. Extract
  3. Decompile class files with jad
  4. Recursive diff

When to use Task.Delay, when to use Thread.Sleep?

if the current thread is killed and you use Thread.Sleep and it is executing then you might get a ThreadAbortException. With Task.Delay you can always provide a cancellation token and gracefully kill it. Thats one reason I would choose Task.Delay. see http://social.technet.microsoft.com/wiki/contents/articles/21177.visual-c-thread-sleep-vs-task-delay.aspx

I also agree efficiency is not paramount in this case.

How can I get the session object if I have the entity-manager?

This will explain better.

EntityManager em = new JPAUtil().getEntityManager();
Session session = em.unwrap(Session.class);
Criteria c = session.createCriteria(Name.class);

Where to find 64 bit version of chromedriver.exe for Selenium WebDriver?

Windows 8 64bit runs both 32bit and 64bit applications. You want chromedriver 32bit for the 32bit version of chrome you're using.

The current release of chromedriver (v2.16) has been mentioned as running much smoother since it's older versions (there were a lot of issues before). This post mentions this and some of the slight differences between chromedriver and running the normal firefox driver:

http://seleniumsimplified.com/2015/07/recent-course-source-code-changes-for-webdriver-2-46-0/

What you mentioned about "doesn't call main method" is an odd remark. You may want to elaborate.

Python Traceback (most recent call last)

You are using Python 2 for which the input() function tries to evaluate the expression entered. Because you enter a string, Python treats it as a name and tries to evaluate it. If there is no variable defined with that name you will get a NameError exception.

To fix the problem, in Python 2, you can use raw_input(). This returns the string entered by the user and does not attempt to evaluate it.

Note that if you were using Python 3, input() behaves the same as raw_input() does in Python 2.

SELECT list is not in GROUP BY clause and contains nonaggregated column

As @Brian Riley already said you should either remove 1 column in your select

select countrylanguage.language ,sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language
order by sum(country.population*countrylanguage.percentage) desc ;

or add it to your grouping

select countrylanguage.language, country.code, sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language, country.code
order by sum(country.population*countrylanguage.percentage) desc ;

How to download excel (.xls) file from API in postman?

In postman - Have you tried adding the header element 'Accept' as 'application/vnd.ms-excel'

Code coverage with Mocha

Now (2021) the preferred way to use istanbul is via its "state of the art command line interface" nyc.

Setup

First, install it in your project with

npm i nyc --save-dev

Then, if you have a npm based project, just change the test script inside the scripts object of your package.json file to execute code coverage of your mocha tests:

{
  "scripts": {
    "test": "nyc --reporter=text mocha"
  }
}

Run

Now run your tests

npm test

and you will see a table like this in your console, just after your tests output:

Istanbul Nyc Mocha code coverage

Customization

Html report

Just use

nyc --reporter=html

instead of text. Now it will produce a report inside ./coverage/index.html.

Report formats

Istanbul supports a wide range of report formats. Just look at its reports library to find the most useful for you. Just add a --reporter=REPORTER_NAME option for each format you want. For example, with

nyc --reporter=html --reporter=text

you will have both the console and the html report.

Don't run coverage with npm test

Just add another script in your package.json and leave the test script with only your test runner (e.g. mocha):

{
  "scripts": {
    "test": "mocha",
    "test-with-coverage": "nyc --reporter=text mocha"
  }
}

Now run this custom script

npm run test-with-coverage

to run tests with code coverage.

Force test failing if code coverage is low

Fail if the total code coverage is below 90%:

nyc --check-coverage --lines 90 

Fail if the code coverage of at least one file is below 90%:

nyc --check-coverage --lines 90 --per-file

Getting the current Fragment instance in the viewpager

To get current fragment - get position in ViewPager at public void onPageSelected(final int position), and then

public PlaceholderFragment getFragmentByPosition(Integer pos){
    for(Fragment f:getChildFragmentManager().getFragments()){
        if(f.getId()==R.viewpager && f.getArguments().getInt("SECTNUM") - 1 == pos) {
            return (PlaceholderFragment) f;
        }
    }
    return null;
}

SECTNUM - position argument assigned in public static PlaceholderFragment newInstance(int sectionNumber); of Fragment

getChildFragmentManager() or getFragmentManager() - depends on how created SectionsPagerAdapter

Peak detection in a 2D array

Perhaps you can use something like Gaussian Mixture Models. Here's a Python package for doing GMMs (just did a Google search) http://www.ar.media.kyoto-u.ac.jp/members/david/softwares/em/

What can lead to "IOError: [Errno 9] Bad file descriptor" during os.system()?

You can get this error if you use wrong mode when opening the file. For example:

    with open(output, 'wb') as output_file:
        print output_file.read()

In that code, I want to read the file, but I use mode wb instead of r or r+

How to escape apostrophe (') in MySql?

Possibly off-topic, but maybe you came here looking for a way to sanitise text input from an HTML form, so that when a user inputs the apostrophe character, it doesn't throw an error when you try to write the text to an SQL-based table in a DB. There are a couple of ways to do this, and you might want to read about SQL injection too. Here's an example of using prepared statements and bound parameters in PHP:

$input_str = "Here's a string with some apostrophes (')";
// sanitise it before writing to the DB (assumes PDO)
$sql = "INSERT INTO `table` (`note`) VALUES (:note)";
try {
    $stmt = $dbh->prepare($sql);
    $stmt->bindParam(':note', $input_str, PDO::PARAM_STR);
    $stmt->execute();
} catch (PDOException $e) {
    return $dbh->errorInfo();
}
return "success";

In the special case where you may want to store your apostrophes using their HTML entity references, PHP has the htmlspecialchars() function which will convert them to &#039;. As the comments indicate, this should not be used as a substitute for proper sanitisation, as per the example given.

date() method, "A non well formed numeric value encountered" does not want to format a date passed in $_POST

From the documentation for strtotime():

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

In your date string, you have 12-16-2013. 16 isn't a valid month, and hence strtotime() returns false.

Since you can't use DateTime class, you could manually replace the - with / using str_replace() to convert the date string into a format that strtotime() understands:

$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16

Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate

The answer I have finally found is that the SMTP service on the server is not using the same certificate as https.

The diagnostic steps I had read here make the assumption they use the same certificate and every time I've tried this in the past they have done and the diagnostic steps are exactly what I've done to solve the problem several times.

In this case those steps didn't work because the certificates in use were different, and the possibility of this is something I had never come across.

The solution is either to export the actual certificate from the server and then install it as a trusted certificate on my machine, or to get a different valid/trusted certificate for the SMTP service on the server. That is currently with our IT department who administer the servers to decide which they want to do.

HTTP headers in Websockets client API

More of an alternate solution, but all modern browsers send the domain cookies along with the connection, so using:

var authToken = 'R3YKZFKBVi';

document.cookie = 'X-Authorization=' + authToken + '; path=/';

var ws = new WebSocket(
    'wss://localhost:9000/wss/'
);

End up with the request connection headers:

Cookie: X-Authorization=R3YKZFKBVi

Why are only final variables accessible in anonymous class?

The reason why the access has been restricted only to the local final variables is that if all the local variables would be made accessible then they would first required to be copied to a separate section where inner classes can have access to them and maintaining multiple copies of mutable local variables may lead to inconsistent data. Whereas final variables are immutable and hence any number of copies to them will not have any impact on the consistency of data.

MySQL JDBC Driver 5.1.33 - Time Zone Issue

There is no impact of setting server time as UTC (for instance with jdbc:mysql://localhost:3306/myschema?serverTimezone=UTC, even if your application/database servers are not in this timezone. The important is for the application connection string + database to be synchronized with the same time zone.

In other words, simply setting serverTimezone=UTC with a different time zone on the database server will shift any dates extracted from the database

Is there any way to have a fieldset width only be as wide as the controls in them?

            <table style="position: relative; top: -0px; left: 0px;">
                <tr>
                    <td>
                        <div>   
                            <fieldset style="width:0px">
                                <legend>A legend</legend>
                                <br/>
                                <table cellspacing="0" align="left">
                                    <tbody>
                                        <tr>
                                            <td align='left' style="white-space: nowrap;">
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </fieldset>
                        </div>
                    </td>
                </tr>
            </table>

Insert picture into Excel cell

Now we can add a picture to Excel directly and easely. Just follow these instructions:

  1. Go to the Insert tab.
  2. Click on the Pictures option (it’s in the illustrations group). image1
  3. In the ‘Insert Picture’ dialog box, locate the pictures that you want to insert into a cell in Excel. image2
  4. Click on the Insert button. image3
  5. Re-size the picture/image so that it can fit perfectly within the cell. image4
  6. Place the picture in the cell. A cool way to do this is to first press the ALT key and then move the picture with the mouse. It will snap and arrange itself with the border of the cell as soon it comes close to it.

If you have multiple images, you can select and insert all the images at once (as shown in step 4).

You can also resize images by selecting it and dragging the edges. In the case of logos or product images, you may want to keep the aspect ratio of the image intact. To keep the aspect ratio intact, use the corners of an image to resize it.


When you place an image within a cell using the steps above, it will not stick with the cell in case you resize, filter, or hide the cells. If you want the image to stick to the cell, you need to lock the image to the cell it’s placed n.

To do this, you need to follow the additional steps as shown below.

  1. Right-click on the picture and select Format Picture. image5
  2. In the Format Picture pane, select Size & Properties and with the options in Properties, select ‘Move and size with cells’. image6

Now you can move cells, filter it, or hide it, and the picture will also move/filter/hide.


NOTE:

This answer was taken from this link: Insert Picture into a Cell in Excel.

Difference between two dates in MySQL

This function takes the difference between two dates and shows it in a date format yyyy-mm-dd. All you need is to execute the code below and then use the function. After executing you can use it like this

SELECT datedifference(date1, date2)
FROM ....
.
.
.
.


DELIMITER $$

CREATE FUNCTION datedifference(date1 DATE, date2 DATE) RETURNS DATE
NO SQL

BEGIN
    DECLARE dif DATE;
    IF DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(date1), '-', DAY(date2)))) < 0    THEN
                SET dif=DATE_FORMAT(
                                        CONCAT(
                                            PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))DIV 12 , 
                                            '-',
                                            PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))% 12 , 
                                            '-',
                                            DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(DATE_SUB(date1, INTERVAL 1 MONTH)), '-', DAY(date2))))),
                                        '%Y-%m-%d');
    ELSEIF DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(date1), '-', DAY(date2)))) < DAY(LAST_DAY(DATE_SUB(date1, INTERVAL 1 MONTH))) THEN
                SET dif=DATE_FORMAT(
                                        CONCAT(
                                            PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))DIV 12 , 
                                            '-',
                                            PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))% 12 , 
                                            '-',
                                            DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(date1), '-', DAY(date2))))),
                                        '%Y-%m-%d');
    ELSE
                SET dif=DATE_FORMAT(
                                        CONCAT(
                                            PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))DIV 12 , 
                                            '-',
                                            PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))% 12 , 
                                            '-',
                                            DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(date1), '-', DAY(date2))))),
                                        '%Y-%m-%d');
    END IF;

RETURN dif;
END $$
DELIMITER;

What's the effect of adding 'return false' to a click event listener?

The return false is saying not to take the default action, which in the case of an <a href> is to follow the link. When you return false to the onclick, then the href will be ignored.

Adding open/closed icon to Twitter Bootstrap collapsibles (accordions)

The most readable CSS-only solution would probably be to use the aria-expanded attribute. Remember that you'll need to add aria-expanded="false" to all collapse-elements as this is not set on load (only on first click).

The HTML:

<h2 data-toggle="collapse" href="#collapseId" aria-expanded="false">
    <span class="glyphicon glyphicon-chevron-right"></span>
    <span class="glyphicon glyphicon-chevron-down"></span> Title
</h2>

The CSS:

h2[aria-expanded="false"] span.glyphicon-chevron-down,
h2[aria-expanded="true"] span.glyphicon-chevron-right
{
    display: none;
}

h2[aria-expanded="true"] span.glyphicon-chevron-down,
h2[aria-expanded="false"] span.glyphicon-chevron-right
{
    display: inline;
}

Works with Bootstrap 3.x.

Software Design vs. Software Architecture

Architecture is design with a rationale that comes from various factors the most important of which are the non-functional requirements like say scalability and certainly not the least is experience. Without rationale you are left with plain pattern, or how to do. Whether designing at a higher level or at the class level its still design.

OR put another way

Architecture is meta-design, i.e. designing the design. You have a few patterns that are known to fit a certain solution space, which would you select and why? Architecture is when you answer the "which" and "why" (the "how" is already given by design). It certainly does not depend on level of abstraction, for example implementing distributed sessions is not a class level task, but there are a few designs from which to select for a given architecture.

Likewise, architecture is reflected even in a class level design. Under a scalable architecture, class design is often different if you were to do it without the scalability factor in mind. Why you must have a method "BeginAsyncUpload" versus "Upload" is an architectural decision.

Interestingly, as we move focus towards system element at the higher level the questions "which and why" become more important and "how" becomes less relevant. Moving in the other direction the "how" part becomes more important, also because repeated usage makes it obvious, for example, to select between Abstract Factory or Prototype.

How do I reverse an int array in Java?

Here is a simple implementation, to reverse array of any type, plus full/partial support.

import java.util.logging.Logger;

public final class ArrayReverser {
 private static final Logger LOGGER = Logger.getLogger(ArrayReverser.class.getName());

 private ArrayReverser () {

 }

 public static <T> void reverse(T[] seed) {
    reverse(seed, 0, seed.length);
 }

 public static <T> void reverse(T[] seed, int startIndexInclusive, int endIndexExclusive) {
    if (seed == null || seed.length == 0) {
        LOGGER.warning("Nothing to rotate");
    }
    int start = startIndexInclusive < 0 ? 0 : startIndexInclusive;
    int end = Math.min(seed.length, endIndexExclusive) - 1;
    while (start < end) {
        swap(seed, start, end);
        start++;
        end--;
    }
}

 private static <T> void swap(T[] seed, int start, int end) {
    T temp =  seed[start];
    seed[start] = seed[end];
    seed[end] = temp;
 }  

}

Here is the corresponding Unit Test

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import org.junit.Before;
import org.junit.Test;

public class ArrayReverserTest {
private Integer[] seed;

@Before
public void doBeforeEachTestCase() {
    this.seed = new Integer[]{1,2,3,4,5,6,7,8};
}

@Test
public void wholeArrayReverse() {
    ArrayReverser.<Integer>reverse(seed);
    assertThat(seed[0], is(8));
}

 @Test
 public void partialArrayReverse() {
    ArrayReverser.<Integer>reverse(seed, 1, 5);
    assertThat(seed[1], is(5));
 }
}

How to run Linux commands in Java?

Java Function to bring Linux Command Result!

public String RunLinuxCommand(String cmd) throws IOException {

    String linuxCommandResult = "";
    Process p = Runtime.getRuntime().exec(cmd);

    BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

    try {
        while ((linuxCommandResult = stdInput.readLine()) != null) {

            return linuxCommandResult;
        }
        while ((linuxCommandResult = stdError.readLine()) != null) {
            return "";
        }
    } catch (Exception e) {
        return "";
    }

    return linuxCommandResult;
}

Currency Formatting in JavaScript

You can use standard JS toFixed method

var num = 5.56789;
var n=num.toFixed(2);

//5.57

In order to add commas (to separate 1000's) you can add regexp as follows (where num is a number):

num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")

//100000 => 100,000
//8000 => 8,000
//1000000 => 1,000,000

Complete example:

var value = 1250.223;
var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");

//document.write(num) would write value as follows: $1,250.22

Separation character depends on country and locale. For some countries it may need to be .

React JS onClick event handler

This is a non-standard (but not so uncommon) React pattern that doesn't use JSX, instead putting everything inline. Also, it's Coffeescript.

The 'React-way' to do this would be with the component's own state:

(c = console.log.bind console)

mock_items: [
    {
        name: 'item_a'
        uid: shortid()
    }
    {
        name: 'item_b'
        uid: shortid()
    }
    {
        name: 'item_c'
        uid: shortid()
    }
]
getInitialState: ->
    lighted_item: null
render: ->
    div null,
        ul null,
            for item, idx in @mock_items
                uid = item.uid
                li
                    key: uid
                    onClick: do (idx, uid) =>
                        (e) =>
                            # justf to illustrate these are bound in closure by the do lambda,
                            c idx
                            c uid
                            @setState
                                lighted_item: uid
                    style:
                        cursor: 'pointer'
                        background: do (uid) =>
                            c @state.lighted_item
                            c 'and uid', uid
                            if @state.lighted_item is uid then 'magenta' else 'chartreuse'
                        # background: 'chartreuse'
                    item.name

This example works -- I tested it locally. You can check out this example code exactly at my github. Originally the env was only local for my own whiteboard r&d purposes but I posted it to Github for this. It may get written over at some point but you can check out the commit from Sept 8, 2016 to see this.

More generally, if you want to see how this CS/no-JSX pattern for React works, check out some recent work here. It's possible I will have time to fully implement a POC for this app idea, the stack for which includes NodeJS, Primus, Redis, & React.

Bootstrap Modal sitting behind backdrop

You could use this :

<div
  class="modal fade stick-up disable-scroll"
  id="filtersModal"
  tabindex="-1"
  role="dialog"
  aria-labelledby="filtersModal"
  aria-hidden="false"
  style="background-color: rgba(0, 0, 0, 0.5);" data-backdrop="false"
>
....
</div>

Adding style="" and data-backdrop false would fix it.

How to properly override clone method?

Do you absolutely have to use clone? Most people agree that Java's clone is broken.

Josh Bloch on Design - Copy Constructor versus Cloning

If you've read the item about cloning in my book, especially if you read between the lines, you will know that I think clone is deeply broken. [...] It's a shame that Cloneable is broken, but it happens.

You may read more discussion on the topic in his book Effective Java 2nd Edition, Item 11: Override clone judiciously. He recommends instead to use a copy constructor or copy factory.

He went on to write pages of pages on how, if you feel you must, you should implement clone. But he closed with this:

Is all this complexities really necessary? Rarely. If you extend a class that implements Cloneable, you have little choice but to implement a well-behaved clone method. Otherwise, you are better off providing alternative means of object copying, or simply not providing the capability.

The emphasis was his, not mine.


Since you made it clear that you have little choice but to implement clone, here's what you can do in this case: make sure that MyObject extends java.lang.Object implements java.lang.Cloneable. If that's the case, then you can guarantee that you will NEVER catch a CloneNotSupportedException. Throwing AssertionError as some have suggested seems reasonable, but you can also add a comment that explains why the catch block will never be entered in this particular case.


Alternatively, as others have also suggested, you can perhaps implement clone without calling super.clone.

Keep-alive header clarification

Where is this info kept ("this connection is between computer A and server F")?

A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.

HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.

This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.

When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection

No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.

which is only for my session ?

Does it mean that no one else can use that connection

That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.

If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?

Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:

  • Lower CPU and memory usage (because fewer connections are open simultaneously).
  • Enables HTTP pipelining of requests and responses.
  • Reduced network congestion (fewer TCP connections).
  • Reduced latency in subsequent requests (no handshaking).

if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)

An typical keep-alive response looks like this:

Keep-Alive: timeout=15, max=100

See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):

  • A host sets the value of the timeout parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.

  • The max parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.

However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.

How can I create an object based on an interface file definition in TypeScript?

If you want an empty object of an interface, you can do just:

var modal = <IModal>{};

The advantage of using interfaces in lieu of classes for structuring data is that if you don't have any methods on the class, it will show in compiled JS as an empty method. Example:

class TestClass {
    a: number;
    b: string;
    c: boolean;
}

compiles into

var TestClass = (function () {
    function TestClass() {
    }
    return TestClass;
})();

which carries no value. Interfaces, on the other hand, don't show up in JS at all while still providing the benefits of data structuring and type checking.

vi/vim editor, copy a block (not usual action)

You can do it as you do in vi, for example to yank lines from 3020 to the end, execute this command (write the block to a file):

:3020,$ w /tmp/yank

And to write this block in another line/file, go to the desired position and execute next command (insert file written before):

:r /tmp/yank

(Reminder: don't forget to remove file: /tmp/yank)

Implement an input with a mask

Below i describe my method. I set event on input in input, to call Masking() method, which will return an formatted string of that we insert in input.

Html:

<input name="phone" pattern="+373 __ ___ ___" class="masked" required>

JQ: Here we set event on input:

$('.masked').on('input', function () {
    var input = $(this);
    input.val(Masking(input.val(), input.attr('pattern')));
});

JS: Function, which will format string by pattern;

function Masking (value, pattern) {
var out = '';
var space = ' ';
var any = '_';

for (var i = 0, j = 0; j < value.length; i++, j++) {
    if (value[j] === pattern[i]) {
        out += value[j];
    }
    else if(pattern[i] === any && value[j] !== space) {
        out += value[j];
    }
    else if(pattern[i] === space && value[j] !== space) {
        out += space;
        j--;
    }
    else if(pattern[i] !== any && pattern[i] !== space) {
        out += pattern[i];
        j--;
    }
}

return out;
}

Rebasing a Git merge commit

Ok, that's an old question and it already have accepted answer by @siride, but that answer wasn't enough in my case, as --preserve-merges forces you to resolve all conflicts second time. My solution based on the idea by @Tobi B but with exact step-by-step commands

So we'll start on such state based on example in the question:

*   8101fe3 Merge branch 'topic'  [HEAD -> master]
|\  
| * b62cae6 2                     [topic]
| |
| | * f5a7ca8 5                   [origin/master]
| | * e7affba 4
| |/  
|/|   
* | eb3b733 3
|/  
* 38abeae 1

Note that we have 2 commits ahead master, so cherry-pick wouldn't work.

  1. First of all, let's create correct history that we want:

    git checkout -b correct-history # create new branch to save master for future
    git rebase --strategy=ours --preserve-merges origin/master
    

    We use --preserve-merges to save our merge commit in history. We use --strategy=ours to ignore all merge conflicts as we don't care about what contents will be in that merge commit, we only need nice history now.

    History will looks like that (ignoring master):

    *   51984c7 Merge branch 'topic'  [HEAD -> correct-history]
    |\  
    | * b62cae6 2                     [topic]
    * | f5a7ca8 5                     [origin/master]
    * | e7affba 4
    * | eb3b733 3
    |/  
    * 38abeae 1
    
  2. Let's get correct index now.

    git checkout master # return to our master branch
    git merge origin/master # merge origin/master on top of our master
    

    We may get some additional merge conflicts here, but that's would only be conflicts from files changed between 8101fe3 and f5a7ca8, but not includes already resolved conflicts from topic

    History will looks like this (ignoring correct-history):

    *   94f1484 Merge branch 'origin/master'  [HEAD -> master]
    |\  
    * | f5a7ca8 5                   [origin/master]
    * | e7affba 4
    | *   8101fe3 Merge branch 'topic'
    | |\  
    | | * b62cae6 2                     [topic]
    |/ /
    * / eb3b733 3
    |/  
    * 38abeae 1
    
  3. The last stage is to combine our branch with correct history and branch with correct index

    git reset --soft correct-history
    git commit --amend
    

    We use reset --soft to reset our branch (and history) to correct-history, but leave index and working tree as is. Then we use commit --amend to rewrite our merge commit, that used to have incorrect index, with our good index from master.

    In the end we will have such state (note another id of top commit):

    *   13e6d03 Merge branch 'topic'  [HEAD -> master]
    |\  
    | * b62cae6 2                     [topic]
    * | f5a7ca8 5                     [origin/master]
    * | e7affba 4
    * | eb3b733 3
    |/  
    * 38abeae 1
    

How to get document height and width without using jquery

If you want to get the full width of the page, including overflow, use document.body.scrollWidth.

Difference between window.location.href=window.location.href and window.location.reload()

In our case we just want to reload the page in webview and for some reasons we couldn't find out why! We try almost every solution that has been on the web, but stuck with no reloading using location.reload() or alternative solutions like window.location.reload(), location.reload(true), ...!

Here is our simple solution :

Just use a < a > tag with the empty "href" attribution value like this :

< a href="" ...>Click Me</a>

(in some cases you have to use "return true" on click of the target to trigger reload)

For more information check out this question : Is an empty href valid?

How can I reference a commit in an issue comment on GitHub?

Answer above is missing an example which might not be obvious (it wasn't to me).

Url could be broken down into parts

https://github.com/liufa/Tuplinator/commit/f36e3c5b3aba23a6c9cf7c01e7485028a23c3811
                  \_____/\________/       \_______________________________________/
                   |        |                              |
            Account name    |                      Hash of revision
                        Project name              

Hash can be found here (you can click it and will get the url from browser).

enter image description here

Hope this saves you some time.

How to have click event ONLY fire on parent DIV, not children?

I had the same problem and came up with this solution (based on the other answers)

 $( ".newsletter_background" ).click(function(e) {
    if (e.target == this) {
        $(".newsletter_background").hide();
    } 
});

Basically it says if the target is the div then run the code otherwise do nothing (don't hide it)

jQuery delete confirmation box

$(document).ready(function(){
  $(".del").click(function(){
    if (!confirm("Do you want to delete")){
      return false;
    }
  });
});

Simple way to get element by id within a div tag?

Sample Html code   
 <div id="temp">
        F1 <input type="text" value="111"/><br/>
        F2 <input type="text" value="222"/><br/>
        F3 <input type="text" value="333"/><br/>
        Type <select>
        <option value="A">A</option>
        <option value="B">B</option>
        <option value="C">C</option>
        </select>
        <input type="button" value="Go" onclick="getVal()">
    </div>

Javascript

    function  getVal()
    {
        var test = document.getElementById("temp").getElementsByTagName("input");
        alert("Number of Input Elements "+test.length);
        for(var i=0;i<test.length;i++)
        {
          if(test[i].type=="text")
          {
            alert(test[i].value);
          }
       }
      test = document.getElementById("temp").getElementsByTagName("select");
      alert("Select box  "+test[0].options[test[0].selectedIndex].text);
    }

By providing different tag names we can get all the values from the div.

Put byte array to JSON and vice versa

Here is a good example of base64 encoding byte arrays. It gets more complicated when you throw unicode characters in the mix to send things like PDF documents. After encoding a byte array the encoded string can be used as a JSON property value.

Apache commons offers good utilities:

 byte[] bytes = getByteArr();
 String base64String = Base64.encodeBase64String(bytes);
 byte[] backToBytes = Base64.decodeBase64(base64String);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding

Java server side example:

public String getUnsecureContentBase64(String url)
        throws ClientProtocolException, IOException {

            //getUnsecureContent will generate some byte[]
    byte[] result = getUnsecureContent(url);

            // use apache org.apache.commons.codec.binary.Base64
            // if you're sending back as a http request result you may have to
            // org.apache.commons.httpclient.util.URIUtil.encodeQuery
    return Base64.encodeBase64String(result);
}

JavaScript decode:

//decode URL encoding if encoded before returning result
var uriEncodedString = decodeURIComponent(response);

var byteArr = base64DecToArr(uriEncodedString);

//from mozilla
function b64ToUint6 (nChr) {

  return nChr > 64 && nChr < 91 ?
      nChr - 65
    : nChr > 96 && nChr < 123 ?
      nChr - 71
    : nChr > 47 && nChr < 58 ?
      nChr + 4
    : nChr === 43 ?
      62
    : nChr === 47 ?
      63
    :
      0;

}

function base64DecToArr (sBase64, nBlocksSize) {

  var
    sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length,
    nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2, taBytes = new Uint8Array(nOutLen);

  for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) {
    nMod4 = nInIdx & 3;
    nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4;
    if (nMod4 === 3 || nInLen - nInIdx === 1) {
      for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
        taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255;
      }
      nUint24 = 0;

    }
  }

  return taBytes;
}

The program can't start because MSVCR110.dll is missing from your computer

I would like to quote an answer given by Microsoft support engineer at here:-

http://answers.microsoft.com/en-us/windows/forum/windows_8-winapps/the-program-cant-start-because-msvcr110dll-is/f052d325-3af9-4ae5-990b-b080799724db

Hi Henny, MSVCR110.dll is the Microsoft Visual C++ Redistributable dll that is needed for projects built with Visual Studio 2011. The dll letters spell this out. MS = Microsoft, V = Visual, C = C++, R = Redistributable For Winroy to get started, this file is probably needed. This error appears when you wish to run a software which require the Microsoft Visual C++ Redistributable 2012. The redistributable can easily be downloaded on the Microsoft website as x86 or x64 edition. Depending on the software you wish to install you need to install either the 32 bit or the 64 bit version. Refer the following link: http://www.microsoft.com/en-us/download/details.aspx?id=30679# Please let us know if the issue persists. We will be happy to assist you further. Thanks, Yaqub Khan - Microsoft Support Engineer

jQuery AutoComplete Trigger Change Event

The simplest, most robust way is to use the internal ._trigger() to fire the autocomplete change event.

$("#CompanyList").autocomplete({
  source : yourSource,
  change : yourChangeHandler
})

$("#CompanyList").data("ui-autocomplete")._trigger("change");

Note, jQuery UI 1.9 changed from .data("autocomplete") to .data("ui-autocomplete"). You may also see some people using .data("uiAutocomplete") which indeed works in 1.9 and 1.10, but "ui-autocomplete" is the official preferred form. See http://jqueryui.com/upgrade-guide/1.9/#changed-naming-convention-for-data-keys for jQuery UI namespaecing on data keys.

How to limit the number of dropzone.js files uploaded?

Dropzone.options.dpzSingleFile = {
    paramName: "file", // The name that will be used to transfer the file
    maxFiles: 1,
    init: function() {
        this.on("maxfilesexceeded", function(file) {
            this.removeAllFiles();
            this.addFile(file);
        });
    }
};

SyntaxError: Non-ASCII character '\xa3' in file when function returns '£'

I'd recommend reading that PEP the error gives you. The problem is that your code is trying to use the ASCII encoding, but the pound symbol is not an ASCII character. Try using UTF-8 encoding. You can start by putting # -*- coding: utf-8 -*- at the top of your .py file. To get more advanced, you can also define encodings on a string by string basis in your code. However, if you are trying to put the pound sign literal in to your code, you'll need an encoding that supports it for the entire file.

What exactly is the function of Application.CutCopyMode property in Excel

By referring this(http://www.excelforum.com/excel-programming-vba-macros/867665-application-cutcopymode-false.html) link the answer is as below:

Application.CutCopyMode=False is seen in macro recorder-generated code when you do a copy/cut cells and paste . The macro recorder does the copy/cut and paste in separate statements and uses the clipboard as an intermediate buffer. I think Application.CutCopyMode = False clears the clipboard. Without that line you will get the warning 'There is a large amount of information on the Clipboard....' when you close the workbook with a large amount of data on the clipboard.

With optimised VBA code you can usually do the copy/cut and paste operations in one statement, so the clipboard isn't used and Application.CutCopyMode = False isn't needed and you won't get the warning.

Hex to ascii string conversion

you need to take 2 (hex) chars at the same time... then calculate the int value and after that make the char conversion like...

char d = (char)intValue;

do this for every 2chars in the hex string

this works if the string chars are only 0-9A-F:

#include <stdio.h>
#include <string.h>

int hex_to_int(char c){
        int first = c / 16 - 3;
        int second = c % 16;
        int result = first*10 + second;
        if(result > 9) result--;
        return result;
}

int hex_to_ascii(char c, char d){
        int high = hex_to_int(c) * 16;
        int low = hex_to_int(d);
        return high+low;
}

int main(){
        const char* st = "48656C6C6F3B";
        int length = strlen(st);
        int i;
        char buf = 0;
        for(i = 0; i < length; i++){
                if(i % 2 != 0){
                        printf("%c", hex_to_ascii(buf, st[i]));
                }else{
                        buf = st[i];
                }
        }
}

Best font for coding

I like Consolas a lot. This top-10 list is a good resource for others. It includes examples and descriptions.

CSS – why doesn’t percentage height work?

Another option is to add style to div

<div style="position: absolute; height:somePercentage%; overflow:auto(or other overflow value)">
 //to be scrolled 
</div>

And it means that an element is positioned relative to the nearest positioned ancestor.

Differences in string compare methods in C#

As Ed said, CompareTo is used for sorting.

There is a difference, however, between .Equals and ==.

== resolves to essentially the following code:

if(object.ReferenceEquals(left, null) && 
   object.ReferenceEquals(right, null))
    return true;
if(object.ReferenceEquals(left, null))
    return right.Equals(left);
return left.Equals(right);

The simple reason is the following will throw an exception:

string a = null;
string b = "foo";

bool equal = a.Equals(b);

And the following will not:

string a = null;
string b = "foo";

bool equal = a == b;

Unable to access JSON property with "-" dash

jsonObj.profile-id is a subtraction expression (i.e. jsonObj.profile - id).

To access a key that contains characters that cannot appear in an identifier, use brackets:

jsonObj["profile-id"]

Sql Server return the value of identity column after insert statement

Here goes a bunch of different ways to get the ID, including Scope_Identity:

https://stackoverflow.com/a/42655/1504882

Invoke JSF managed bean action on page load

@PostConstruct is run ONCE in first when Bean Created. the solution is create a Unused property and Do your Action in Getter method of this property and add this property to your .xhtml file like this :

<h:inputHidden  value="#{loginBean.loginStatus}"/>

and in your bean code:

public void setLoginStatus(String loginStatus) {
    this.loginStatus = loginStatus;
}

public String getLoginStatus()  {
    // Do your stuff here.
    return loginStatus;
}

using jQuery .animate to animate a div from right to left?

If you know the width of the child element you are animating, you can use and animate a margin offset as well. For example, this will animate from left:0 to right:0

CSS:

.parent{
width:100%;
position:relative;
}

#itemToMove{
position:absolute;
width:150px;
right:100%;
margin-right:-150px;
}

Javascript:

$( "#itemToMove" ).animate({
"margin-right": "0",
"right": "0"
}, 1000 );

matplotlib colorbar in each subplot

Try to use the func below to add colorbar:

def add_colorbar(mappable):
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    import matplotlib.pyplot as plt
    last_axes = plt.gca()
    ax = mappable.axes
    fig = ax.figure
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    cbar = fig.colorbar(mappable, cax=cax)
    plt.sca(last_axes)
    return cbar

Then you codes need to be modified as:

fig , ( (ax1,ax2) , (ax3,ax4)) = plt.subplots(2, 2,sharex = True,sharey=True)
z1_plot = ax1.scatter(x,y,c = z1,vmin=0.0,vmax=0.4)
add_colorbar(z1_plot)

How to populate a sub-document in mongoose after creating it?

In order to populate referenced subdocuments, you need to explicitly define the document collection to which the ID references to (like created_by: { type: Schema.Types.ObjectId, ref: 'User' }).

Given this reference is defined and your schema is otherwise well defined as well, you can now just call populate as usual (e.g. populate('comments.created_by'))

Proof of concept code:

// Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
  name: String
});

var CommentSchema = new Schema({
  text: String,
  created_by: { type: Schema.Types.ObjectId, ref: 'User' }
});

var ItemSchema = new Schema({
   comments: [CommentSchema]
});

// Connect to DB and instantiate models    
var db = mongoose.connect('enter your database here');
var User = db.model('User', UserSchema);
var Comment = db.model('Comment', CommentSchema);
var Item = db.model('Item', ItemSchema);

// Find and populate
Item.find({}).populate('comments.created_by').exec(function(err, items) {
    console.log(items[0].comments[0].created_by.name);
});

Finally note that populate works only for queries so you need to first pass your item into a query and then call it:

item.save(function(err, item) {
    Item.findOne(item).populate('comments.created_by').exec(function (err, item) {
        res.json({
            status: 'success',
            message: "You have commented on this item",
            comment: item.comments.id(comment._id)
        });
    });
});

sendUserActionEvent() is null

Same issue on a Galaxy Tab and on a Xperia S, after uninstall and install again it seems that disappear.

The code that suddenly appear to raise this problem is this:

public void unlockMainActivity() {
    SharedPreferences prefs = getSharedPreferences("CALCULATOR_PREFS", 0);
    boolean hasCode = prefs.getBoolean("HAS_CODE", false);
    Context context = this.getApplicationContext();
    Intent intent = null;

    if (!hasCode) {
        intent = new Intent(context, WellcomeActivity.class);
    } else {
        intent = new Intent(context, CalculatingActivity.class);
    }
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    (context).startActivity(intent);
}

Android Studio says "cannot resolve symbol" but project compiles

None of the answers above works for me.

After a lots of attempts, I upgraded com.android.tools.build:gradle in Project/build.gradle from 2.3.0 to 3.0.1, and it works.

I guess the version of the com.android.tools.build:gradle should be match to the version of AndroidStudio, and my AS version is 3.2.1

How do you validate a URL with a regular expression in Python?

Here's the complete regexp to parse a URL.

(?:http://(?:(?:(?:(?:(?:[a-zA-Z\d](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?)\.
)*(?:[a-zA-Z](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?))|(?:(?:\d+)(?:\.(?:\d+)
){3}))(?::(?:\d+))?)(?:/(?:(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F
\d]{2}))|[;:@&=])*)(?:/(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{
2}))|[;:@&=])*))*)(?:\?(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{
2}))|[;:@&=])*))?)?)|(?:ftp://(?:(?:(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?
:%[a-fA-F\d]{2}))|[;?&=])*)(?::(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-
fA-F\d]{2}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[a-fA-F\d]{2}))|[&=~:@/])+)))?))
)?)|(?:nfs:(?:(?://(?:(?:(?:(?:(?:[a-zA-Z\d](?:(?:[a-zA-Z\d]|-)*[a-zA-
Z\d])?)\.)*(?:[a-zA-Z](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?))|(?:(?:\d+)(?:
\.(?:\d+)){3}))(?::(?:\d+))?)(?:(?:/(?:(?:(?:(?:(?:[a-zA-Z\d\$\-_.!~*'
(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*)(?:/(?:(?:(?:[a-zA-Z\d\$\-_.!~*'(),
])|(?:%[a-fA-F\d]{2})|[:@&=+])*))*)?)))?)|(?:/(?:(?:(?:(?:(?:[a-zA-Z\d
\$\-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*)(?:/(?:(?:(?:[a-zA-Z\d\$\
-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*))*)?))|(?:(?:(?:(?:(?:[a-zA-
Z\d\$\-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*)(?:/(?:(?:(?:[a-zA-Z\d
\$\-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*))*)?)))

Given its complexibility, I think you should go the urlparse way.

For completeness, here's the pseudo-BNF of the above regex (as a documentation):

; The generic form of a URL is:

genericurl     = scheme ":" schemepart

; Specific predefined schemes are defined here; new schemes
; may be registered with IANA

url            = httpurl | ftpurl | newsurl |
                 nntpurl | telneturl | gopherurl |
                 waisurl | mailtourl | fileurl |
                 prosperourl | otherurl

; new schemes follow the general syntax
otherurl       = genericurl

; the scheme is in lower case; interpreters should use case-ignore
scheme         = 1*[ lowalpha | digit | "+" | "-" | "." ]
schemepart     = *xchar | ip-schemepart


; URL schemeparts for ip based protocols:

ip-schemepart  = "//" login [ "/" urlpath ]

login          = [ user [ ":" password ] "@" ] hostport
hostport       = host [ ":" port ]
host           = hostname | hostnumber
hostname       = *[ domainlabel "." ] toplabel
domainlabel    = alphadigit | alphadigit *[ alphadigit | "-" ] alphadigit
toplabel       = alpha | alpha *[ alphadigit | "-" ] alphadigit
alphadigit     = alpha | digit
hostnumber     = digits "." digits "." digits "." digits
port           = digits
user           = *[ uchar | ";" | "?" | "&" | "=" ]
password       = *[ uchar | ";" | "?" | "&" | "=" ]
urlpath        = *xchar    ; depends on protocol see section 3.1

; The predefined schemes:

; FTP (see also RFC959)

ftpurl         = "ftp://" login [ "/" fpath [ ";type=" ftptype ]]
fpath          = fsegment *[ "/" fsegment ]
fsegment       = *[ uchar | "?" | ":" | "@" | "&" | "=" ]
ftptype        = "A" | "I" | "D" | "a" | "i" | "d"

; FILE

fileurl        = "file://" [ host | "localhost" ] "/" fpath

; HTTP

httpurl        = "http://" hostport [ "/" hpath [ "?" search ]]
hpath          = hsegment *[ "/" hsegment ]
hsegment       = *[ uchar | ";" | ":" | "@" | "&" | "=" ]
search         = *[ uchar | ";" | ":" | "@" | "&" | "=" ]

; GOPHER (see also RFC1436)

gopherurl      = "gopher://" hostport [ / [ gtype [ selector
                 [ "%09" search [ "%09" gopher+_string ] ] ] ] ]
gtype          = xchar
selector       = *xchar
gopher+_string = *xchar

; MAILTO (see also RFC822)

mailtourl      = "mailto:" encoded822addr
encoded822addr = 1*xchar               ; further defined in RFC822

; NEWS (see also RFC1036)

newsurl        = "news:" grouppart
grouppart      = "*" | group | article
group          = alpha *[ alpha | digit | "-" | "." | "+" | "_" ]
article        = 1*[ uchar | ";" | "/" | "?" | ":" | "&" | "=" ] "@" host

; NNTP (see also RFC977)

nntpurl        = "nntp://" hostport "/" group [ "/" digits ]

; TELNET

telneturl      = "telnet://" login [ "/" ]

; WAIS (see also RFC1625)

waisurl        = waisdatabase | waisindex | waisdoc
waisdatabase   = "wais://" hostport "/" database
waisindex      = "wais://" hostport "/" database "?" search
waisdoc        = "wais://" hostport "/" database "/" wtype "/" wpath
database       = *uchar
wtype          = *uchar
wpath          = *uchar

; PROSPERO

prosperourl    = "prospero://" hostport "/" ppath *[ fieldspec ]
ppath          = psegment *[ "/" psegment ]
psegment       = *[ uchar | "?" | ":" | "@" | "&" | "=" ]
fieldspec      = ";" fieldname "=" fieldvalue
fieldname      = *[ uchar | "?" | ":" | "@" | "&" ]
fieldvalue     = *[ uchar | "?" | ":" | "@" | "&" ]

; Miscellaneous definitions

lowalpha       = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" |
                 "i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" |
                 "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" |
                 "y" | "z"
hialpha        = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" |
                 "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" |
                 "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z"
alpha          = lowalpha | hialpha
digit          = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" |
                 "8" | "9"
safe           = "$" | "-" | "_" | "." | "+"
extra          = "!" | "*" | "'" | "(" | ")" | ","
national       = "{" | "}" | "|" | "\" | "^" | "~" | "[" | "]" | "`"
punctuation    = "" | "#" | "%" | 


reserved       = ";" | "/" | "?" | ":" | "@" | "&" | "="
hex            = digit | "A" | "B" | "C" | "D" | "E" | "F" |
                 "a" | "b" | "c" | "d" | "e" | "f"
escape         = "%" hex hex

unreserved     = alpha | digit | safe | extra
uchar          = unreserved | escape
xchar          = unreserved | reserved | escape
digits         = 1*digit

How to run mysql command on bash?

I have written a shell script which will read data from properties file and then run mysql script on shell script. sharing this may help to others.

#!/bin/bash
    PROPERTY_FILE=filename.properties

    function getProperty {
       PROP_KEY=$1
       PROP_VALUE=`cat $PROPERTY_FILE | grep "$PROP_KEY" | cut -d'=' -f2`
       echo $PROP_VALUE
    }

    echo "# Reading property from $PROPERTY_FILE"
    DB_USER=$(getProperty "db.username")
    DB_PASS=$(getProperty "db.password")
    ROOT_LOC=$(getProperty "root.location")
    echo $DB_USER
    echo $DB_PASS
    echo $ROOT_LOC
    echo "Writing on DB ... "
    mysql -u$DB_USER -p$DB_PASS dbname<<EOFMYSQL

    update tablename set tablename.value_ = "$ROOT_LOC" where tablename.name_="Root directory location";
    EOFMYSQL
    echo "Writing root location($ROOT_LOC) is done ... "
    counter=`mysql -u${DB_USER} -p${DB_PASS} dbname -e "select count(*) from tablename where tablename.name_='Root directory location' and tablename.value_ = '$ROOT_LOC';" | grep -v "count"`;

    if [ "$counter" = "1" ]
    then
    echo "ROOT location updated"
    fi

python JSON only get keys in first level

Just do a simple .keys()

>>> dct = {
...     "1": "a", 
...     "3": "b", 
...     "8": {
...         "12": "c", 
...         "25": "d"
...     }
... }
>>> 
>>> dct.keys()
['1', '8', '3']
>>> for key in dct.keys(): print key
...
1
8
3
>>>

If you need a sorted list:

keylist = dct.keys()
keylist.sort()

How to use ArrayList's get() method

To put it nice and simply, get(int index) returns the element at the specified index.

So say we had an ArrayList of Strings:

List<String> names = new ArrayList<String>();
names.add("Arthur Dent");
names.add("Marvin");
names.add("Trillian");
names.add("Ford Prefect");

Which can be visualised as: A visual representation of the array list Where 0, 1, 2, and 3 denote the indexes of the ArrayList.

Say we wanted to retrieve one of the names we would do the following: String name = names.get(1); Which returns the name at the index of 1.

Getting the element at index 1 So if we were to print out the name System.out.println(name); the output would be Marvin - Although he might not be too happy with us disturbing him.

MySQL Insert query doesn't work with WHERE clause

Insert into = Adding rows to a table

Upate = update specific rows.

What would the where clause describe in your insert? It doesn't have anything to match, the row doesn't exist (yet)...

Finding rows that don't contain numeric data in Oracle

You can use this one check:

create or replace function to_n(c varchar2) return number is
begin return to_number(c);
exception when others then return -123456;
end;

select id, n from t where to_n(n) = -123456;

What is DOM element?

Document object model.
The DOM is the way Javascript sees its containing pages' data. It is an object that includes how the HTML/XHTML/XML is formatted, as well as the browser state.

A DOM element is something like a DIV, HTML, BODY element on a page. You can add classes to all of these using CSS, or interact with them using JS.

Ansible - Use default if a variable is not defined

You can use Jinja's default:

- name: Create user
  user:
    name: "{{ my_variable | default('default_value') }}"

How to add fonts to create-react-app based projects?

Local fonts linking to your react js may be a failure. So, I prefer to use online css file from google to link fonts. Refer the following code,

<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

or

<style>
    @import url('https://fonts.googleapis.com/css?family=Roboto');
</style>

How to set min-font-size in CSS

Use a media query. Example: This is something im using the original size is 1.0vw but when it hits 1000 the letter gets too small so I scale it up

@media(max-width:600px){
    body,input,textarea{
         font-size:2.0vw !important;
    }
}

This site I m working on is not responsive for >500px but you might need more. The pro,benefit for this solution is you keep font size scaling without having super mini letters and you can keep it js free.

How to make a input field readonly with JavaScript?

Try This :

document.getElementById(<element_ID>).readOnly=true;

How to specify the actual x axis values to plot as x axis ticks in R

Take a closer look at the ?axis documentation. If you look at the description of the labels argument, you'll see that it is:

"a logical value specifying whether (numerical) annotations are 
to be made at the tickmarks,"

So, just change it to true, and you'll get your tick labels.

x <- seq(10,200,10)
y <- runif(x)
plot(x,y,xaxt='n')
axis(side = 1, at = x,labels = T)
# Since TRUE is the default for labels, you can just use axis(side=1,at=x)

Be careful that if you don't stretch your window width, then R might not be able to write all your labels in. Play with the window width and you'll see what I mean.


It's too bad that you had such trouble finding documentation! What were your search terms? Try typing r axis into Google, and the first link you will get is that Quick R page that I mentioned earlier. Scroll down to "Axes", and you'll get a very nice little guide on how to do it. You should probably check there first for any plotting questions, it will be faster than waiting for a SO reply.

pass array to method Java

Important Points

  • you have to use java.util package
  • array can be passed by reference

In the method calling statement

  • Don't use any object to pass an array
  • only the array's name is used, don't use datatype or array brackets []

Sample Program

import java.util.*;

class atg {
  void a() {
    int b[]={1,2,3,4,5,6,7};
    c(b);
  }

  void c(int b[]) {
    int e=b.length;
    for(int f=0;f<e;f++) {
      System.out.print(b[f]+" ");//Single Space
    }
  }

  public static void main(String args[]) {
    atg ob=new atg();
    ob.a();
  }
}

Output Sample Program

1 2 3 4 5 6 7

how to read xml file from url using php

$url = 'http://www.example.com'; $xml = simpleXML_load_file($url,"SimpleXMLElement",LIBXML_NOCDATA);

$url can be php file, as long as the file generate xml format data as output.

Visual c++ can't open include file 'iostream'

You are more than likely missing $(IncludePath) within Properties->VC++ Directories->Include Directories. Adding this should make iostream and others visible again. You probably deleted it by mistake while setting up your program.

Running Java gives "Error: could not open `C:\Program Files\Java\jre6\lib\amd64\jvm.cfg'"

If this was working before, it means the PATH isn't correct anymore.

That can happen when the PATH becomes too long and gets truncated.
All posts (like this one) suggest updating the PATH, which you can test first in a separate DOS session, by setting a minimal path and see if java works again there.


Finally the OP Highland Mark concludes:

Finally fixed by uninstalling java, removing all references to it from the registry, and then re-installing.

scary ;)

PHP date add 5 year to current date

try this:

$yearnow= date("Y");
$yearnext=$yearnow+1;
echo date("Y")."-".$yearnext;

php convert datetime to UTC

As an improvement on Phill Pafford's answer (I did not understand his 'Y-d-mTG:i:sz' and he suggested to revert timezone). So I propose this (I complicated by changing the HMTL format in plain/text...):

<?php
header('content-type: text/plain;');
$my_timestamp = strtotime("2010-01-19 00:00:00");

// stores timezone
$my_timezone = date_default_timezone_get();
echo date(DATE_ATOM, $my_timestamp)."\t ($my_timezone date)\n";

// changes timezone
date_default_timezone_set("UTC");
echo date("Y-m-d\TH:i:s\Z", $my_timestamp)."\t\t (ISO8601 UTC date)\n";
echo date("Y-m-d H:i:s", $my_timestamp)."\t\t (your UTC date)\n";

// reverts change
date_default_timezone_set($my_timezone);
echo date(DATE_ATOM, $my_timestamp)."\t ($my_timezone date is back)\n"; 
?>

Why GDB jumps unpredictably between lines and prints variables as "<value optimized out>"?

Typically, boolean values that are used in branches immediately after they're calculated like this are never actually stored in variables. Instead, the compiler just branches directly off the condition codes that were set from the preceding comparison. For example,

int a = SomeFunction();
bool result = --a >= 0; // use subtraction as example computation
if ( result ) 
{
   foo(); 
}
else
{
   bar();
}
return;

Usually compiles to something like:

call .SomeFunction  ; calls to SomeFunction(), which stores its return value in eax
sub eax, 1 ; subtract 1 from eax and store in eax, set S (sign) flag if result is negative
jl ELSEBLOCK ; GOTO label "ELSEBLOCK" if S flag is set
call .foo ; this is the "if" black, call foo()
j FINISH ; GOTO FINISH; skip over the "else" block
ELSEBLOCK: ; label this location to the assembler
call .bar
FINISH: ; both paths end up here
ret ; return

Notice how the "bool" is never actually stored anywhere.

How to declare an array in Python?

Following on from Lennart, there's also numpy which implements homogeneous multi-dimensional arrays.

adding noise to a signal in python

You can generate a noise array, and add it to your signal

import numpy as np

noise = np.random.normal(0,1,100)

# 0 is the mean of the normal distribution you are choosing from
# 1 is the standard deviation of the normal distribution
# 100 is the number of elements you get in array noise

how to get list of port which are in use on the server

Open up a command prompt then type...

netstat -a

Getting the last element of a split string array

You can also consider to reverse your array and take the first element. That way you don't have to know about the length, but it brings no real benefits and the disadvantage that the reverse operation might take longer with big arrays:

array1.split(",").reverse()[0]

It's easy though, but also modifies the original array in question. That might or might not be a problem.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse

Probably you might want to use this though:

array1.split(",").pop()

QR Code encoding and decoding using zxing

So, for future reference for anybody who doesn't want to spend two days searching the internet to figure this out, when you encode byte arrays into QR Codes, you have to use the ISO-8859-1character set, not UTF-8.

DateTime.TryParseExact() rejecting valid formats

Try:

 DateTime.TryParseExact(txtStartDate.Text, formats, 
        System.Globalization.CultureInfo.InvariantCulture,
        System.Globalization.DateTimeStyles.None, out startDate)

Given URL is not allowed by the Application configuration

For me it was the "Single Sign On" (can be seen at the bottome of the screenshot in phwd's answer) setting that was turned off.

When to use IList and when to use List

It's always best to use the lowest base type possible. This gives the implementer of your interface, or consumer of your method, the opportunity to use whatever they like behind the scenes.

For collections you should aim to use IEnumerable where possible. This gives the most flexibility but is not always suited.

laravel throwing MethodNotAllowedHttpException

I encountered this problem as well and the other answers here were helpful, but I am using a Route::resource which takes care of GET, POST, and other requests.

In my case I left my route as is:

Route::resource('file', 'FilesController');

And simply modified my form to submit to the store function in my FilesController

{{ Form::open(array('route' => 'file.store')) }}

This fixed the issue, and I thought it was worth pointing out as a separate answer since various other answers suggest adding a new POST route. This is an option but it's not necessary.

How do I define and use an ENUM in Objective-C?

Apple provides a macro to help provide better code compatibility, including Swift. Using the macro looks like this.

typedef NS_ENUM(NSInteger, PlayerStateType) {
  PlayerStateOff,
  PlayerStatePlaying,
  PlayerStatePaused
};

Documented here

How to show Page Loading div until the page has finished loading?

I've needed this and after some research I came up with this (jQuery needed):

First, right after the <body> tag add this:

<div id="loading">
  <img id="loading-image" src="images/ajax-loader.gif" alt="Loading..." />
</div>

Then add the style class for the div and image to your CSS:

#loading {
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  position: fixed;
  display: block;
  opacity: 0.7;
  background-color: #fff;
  z-index: 99;
  text-align: center;
}

#loading-image {
  position: absolute;
  top: 100px;
  left: 240px;
  z-index: 100;
}

Then, add this javascript to your page (preferably at the end of your page, before your closing </body> tag, of course):

<script>
  $(window).load(function() {
    $('#loading').hide();
  });
</script>

Finally, adjust the position of the loading image and the background-colour of the loading div with the style class.

This is it, should work just fine. But of course you have to have an ajax-loader.gif somewhere. Freebies here. (Right-click > Save Image As...)

Setting up FTP on Amazon Cloud Server

It will not be ok until you add your user to the group www by the following commands:

sudo usermod -a -G www <USER>

This solves the permission problem.

Set the default path by adding this:

local_root=/var/www/html

Rails 4: List of available datatypes

Here are all the Rails 4 (ActiveRecord migration) datatypes:

  • :binary
  • :boolean
  • :date
  • :datetime
  • :decimal
  • :float
  • :integer
  • :bigint
  • :primary_key
  • :references
  • :string
  • :text
  • :time
  • :timestamp

Source: http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_column
These are the same as with Rails 3.

If you use PostgreSQL, you can also take advantage of these:

  • :hstore
  • :json
  • :jsonb
  • :array
  • :cidr_address
  • :ip_address
  • :mac_address

They are stored as strings if you run your app with a not-PostgreSQL database.

Edit, 2016-Sep-19:

There's a lot more postgres specific datatypes in Rails 4 and even more in Rails 5.

When to use MyISAM and InnoDB?

Use MyISAM for very unimportant data or if you really need those minimal performance advantages. The read performance is not better in every case for MyISAM.

I would personally never use MyISAM at all anymore. Choose InnoDB and throw a bit more hardware if you need more performance. Another idea is to look at database systems with more features like PostgreSQL if applicable.

EDIT: For the read-performance, this link shows that innoDB often is actually not slower than MyISAM: https://www.percona.com/blog/2007/01/08/innodb-vs-myisam-vs-falcon-benchmarks-part-1/

How can I rename column in laravel using migration?

I know this is an old question, but I faced the same problem recently in Laravel 7 application. To make renaming columns work I used a tip from this answer where instead of composer require doctrine/dbal I have issued composer require doctrine/dbal:^2.12.1 because the latest version of doctrine/dbal still throws an error.

Just keep in mind that if you already use a higher version, this answer might not be appropriate for you.

Check if value is zero or not null in python

You can check if it can be converted to decimal. If yes, then its a number

from decimal import Decimal

def is_number(value):
    try:
        value = Decimal(value)
        return True
    except:
        return False

print is_number(None)   // False
print is_number(0)      // True
print is_number(2.3)    // True
print is_number('2.3')  // True (caveat!)

I want to add a JSONObject to a JSONArray and that JSONArray included in other JSONObject

JSONObject json = new JSONObject();
json.put("fromZIPCode","123456"); 

JSONObject json1 = new JSONObject();
json1.put("fromZIPCode","123456"); 
       sList.add(json1);
       sList.add(json);

System.out.println(sList);

Output will be

[{"fromZIPCode":"123456"},{"fromZIPCode":"123456"}]

Getting Hour and Minute in PHP

Try this:

$hourMin = date('H:i');

This will be 24-hour time with an hour that is always two digits. For all options, see the PHP docs for date().

Convert base-2 binary number string to int

Another way to do this is by using the bitstring module:

>>> from bitstring import BitArray
>>> b = BitArray(bin='11111111')
>>> b.uint
255

Note that the unsigned integer is different from the signed integer:

>>> b.int
-1

The bitstring module isn't a requirement, but it has lots of performant methods for turning input into and from bits into other forms, as well as manipulating them.

Relative URLs in WordPress

I think this is the kind of question only a core developer could/should answer. I've researched and found the core ticket #17048: URLs delivered to the browser should be root-relative. Where we can find the reasons explained by Andrew Nacin, lead core developer. He also links to this [wp-hackers] thread. On both those links, these are the key quotes on why WP doesn't use relative URLs:

Core ticket:

  • Root-relative URLs aren't really proper. /path/ might not be WordPress, it might be outside of the install. So really it's not much different than an absolute URL.

  • Any relative URLs also make it significantly more difficult to perform transformations when the install is moved. The find-replace is going to be necessary in most situations, and having an absolute URL is ironically more portable for those reasons.

  • absolute URLs are needed in numerous other places. Needing to add these in conditionally will add to processing, as well as introduce potential bugs (and incompatibilities with plugins).

[wp-hackers] thread

  • Relative to what, I'm not sure, as WordPress is often in a subdirectory, which means we'll always need to process the content to then add in the rest of the path. This introduces overhead.

  • Keep in mind that there are two types of relative URLs, with and without the leading slash. Both have caveats that make this impossible to properly implement.

  • WordPress should (and does) store absolute URLs. This requires no pre-processing of content, no overhead, no ambiguity. If you need to relocate, it is a global find-replace in the database.


And, on a personal note, more than once I've found theme and plugins bad coded that simply break when WP_CONTENT_URL is defined.
They don't know this can be set and assume that this is true: WP.URL/wp-content/WhatEver, and it's not always the case. And something will break along the way.


The plugin Relative URLs (linked in edse's Answer), applies the function wp_make_link_relative in a series of filters in the action hook template_redirect. It's quite a simple code and seems a nice option.

Incrementing a date in JavaScript

Tomorrow in one line in pure JS but it's ugly !

new Date(new Date().setDate(new Date().getDate() + 1))

Here is the result :

Thu Oct 12 2017 08:53:30 GMT+0200 (Romance Summer Time)

Iterating through list of list in Python

Create a method to recursively iterate through nested lists. If the current element is an instance of list, then call the same method again. If not, print the current element. Here's an example:

data = [1,2,3,[4,[5,6,7,[8,9]]]]

def print_list(the_list):

    for each_item in the_list:
        if isinstance(each_item, list):
            print_list(each_item)
        else:
            print(each_item)

print_list(data)

CSS show div background image on top of other contained elements

If you are using the background image for the rounded corners then I would rather increase the padding style of the main div to give enough room for the rounded corners of the background image to be visible.

Try increasing the padding of the main div style:

#mainWrapperDivWithBGImage 
{   
    background: url("myImageWithRoundedCorners.jpg") no-repeat scroll 0 0 transparent;   
    height: 248px;   
    margin: 0;   
    overflow: hidden;   
    padding: 10px 10px;   
    width: 996px; 
}

P.S: I assume the rounded corners have a radius of 10px.

Set select option 'selected', by value

Use the change() event after selecting the value. From the docs:

If the field loses focus without the contents having changed, the event is not triggered. To trigger the event manually, apply .change() without arguments:

$("#select_id").val("val2").change();

More information is at .change().

Java current machine name and logged in user?

To get the currently logged in user path:

System.getProperty("user.home");

Error: " 'dict' object has no attribute 'iteritems' "

In Python2, dictionary.iteritems() is more efficient than dictionary.items() so in Python3, the functionality of dictionary.iteritems() has been migrated to dictionary.items() and iteritems() is removed. So you are getting this error.

Use dict.items() in Python3 which is same as dict.iteritems() of Python2.

How to redirect single url in nginx?

If you need to duplicate more than a few redirects, you might consider using a map:

# map is outside of server block
map $uri $redirect_uri {
    ~^/issue1/?$    http://example.com/shop/issues/custom_isse_name1;
    ~^/issue2/?$    http://example.com/shop/issues/custom_isse_name2;
    ~^/issue3/?$    http://example.com/shop/issues/custom_isse_name3;
    # ... or put these in an included file
}

location / {
    try_files $uri $uri/ @redirect-map;
}

location @redirect-map {
    if ($redirect_uri) {  # redirect if the variable is defined
        return 301 $redirect_uri;
    }
}

Why can't static methods be abstract in Java?

Because abstract is a keyword which is applied over Abstract methods do not specify a body. And If we talk about static keyword it belongs to class area.

Get random sample from list while maintaining ordering of items?

Following code will generate a random sample of size 4:

import random

sample_size = 4
sorted_sample = [
    mylist[i] for i in sorted(random.sample(range(len(mylist)), sample_size))
]

(note: with Python 2, better use xrange instead of range)

Explanation

random.sample(range(len(mylist)), sample_size)

generates a random sample of the indices of the original list.

These indices then get sorted to preserve the ordering of elements in the original list.

Finally, the list comprehension pulls out the actual elements from the original list, given the sampled indices.

Check if one list contains element from the other

There is one method of Collection named retainAll but having some side effects for you reference

Retains only the elements in this list that are contained in the specified collection (optional operation). In other words, removes from this list all of its elements that are not contained in the specified collection.

true if this list changed as a result of the call

Its like

boolean b = list1.retainAll(list2);

ThreadStart with parameters

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleApp6
{
    class Program
    {
        static void Main(string[] args)
        {

            int x = 10;
            Thread t1 =new Thread(new ParameterizedThreadStart(order1));
            t1.IsBackground = true;//i can stope 
            t1.Start(x);

            Thread t2=new Thread(order2);
            t2.Priority = ThreadPriority.Highest;
            t2.Start();

            Console.ReadKey();
        }//Main

        static void  order1(object args)
        {
            int x = (int)args;


                for (int i = 0; i < x; i++)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write(i.ToString() + " ");
            }
        }

        static void order2()
        {
            for (int i = 100; i > 0; i--)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write(i.ToString() + " ");
            }
        }`enter code here`
    }
}

Reference to non-static member function must be called

You may want to have a look at https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types, especially [33.1] Is the type of "pointer-to-member-function" different from "pointer-to-function"?

Static Block in Java

yes, static block is used for initialize the code and it will load at the time JVM start for execution.

static block is used in previous versions of java but in latest version it doesn't work.

In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

For chat applications or any other application that is in constant conversation with the server, WebSockets are the best option. However, you can only use WebSockets with a server that supports them, so that may limit your ability to use them if you cannot install the required libraries. In which case, you would need to use Long Polling to obtain similar functionality.

How do I install a NuGet package .nupkg file locally?

For Visual Studio 2017 and its new .csproj format

You can no longer just use Install-Package to point to a local file. (That's likely because the PackageReference element doesn't support file paths; it only allows you to specify the package's Id.)

You first have to tell Visual Studio about the location of your package, and then you can add it to a project. What most people do is go into the NuGet Package Manager and add the local folder as a source (menu Tools ? Options ? NuGet Package Manager ? Package Sources). But that means your dependency's location isn't committed (to version-control) with the rest of your codebase.

Local NuGet packages using a relative path

This will add a package source that only applies to a specific solution, and you can use relative paths.

You need to create a nuget.config file in the same directory as your .sln file. Configure the file with the package source(s) you want. When you next open the solution in Visual Studio 2017, any .nupkg files from those source folders will be available. (You'll see the source(s) listed in the Package Manager, and you'll find the packages on the "Browse" tab when you're managing packages for a project.)

Here's an example nuget.config to get you started:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <packageSources>
        <add key="MyLocalSharedSource" value="..\..\..\some\folder" />
    </packageSources>
</configuration>

Backstory

My use case for this functionality is that I have multiple instances of a single code repository on my machine. There's a shared library within the codebase that's published/deployed as a .nupkg file. This approach allows the various dependent solutions throughout our codebase to use the package within the same repository instance. Also, someone with a fresh install of Visual Studio 2017 can just checkout the code wherever they want, and the dependent solutions will successfully restore and build.

Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

It depends on the length of the array. If the array length is <= 1,000,000, the slice and concat methods are taking approximately the same time. But when you give a wider range, the concat method wins.

For example, try this code:

var original_array = [];
for(var i = 0; i < 10000000; i ++) {
    original_array.push( Math.floor(Math.random() * 1000000 + 1));
}

function a1() {
    var dup = [];
    var start = Date.now();
    dup = original_array.slice();
    var end = Date.now();
    console.log('slice method takes ' + (end - start) + ' ms');
}

function a2() {
    var dup = [];
    var start = Date.now();
    dup = original_array.concat([]);
    var end = Date.now();
    console.log('concat method takes ' + (end - start) + ' ms');
}

function a3() {
    var dup = [];
    var start = Date.now();
    for(var i = 0; i < original_array.length; i ++) {
        dup.push(original_array[i]);
    }
    var end = Date.now();
    console.log('for loop with push method takes ' + (end - start) + ' ms');
}

function a4() {
    var dup = [];
    var start = Date.now();
    for(var i = 0; i < original_array.length; i ++) {
        dup[i] = original_array[i];
    }
    var end = Date.now();
    console.log('for loop with = method takes ' + (end - start) + ' ms');
}

function a5() {
    var dup = new Array(original_array.length)
    var start = Date.now();
    for(var i = 0; i < original_array.length; i ++) {
        dup.push(original_array[i]);
    }
    var end = Date.now();
    console.log('for loop with = method and array constructor takes ' + (end - start) + ' ms');
}

a1();
a2();
a3();
a4();
a5();

If you set the length of original_array to 1,000,000, the slice method and concat method are taking approximately the same time (3-4 ms, depending on the random numbers).

If you set the length of original_array to 10,000,000, then the slice method takes over 60 ms and the concat method takes over 20 ms.

select unique rows based on single distinct column

If you are using MySql 5.7 or later, according to these links (MySql Official, SO QA), we can select one record per group by with out the need of any aggregate functions.

So the query can be simplified to this.

select * from comments_table group by commentname;

Try out the query in action here

Best practice for localization and globalization of strings and labels

As far as I know, there's a good library called localeplanet for Localization and Internationalization in JavaScript. Furthermore, I think it's native and has no dependencies to other libraries (e.g. jQuery)

Here's the website of library: http://www.localeplanet.com/

Also look at this article by Mozilla, you can find very good method and algorithms for client-side translation: http://blog.mozilla.org/webdev/2011/10/06/i18njs-internationalize-your-javascript-with-a-little-help-from-json-and-the-server/

The common part of all those articles/libraries is that they use a i18n class and a get method (in some ways also defining an smaller function name like _) for retrieving/converting the key to the value. In my explaining the key means that string you want to translate and the value means translated string.
Then, you just need a JSON document to store key's and value's.

For example:

var _ = document.webL10n.get;
alert(_('test'));

And here the JSON:

{ test: "blah blah" }

I believe using current popular libraries solutions is a good approach.

CSS hexadecimal RGBA?

why not use background-color: #ff0000; opacity: 0.5; filter: alpha(opacity=50); /* in IE */

if you target a color for a text or probably an element, this should be a lot easier to do.

Getting error "No such module" using Xcode, but the framework is there

I had the same issue using Cocoapods and Swift. I didn't notice the following lines in the Podfile:

# Uncomment this line if you're using Swift
# use_frameworks!

So, all I had to do was change it to:

# Uncomment this line if you're using Swift
use_frameworks!

...aaand it worked :)

Jquery/Ajax Form Submission (enctype="multipart/form-data" ). Why does 'contentType:False' cause undefined index in PHP?

contentType option to false is used for multipart/form-data forms that pass files.

When one sets the contentType option to false, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multipart/form-data, one must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.


To try and fix your issue:

Use jQuery's .serialize() method which creates a text string in standard URL-encoded notation.

You need to pass un-encoded data when using contentType: false.

Try using new FormData instead of .serialize():

  var formData = new FormData($(this)[0]);

See for yourself the difference of how your formData is passed to your php page by using console.log().

  var formData = new FormData($(this)[0]);
  console.log(formData);

  var formDataSerialized = $(this).serialize();
  console.log(formDataSerialized);

Real differences between "java -server" and "java -client"?

IIRC the server VM does more hotspot optimizations at startup so it runs faster but takes a little longer to start and uses more memory. The client VM defers most of the optimization to allow faster startup.

Edit to add: Here's some info from Sun, it's not very specific but will give you some ideas.

How to convert BigDecimal to Double in Java?

You need to use the doubleValue() method to get the double value from a BigDecimal object.

BigDecimal bd; // the value you get
double d = bd.doubleValue(); // The double you want

byte[] to file in Java

Basic example:

String fileName = "file.test";

BufferedOutputStream bs = null;

try {

    FileOutputStream fs = new FileOutputStream(new File(fileName));
    bs = new BufferedOutputStream(fs);
    bs.write(byte_array);
    bs.close();
    bs = null;

} catch (Exception e) {
    e.printStackTrace()
}

if (bs != null) try { bs.close(); } catch (Exception e) {}

How to completely DISABLE any MOUSE CLICK

To disable all mouse click

var event = $(document).click(function(e) {
    e.stopPropagation();
    e.preventDefault();
    e.stopImmediatePropagation();
    return false;
});

// disable right click
$(document).bind('contextmenu', function(e) {
    e.stopPropagation();
    e.preventDefault();
    e.stopImmediatePropagation();
    return false;
});

to enable it again:

$(document).unbind('click');
$(document).unbind('contextmenu');

Selecting fields from JSON output

Assume you stored that dictionary in a variable called values. To get id in to a variable, do:

idValue = values['criteria'][0]['id']

If that json is in a file, do the following to load it:

import json
jsonFile = open('your_filename.json', 'r')
values = json.load(jsonFile)
jsonFile.close()

If that json is from a URL, do the following to load it:

import urllib, json
f = urllib.urlopen("http://domain/path/jsonPage")
values = json.load(f)
f.close()

To print ALL of the criteria, you could:

for criteria in values['criteria']:
    for key, value in criteria.iteritems():
        print key, 'is:', value
    print ''

Scala Doubles, and Precision

You can use scala.math.BigDecimal:

BigDecimal(1.23456789).setScale(2, BigDecimal.RoundingMode.HALF_UP).toDouble

There are a number of other rounding modes, which unfortunately aren't very well documented at present (although their Java equivalents are).

SQL Greater than, Equal to AND Less Than

Supposing you use sql server:

WHERE StartTime BETWEEN DATEADD(HOUR, -1, GetDate())
                    AND DATEADD(HOUR, 1, GetDate())

Primefaces valueChangeListener or <p:ajax listener not firing for p:selectOneMenu

this works for me:

It can be used inside the dialog, but the dialog can´t be inside any componet such as panels, accordion, etc.

Border color on default input style

If it is an Angular application you can simply do this

input.ng-invalid.ng-touched
{
    border: 1px solid red !important; 
}

Python equivalent to 'hold on' in Matlab

check pyplot docs. For completeness,

import numpy as np
import matplotlib.pyplot as plt

#evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)

# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()

Converting a String array into an int Array in java

To get rid of additional whitespace, you could change the code like this:

intarray[i]=Integer.parseInt(str.trim()); // No more Exception in this line

Create tap-able "links" in the NSAttributedString of a UILabel?

Yes this is possible albeit very confusing to figure out at first. I will go a step further and show you how you can even click on any area in the text as well.

With this method you can have UI Label tha is:

  • Multiline Friendly
  • Autoshrink Friendly
  • Clickable Friendly (yes, even individual characters)
  • Swift 5

Step 1:

Make the UILabel have the properties for Line Break of 'Truncate Tail' and set a minimum font scale.

If you are unfamiliar with font scale just remember this rule:

minimumFontSize/defaultFontSize = fontscale

In my case I wanted 7.2 to be the minimum font size and my starting font size was 36. Therefore, 7.2 / 36 = 0.2

enter image description here

Step 2:

If you do not care about the labels being clickable and just wanted a working multiline label you are done!

HOWEVER, if you want the labels to be clickable read on...

Add this following extension I created

extension UILabel {

    func setOptimalFontSize(maxFontSize:CGFloat,text:String){
        let width = self.bounds.size.width

        var font_size:CGFloat = maxFontSize //Set the maximum font size.
        var stringSize = NSString(string: text).size(withAttributes: [.font : self.font.withSize(font_size)])
        while(stringSize.width > width){
            font_size = font_size - 1
            stringSize = NSString(string: text).size(withAttributes: [.font : self.font.withSize(font_size)])
        }

        self.font = self.font.withSize(font_size)//Forcefully change font to match what it would be graphically.
    }
}

It's used like this (just replace <Label> with your actual label name):

<Label>.setOptimalFontSize(maxFontSize: 36.0, text: formula)

This extension is needed because auto shrink does NOT change the 'font' property of the label after it auto-shrinks so you have to deduce it by calculating it the same way it does by using .size(withAttributes) function which simulates what it's size would be with that particular font.

This is necessary because the solution for detecting where to click on the label requires the exact font size to be known.

Step 3:

Add the following extension:

extension UITapGestureRecognizer {

    func didTapAttributedTextInLabel(label: UILabel, inRange targetRange: NSRange) -> Bool {
        // Create instances of NSLayoutManager, NSTextContainer and NSTextStorage
        let layoutManager = NSLayoutManager()
        let textContainer = NSTextContainer(size: CGSize.zero)

        let mutableAttribString = NSMutableAttributedString(attributedString: label.attributedText!)
        mutableAttribString.addAttributes([NSAttributedString.Key.font: label.font!], range: NSRange(location: 0, length: label.attributedText!.length))

        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 6
        paragraphStyle.lineBreakMode = .byTruncatingTail
        paragraphStyle.alignment = .center
        mutableAttribString.addAttributes([.paragraphStyle: paragraphStyle], range: NSMakeRange(0, mutableAttribString.string.count))

        let textStorage = NSTextStorage(attributedString: mutableAttribString)

        // Configure textContainer
        textContainer.lineFragmentPadding = 0.0
        textContainer.lineBreakMode = label.lineBreakMode
        textContainer.maximumNumberOfLines = label.numberOfLines

        // Configure layoutManager and textStorage
        layoutManager.addTextContainer(textContainer)

        textStorage.addLayoutManager(layoutManager)

        let labelSize = label.bounds.size

        textContainer.size = labelSize

        // Find the tapped character location and compare it to the specified range
        let locationOfTouchInLabel = self.location(in: label)

        let textBoundingBox = layoutManager.usedRect(for: textContainer)
        //let textContainerOffset = CGPointMake((labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x,
                                              //(labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y);
        let textContainerOffset = CGPoint(x: (labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x, y: (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y)

        //let locationOfTouchInTextContainer = CGPointMake(locationOfTouchInLabel.x - textContainerOffset.x,
                                                        // locationOfTouchInLabel.y - textContainerOffset.y);
        let locationOfTouchInTextContainer = CGPoint(x: locationOfTouchInLabel.x - textContainerOffset.x, y: locationOfTouchInLabel.y - textContainerOffset.y)

        let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
        print("IndexOfCharacter=",indexOfCharacter)

        print("TargetRange=",targetRange)
        return NSLocationInRange(indexOfCharacter, targetRange)
    }

}

You will need to modify this extension for your particular multiline situation. In my case you will notice that I use a paragraph style.

let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 6
        paragraphStyle.lineBreakMode = .byTruncatingTail
        paragraphStyle.alignment = .center
        mutableAttribString.addAttributes([.paragraphStyle: paragraphStyle], range: NSMakeRange(0, mutableAttribString.string.count))

Make sure to change this in the extension to what you are actually using for your line spacing so that everything calculates correctly.

Step 4:

Add the gestureRecognizer to the label in viewDidLoad or where you think is appropriate like so (just replace <Label> with your label name again:

<Label>.addGestureRecognizer(UITapGestureRecognizer(target:self, action: #selector(tapLabel(gesture:))))

Here is a simplified example of my tapLabel function (just replace <Label> with your UILabel name):

@IBAction func tapLabel(gesture: UITapGestureRecognizer) {
        guard let text = <Label>.attributedText?.string else {
            return
        }

        let click_range = text.range(of: "(a/ß)")

        if gesture.didTapAttributedTextInLabel(label: <Label>, inRange: NSRange(click_range!, in: text)) {
           print("Tapped a/b")
        }else {
           print("Tapped none")
        }
    }

Just a note in my example, my string is BED = N * d * [ RBE + ( d / (a/ß) ) ], so I was just getting the range of the a/ß in this case. You could add "\n" to the string to add a newline and whatever text you wanted after and test this to find a string on the next line and it will still find it and detect the click correctly!

That's it! You are done. Enjoy a multiline clickable label.

What is the difference between json.dump() and json.dumps() in python?

The functions with an s take string parameters. The others take file streams.

Listing only directories using ls in Bash?

For all folders without subfolders:

find /home/alice/Documents -maxdepth 1 -type d

For all folders with subfolders:

find /home/alice/Documents -type d

Creating InetAddress object in Java

You should be able to use getByName or getByAddress.

The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address

InetAddress addr = InetAddress.getByName("127.0.0.1");

The method that takes a byte array can be used like this:

byte[] ipAddr = new byte[]{127, 0, 0, 1};
InetAddress addr = InetAddress.getByAddress(ipAddr);

Bootstrap - Uncaught TypeError: Cannot read property 'fn' of undefined

I had the same problem. Firefox showed me this error but in chrome everything was OK. then after a google search, i used google cdn for jquery in index.html instead of loading local js file and the problem solved.

Converting ArrayList to Array in java

You don't need to reinvent the wheel, here's the toArray() method:

String []dsf = new String[al.size()];
al.toArray(dsf);

Submitting a form on 'Enter' with jQuery?

$('.input').keypress(function (e) {
  if (e.which == 13) {
    $('form#login').submit();
    return false;    //<---- Add this line
  }
});

Check out this stackoverflow answer: event.preventDefault() vs. return false

Essentially, "return false" is the same as calling e.preventDefault and e.stopPropagation().

Fail during installation of Pillow (Python module) in Linux

On debian / ubuntu you only need: libjpeg62-turbo-dev

So a simple sudo apt install libjpeg62-turbo-dev and a pip install pillow

Format Date/Time in XAML in Silverlight

C#: try this

  • yyyy(yy/yyy) - years
  • MM - months(like '03'), MMMM - months(like 'March')
  • dd - days(like 09), ddd/dddd - days(Sun/Sunday)
  • hh - hour 12(AM/PM), HH - hour 24
  • mm - minute
  • ss - second

Use some delimeter,like this:

  1. MessageBox.Show(DateValue.ToString("yyyy-MM-dd")); example result: "2014-09-30"
  2. empty format string: MessageBox.Show(DateValue.ToString()); example result: "30.09.2014 0:00:00"

How to select last one week data from today's date

to select records for the last 7 days

WHERE Created_Date >= DATEADD(day, -7, GETDATE())

to select records for the current week

SET DATEFIRST 1 -- Define beginning of week as Monday
SELECT * FROM
WHERE CreatedDate >= DATEADD(day, 1 - DATEPART(dw, GETDATE()), CONVERT(DATE, GETDATE())) 
  AND CreatedDate <  DATEADD(day, 8 - DATEPART(dw, GETDATE()), CONVERT(DATE, GETDATE()))

if you want to select records for last week instead of the last 7 days

SET DATEFIRST 1 -- Define beginning of week as Monday
SELECT * FROM  
WHERE CreatedDate >= DATEADD(day, -(DATEPART(dw, GETDATE()) + 6), CONVERT(DATE, GETDATE())) 
  AND CreatedDate <  DATEADD(day, 1 - DATEPART(dw, GETDATE()), CONVERT(DATE, GETDATE()))

How can I print message in Makefile?

$(info your_text) : Information. This doesn't stop the execution.

$(warning your_text) : Warning. This shows the text as a warning.

$(error your_text) : Fatal Error. This will stop the execution.

insert password into database in md5 format?

if you want to use md5 encryptioon you can do it in your php script

$pass = $_GET['pass'];

$newPass = md5($pass)

and then insert it into the database that way, however MD5 is a one way encryption method and is near on impossible to decrypt without difficulty

Calculate row means on subset of columns

You can create a new row with $ in your data frame corresponding to the Means

DF$Mean <- rowMeans(DF[,2:4])

ORA-01882: timezone region not found

What happens is, that the JDBC client sends the timezone ID to the Server. The server needs to know that zone. You can check with

SELECT DISTINCT tzname FROM V$TIMEZONE_NAMES where tzname like 'Etc%';

I have some db servers which know about 'Etc/UTC' and 'UTC' (tzfile version 18) but others only know 'UTC' (tz version 11).

SELECT FILENAME,VERSION from V$TIMEZONE_FILE;

There is also different behavior on the JDBC client side. Starting with 11.2 the driver will sent the zone IDs if it is "known" to Oracle, whereas before it sent the time offset. The problem with this "sending of known IDs" is, that the client does not check what timezone version/content is present on the server but has its own list.

This is explained in Oracle Support Article [ID 1068063.1].

It seems it also depends on the Client OS, it was more likely that Etc/UTC fails with Ubuntu than RHEL or Windows. I guess this is due to some normalization but I haven't figured out what exactly.

Get environment value in controller

Try it with:

<?php $hostname = env("IMAP_HOSTNAME_TEST", "somedefaultvalue"); ?>

No newline at end of file

For what it's worth, I encountered this when I created an IntelliJ project on a Mac, and then moved the project over to my Windows machine. I had to manually open every file and change the encoding setting at the bottom right of the IntelliJ window. Probably not happening to most if any who read this question but that could have saved me a couple of hours of work...

Can you control how an SVG's stroke-width is drawn?

No, you cannot specify whether the stroke is drawn inside or outside an element. I made a proposal to the SVG working group for this functionality in 2003, but it received no support (or discussion).

SVG proposed stroke-location example, from phrogz.net/SVG/stroke-location.svg

As I noted in the proposal,

  • you can achieve the same visual result as "inside" by doubling your stroke width and then using a clipping path to clip the object to itself, and
  • you can achieve the same visual result as 'outside' by doubling the stroke width and then overlaying a no-stroke copy of the object on top of itself.

Edit: This answer may be wrong in the future. It should be possible to achieve these results using SVG Vector Effects, by combining veStrokePath with veIntersect (for 'inside') or with veExclude (for 'outside). However, Vector Effects are still a working draft module with no implementations that I can yet find.

Edit 2: The SVG 2 draft specification includes a stroke-alignment property (with center|inside|outside possible values). This property may make it into UAs eventually.

Edit 3: Amusingly and dissapointingly, the SVG working group has removed stroke-alignment from SVG 2. You can see some of the concerns described after the prose here.

How to change JDK version for an Eclipse project

See the page Set Up JDK in Eclipse. From the add button you can add a different version of the JDK...

Passing data to a jQuery UI Dialog

In terms of what you are doing with jQuery, my understanding is that you can chain functions like you have and the inner ones have access to variables from the outer ones. So is your ShowDialog(x) function contains these other functions, you can re-use the x variable within them and it will be taken as a reference to the parameter from the outer function.

I agree with mausch, you should really look at using POST for these actions, which will add a <form> tag around each element, but make the chances of an automated script or tool triggering the Cancel event much less likely. The Change action can remain as is because it (presumably just opens an edit form).

How to set up Android emulator proxy settings

I tried after removing http in the server name and it worked for me.

emulator -avd myavd -http-proxy 168.192.1.2:3300

Git remote branch deleted, but still it appears in 'branch -a'

Use:

git remote prune <remote>

Where <remote> is a remote source name like origin or upstream.

Example: git remote prune origin

Free ASP.Net and/or CSS Themes

I wouldn't bother looking for ASP.NET stuff specifically (probably won't find any anyways). Finding a good CSS theme easily can be used in ASP.NET.

Here's some sites that I love for CSS goodness:

http://www.freecsstemplates.org/
http://www.oswd.org/
http://www.openwebdesign.org/
http://www.styleshout.com/
http://www.freelayouts.com/

Jinja2 template not rendering if-elif-else statement properly

You are testing if the values of the variables error and Already are present in RepoOutput[RepoName.index(repo)]. If these variables don't exist then an undefined object is used.

Both of your if and elif tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].

I think you wanted to test if certain strings are in the value instead:

{% if "error" in RepoOutput[RepoName.index(repo)] %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
    <td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>

Other corrections I made:

  • Used {% elif ... %} instead of {$ elif ... %}.
  • moved the </tr> tag out of the if conditional structure, it needs to be there always.
  • put quotes around the id attribute

Note that most likely you want to use a class attribute instead here, not an id, the latter must have a value that must be unique across your HTML document.

Personally, I'd set the class value here and reduce the duplication a little:

{% if "Already" in RepoOutput[RepoName.index(repo)] %}
    {% set row_class = "good" %}
{% else %}
    {% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>

Where does linux store my syslog?

On my Ubuntu machine, I can see the output at /var/log/syslog.

On a RHEL/CentOS machine, the output is found in /var/log/messages.

This is controlled by the rsyslog service, so if this is disabled for some reason you may need to start it with systemctl start rsyslog.

As noted by others, your syslog() output would be logged by the /var/log/syslog file.
You can see system, user, and other logs at /var/log.

For more details: here's an interesting link.

How different is Scrum practice from Agile Practice?

Agile is not a methodology, embracing the agile manifesto means adopting a particular philosophy about software development. Within that philosophical perspective, there are many processes and practices. Scrum is a set of practices that follow agile principles. Many people grab onto the practices and processes without embracing (or even understanding) the underlying philosophy and they often end up with gorillarinas.

Trim leading and trailing spaces from a string in awk

I just came across this. The correct answer is:

awk 'BEGIN{FS=OFS=","} {gsub(/^[[:space:]]+|[[:space:]]+$/,"",$2)} 1'

How to set the project name/group/version, plus {source,target} compatibility in the same file?

I found the solution to a similar problem. I am using Gradle 1.11 (as April, 2014). The project name can be changed directly in settings.gradle file as following:

  rootProject.name='YourNewName'

This takes care of uploading to repository (Artifactory w/ its plugin for me) with the correct artifactId.

error: src refspec master does not match any

Try following command:

git push origin HEAD:master

Git threw the below error when I tried simply git push. So clearly this is because Git matches the local and remote branch while pushing commits. This is the push.default behavior, you can find out more details here.

fatal: The upstream branch of your current branch does not match
the name of your current branch.  To push to the upstream branch
on the remote, use

    git push origin HEAD:<Branch_Name>

To push to the branch of the same name on the remote, use

    git push origin <Branch_Name>

To choose either option permanently, see push.default in 'git help config'.

Windows git "warning: LF will be replaced by CRLF", is that warning tail backward?

YES the warning is backwards.

And in fact it shouldn't even be a warning in the first place. Because all this warning is saying (but backwards unfortunately) is that the CRLF characters in your file with Windows line endings will be replaced with LF's on commit. Which means it's normalized to the same line endings used by *nix and MacOS.

Nothing strange is going on, this is exactly the behavior you would normally want.

This warning in it's current form is one of two things:

  1. An unfortunate bug combined with an over-cautious warning message, or
  2. A very clever plot to make you really think this through...

;)

How can I join on a stored procedure?

Here's a terrible idea for you.

Use an alias, create a new linked server from your server to its own alias.

Now you can do:

select a.SomeColumns, b.OtherColumns
from LocalDb.dbo.LocalTable a
inner join (select * from openquery([AliasToThisServer],'
exec LocalDb.dbo.LocalStoredProcedure
') ) b
on a.Id = b.Id

What to gitignore from the .idea folder?

https://www.gitignore.io/api/jetbrains

Created by https://www.gitignore.io/api/jetbrains

### JetBrains ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839

# User-specific stuff:
.idea/workspace.xml
.idea/tasks.xml
.idea/dictionaries
.idea/vcs.xml
.idea/jsLibraryMappings.xml

# Sensitive or high-churn files:
.idea/dataSources.ids
.idea/dataSources.xml
.idea/dataSources.local.xml
.idea/sqlDataSources.xml
.idea/dynamic.xml
.idea/uiDesigner.xml

# Gradle:
.idea/gradle.xml
.idea/libraries

# Mongo Explorer plugin:
.idea/mongoSettings.xml

## File-based project format:
*.iws

## Plugin-specific files:

# IntelliJ
/out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties

### JetBrains Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721

# *.iml
# modules.xml
# .idea/misc.xml 
# *.ipr 

How to check which locks are held on a table

You can find blocking sql and wait sql by running this:

SELECT
    t1.resource_type ,
    DB_NAME( resource_database_id) AS dat_name ,
    t1.resource_associated_entity_id,
    t1.request_mode,
    t1.request_session_id,
    t2.wait_duration_ms,
    ( SELECT TEXT FROM sys.dm_exec_requests r CROSS apply sys.dm_exec_sql_text ( r.sql_handle ) WHERE r.session_id = t1.request_session_id ) AS wait_sql,
    t2.blocking_session_id,
    ( SELECT TEXT FROM sys.sysprocesses p CROSS apply sys.dm_exec_sql_text ( p.sql_handle ) WHERE p.spid = t2.blocking_session_id ) AS blocking_sql 
FROM
    sys.dm_tran_locks t1,
    sys.dm_os_waiting_tasks t2 
WHERE
    t1.lock_owner_address = t2.resource_address

sqlite3.OperationalError: unable to open database file

This worked for me:

conn = sqlite3.connect("C:\\users\\guest\\desktop\\example.db")

Note: Double slashes in the full path

Using python v2.7 on Win 7 enterprise and Win Xp Pro

Hope this helps someone.

Access is denied when attaching a database

I'd like to add additional info to the answers that were posted.

Be careful when detaching the database because the windows user you are logged in as becomes the only user with permissions to the .mdf file! The original permissions the .mdf file had which included the user SQLServerMSSQLUser$<computer_name>$<instance_name> and the Administrators account get overwritten by whichever windows user you are logged in as (not sql server user). Boom, all permissions gone just like that. So do as others have said and right click your .mdf file and double check the permissions.

I ran into this problem because I used SSMS to connect to the database (doesn't matter which sql server account) and detached the database. After doing that my windows user was the only one that had any permissions to the .mdf file. So later on when I tried to attach the db using the sa account, it threw the "access denied" error.

To keep the original permissions in tact you should take the database offline, then detach, then attach in that order like so:

USE [master]
GO
-- kick all users out of the db
ALTER DATABASE mydb
SET SINGLE_USER WITH ROLLBACK IMMEDIATE 
GO

-- Take the Database Offline
ALTER DATABASE mydb SET OFFLINE WITH
ROLLBACK IMMEDIATE
GO

-- detach the db
EXEC master.dbo.sp_detach_db @dbname = N'mydb'
GO

Disable autocomplete via CSS

You can use a generated id and name everytime, which is different, so the browser cannot remember this text-field and will fail to suggest some values.

This is at least the cross browser safe alternative, but I would recommend to go with the answer from RobertsonM (autocomplete="off").

IndexError: too many indices for array

The message that you are getting is not for the default Exception of Python:

For a fresh python list, IndexError is thrown only on index not being in range (even docs say so).

>>> l = []
>>> l[1]
IndexError: list index out of range

If we try passing multiple items to list, or some other value, we get the TypeError:

>>> l[1, 2]
TypeError: list indices must be integers, not tuple

>>> l[float('NaN')]
TypeError: list indices must be integers, not float

However, here, you seem to be using matplotlib that internally uses numpy for handling arrays. On digging deeper through the codebase for numpy, we see:

static NPY_INLINE npy_intp
unpack_tuple(PyTupleObject *index, PyObject **result, npy_intp result_n)
{
    npy_intp n, i;
    n = PyTuple_GET_SIZE(index);
    if (n > result_n) {
        PyErr_SetString(PyExc_IndexError,
                        "too many indices for array");
        return -1;
    }
    for (i = 0; i < n; i++) {
        result[i] = PyTuple_GET_ITEM(index, i);
        Py_INCREF(result[i]);
    }
    return n;
}

where, the unpack method will throw an error if it the size of the index is greater than that of the results.

So, Unlike Python which raises a TypeError on incorrect Indexes, Numpy raises the IndexError because it supports multidimensional arrays.

Response::json() - Laravel 5.1

However, the previous answer could still be confusing for some programmers. Most especially beginners who are most probably using an older book or tutorial. Or perhaps you still feel the facade is needed. Sure you can use it. Me for one I still love to use the facade, this is because some times while building my api I forget to use the '\' before the Response.

if you are like me, simply add

   "use Response;"

above your class ...extends contoller. this should do.

with this you can now use:

$response = Response::json($posts, 200);

instead of:

$response = \Response::json($posts, 200);

Temporary table in SQL server causing ' There is already an object named' error

In Azure Data warehouse also this occurs sometimes, because temporary tables created for a user session.. I got the same issue fixed by reconnecting the database,

Link to a section of a webpage

Hashtags at the end of the URL bring a visitor to the element with the ID: e.g.

http://stackoverflow.com/questions/8424785/link-to-a-section-of-a-webpage#answers 

Would bring you to where the DIV with the ID 'answers' begins. Also, you can use the name attribute in anchor tags, to create the same effect.

Resource

The view or its master was not found or no view engine supports the searched locations

Check the build action of your view (.cshtml file) It should be set to content. In some cases, I have seen that the build action was set to None (by mistake) and this particular view was not deploy on the target machine even though you see that view present in visual studio project file under valid folder

Get ASCII value at input word

char (with a lower-case c) is a numeric type. It already holds the ascii value of the char. Just cast it to an integer to display it as a numeric value rather than a textual value:

System.out.println("char " + ch + " has the following value : " + (int) ch);

When should the xlsm or xlsb formats be used?

They're all similar in that they're essentially zip files containing the actual file components. You can see the contents just by replacing the extension with .zip and opening them up. The difference with xlsb seems to be that the components are not XML-based but are in a binary format: supposedly this is beneficial when working with large files.

https://blogs.msdn.microsoft.com/dmahugh/2006/08/22/new-binary-file-format-for-spreadsheets/

Bootstrap: how do I change the width of the container?

Add these piece of CSS in your css styling. Its better to add this after the bootstrap css file is added in order to overwrite the same.

html, body {
 height: 100%;
 max-width: 100%;
 overflow-x: hidden;
}`

How to get a single value from FormGroup

This code also works:

this.formGroup.controls.nameOfcontrol.value

WordPress asking for my FTP credentials to install plugins

The easiest way to solve this problem is add the following FTP information to your wp-config.php

define('FS_METHOD', 'direct');
define('FTP_BASE', '/usr/home/username/public_html/my-site.example.com/wordpress/');
define('FTP_CONTENT_DIR', '/usr/home/username/public_html/my-site.example.com/wordpress/wp-content/');
define('FTP_PLUGIN_DIR ', '/usr/home/username/public_html/my-site.example.com/wordpress/wp-content/plugins/');

FTP_BASE is the full path to the "base"(ABSPATH) folder of the WordPress installation FTP_CONTENT_DIR is the full path to the wp-content folder of the WordPress installation. FTP_PLUGIN_DIR is the full path to the plugins folder of the WordPress installation.

How to install a plugin in Jenkins manually

Sometimes when you download plugins you may get (.zip) files then just rename with (.hpi) and then extract all the plugins and move to <jenkinsHome>/plugins/ directory.

whitespaces in the path of windows filepath

Try putting double quotes in your filepath variable

"\"E:/ABC/SEM 2/testfiles/all.txt\""

Check the permissions of the file or in any case consider renaming the folder to remove the space

Xcode build failure "Undefined symbols for architecture x86_64"

in my case I had to add

    target 'SomeTargetTests' do
        inherit! :search_paths
    end
to my podfile and then delete the /Pods directory and run `pod install`

(Xcode 10.1)

How can I loop through enum values for display in radio buttons?

Two options:

for (let item in MotifIntervention) {
    if (isNaN(Number(item))) {
        console.log(item);
    }
}

Or

Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

(code in playground)


Edit

String enums look different than regular ones, for example:

enum MyEnum {
    A = "a",
    B = "b",
    C = "c"
}

Compiles into:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

Which just gives you this object:

{
    A: "a",
    B: "b",
    C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():

Object.values(MyEnum)

Kill a Process by Looking up the Port being used by it from a .BAT

if you by system you cannot end task it. try this command

x:> net stop http /y

Replace contents of factor column in R dataframe

You can use the function revalue from the package plyr to replace values in a factor vector.

In your example to replace the factor virginica by setosa:

 data(iris)
 library(plyr)
 revalue(iris$Species, c("virginica" = "setosa")) -> iris$Species

Remove all special characters with RegExp

The first solution does not work for any UTF-8 alphabet. (It will cut text such as ????). I have managed to create a function which does not use RegExp and use good UTF-8 support in the JavaScript engine. The idea is simple if a symbol is equal in uppercase and lowercase it is a special character. The only exception is made for whitespace.

function removeSpecials(str) {
    var lower = str.toLowerCase();
    var upper = str.toUpperCase();

    var res = "";
    for(var i=0; i<lower.length; ++i) {
        if(lower[i] != upper[i] || lower[i].trim() === '')
            res += str[i];
    }
    return res;
}

Update: Please note, that this solution works only for languages where there are small and capital letters. In languages like Chinese, this won't work.

Update 2: I came to the original solution when I was working on a fuzzy search. If you also trying to remove special characters to implement search functionality, there is a better approach. Use any transliteration library which will produce you string only from Latin characters and then the simple Regexp will do all magic of removing special characters. (This will work for Chinese also and you also will receive side benefits by making Tromsø == Tromso).

Converting binary to decimal integer output

I started working on this problem a long time ago, trying to write my own binary to decimal converter function. I don't actually know how to convert decimal to binary though! I just revisited it today and figured it out and this is what I came up with. I'm not sure if this is what you need, but here it is:

def __degree(number):
    power = 1

    while number % (10**power) != number:
        power += 1

    return power

def __getDigits(number):
    digits = []
    degree = __degree(number)

    for x in range(0, degree):
        digits.append(int(((number % (10**(degree-x))) - (number % (10**(degree-x-1)))) / (10**(degree-x-1))))
    return digits

def binaryToDecimal(number):
    list = __getDigits(number)
    decimalValue = 0
    for x in range(0, len(list)):
        if (list[x] is 1):
            decimalValue += 2**(len(list) - x - 1)
    return decimalValue

Again, I'm still learning Python just on my own, hopefully this helps. The first function determines how many digits there are, the second function actually figures out they are and returns them in a list, and the third function is the only one you actually need to call, and it calculates the decimal value. If your teacher actually wanted you to write your own converter, this works, I haven't tested it with every number, but it seems to work perfectly! I'm sure you'll all find the bugs for me! So anyway, I just called it like:

binaryNum = int(input("Enter a binary number: "))

print(binaryToDecimal(binaryNum))

This prints out the correct result. Cheers!

python 3.x ImportError: No module named 'cStringIO'

I had the same issue because my file was called email.py. I renamed the file and the issue disappeared.