Programs & Examples On #Java.util.date

Through Java 7, the official class for representing a moment in time, using a thin wrapper around the number of milliseconds from epoch (1970-01-01). In Java 8, java.time.Instant and related classes were introduced as a replacement.

Convert java.util.date default format to Timestamp in Java

You can use the Calendar class to convert Date

public long getDifference()
{
    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy");
    Date d = sdf.parse("Mon May 27 11:46:15 IST 2013");

    Calendar c = Calendar.getInstance();
    c.setTime(d);
    long time = c.getTimeInMillis();
    long curr = System.currentTimeMillis();
    long diff = curr - time;    //Time difference in milliseconds
    return diff/1000;
}

How to add minutes to my Date

The issue for you is that you are using mm. You should use MM. MM is for month and mm is for minutes. Try with yyyy-MM-dd HH:mm

Other approach:

It can be as simple as this (other option is to use joda-time)

static final long ONE_MINUTE_IN_MILLIS=60000;//millisecs

Calendar date = Calendar.getInstance();
long t= date.getTimeInMillis();
Date afterAddingTenMins=new Date(t + (10 * ONE_MINUTE_IN_MILLIS));

How to set time zone of a java.util.Date?

You could also set the timezone at the JVM level

Date date1 = new Date();
System.out.println(date1);

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
// or pass in a command line arg: -Duser.timezone="UTC"

Date date2 = new Date();
System.out.println(date2);

output:

Thu Sep 05 10:11:12 EDT 2013
Thu Sep 05 14:11:12 UTC 2013

Get the current date in java.sql.Date format

tl;dr

myPreparedStatement.setObject(   // Directly exchange java.time objects with database without the troublesome old java.sql.* classes.
    … ,                                   
    LocalDate.parse(             // Parse string as a `LocalDate` date-only value.
        "2018-01-23"             // Input string that complies with standard ISO 8601 formatting.
    ) 
)

java.time

The modern approach uses the java.time classes that supplant the troublesome old legacy classes such as java.util.Date and java.sql.Date.

For a date-only value, use LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.

The java.time classes use standard formats when parsing/generating strings. So no need to specify a formatting pattern.

LocalDate ld = LocalDate.parse( input ) ;

You can directly exchange java.time objects with your database using a JDBC driver compliant with JDBC 4.2 or later. You can forget about transforming in and out of java.sql.* classes.

myPreparedStatement.setObject( … , ld ) ;

Retrieval:

LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to convert ZonedDateTime to Date?

For a docker application like beehuang commented you should set your timezone.

Alternatively you can use withZoneSameLocal. For example:

2014-07-01T00:00+02:00[GMT+02:00] is converted by

Date.from(zonedDateTime.withZoneSameLocal(ZoneId.systemDefault()).toInstant())

to Tue Jul 01 00:00:00 CEST 2014 and by

Date.from(zonedDateTime.toInstant())

to Mon Jun 30 22:00:00 UTC 2014

Calculating the difference between two Java date instances

If you have d1 and d2 as your dates, the best solution is probably the following:

int days1 = d1.getTime()/(60*60*24*1000);//find the number of days since the epoch.
int days2 = d2.getTime()/(60*60*24*1000);

then just say

days2-days1

or whatever

How to subtract X day from a Date object in Java?

As you can see HERE there is a lot of manipulation you can do. Here an example showing what you could do!

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();

//Add one day to current date.
cal.add(Calendar.DATE, 1);
System.out.println(dateFormat.format(cal.getTime()));

//Substract one day to current date.
cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
System.out.println(dateFormat.format(cal.getTime()));

/* Can be Calendar.DATE or
*  Calendar.MONTH, Calendar.YEAR, Calendar.HOUR, Calendar.SECOND
*/

Convert java.util.Date to String

Let's try this

public static void main(String args[]) {

    Calendar cal = GregorianCalendar.getInstance();
    Date today = cal.getTime();
    DateFormat df7 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    try {           
        String str7 = df7.format(today);
        System.out.println("String in yyyy-MM-dd format is: " + str7);          
    } catch (Exception ex) {
      ex.printStackTrace();
    }
}

Or a utility function

public String convertDateToString(Date date, String format) {
    String dateStr = null;
    DateFormat df = new SimpleDateFormat(format);

    try {
        dateStr = df.format(date);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return dateStr;
}

From Convert Date to String in Java

Including dependencies in a jar with Maven

There's the shade maven plugin. It can be used to package and rename dependencies (to omit dependency problems on the classpath).

pandas python how to count the number of records or rows in a dataframe

Simply, row_num = df.shape[0] # gives number of rows, here's the example:

import pandas as pd
import numpy as np

In [322]: df = pd.DataFrame(np.random.randn(5,2), columns=["col_1", "col_2"])

In [323]: df
Out[323]: 
      col_1     col_2
0 -0.894268  1.309041
1 -0.120667 -0.241292
2  0.076168 -1.071099
3  1.387217  0.622877
4 -0.488452  0.317882

In [324]: df.shape
Out[324]: (5, 2)

In [325]: df.shape[0]   ## Gives no. of rows/records
Out[325]: 5

In [326]: df.shape[1]   ## Gives no. of columns
Out[326]: 2

How to create an empty file with Ansible?

A combination of two answers, with a twist. The code will be detected as changed, when the file is created or the permission updated.

- name: Touch again the same file, but dont change times this makes the task idempotent
  file:
    path: /etc/foo.conf
    state: touch
    mode: 0644
    modification_time: preserve
    access_time: preserve
  changed_when: >
    p.diff.before.state == "absent" or
    p.diff.before.mode|default("0644") != "0644"

and a version that also corrects the owner and group and detects it as changed when it does correct these:

- name: Touch again the same file, but dont change times this makes the task idempotent
  file:
    path: /etc/foo.conf
    state: touch
    state: touch
    mode: 0644
    owner: root
    group: root
    modification_time: preserve
    access_time: preserve
  register: p
  changed_when: >
    p.diff.before.state == "absent" or
    p.diff.before.mode|default("0644") != "0644" or
    p.diff.before.owner|default(0) != 0 or
    p.diff.before.group|default(0) != 0

Limit String Length

$value = str_limit('This string is really really long.', 7);

// This st...

How to center a <p> element inside a <div> container?

This solution works fine for all major browsers, except IE. So keep that in mind.

In this example, basicaly I use positioning, horizontal and vertical transform for the UI element to center it.

_x000D_
_x000D_
        .container {_x000D_
            /* set the the position to relative */_x000D_
            position: relative;_x000D_
            width: 30rem;_x000D_
            height: 20rem;_x000D_
            background-color: #2196F3;_x000D_
        }_x000D_
_x000D_
_x000D_
        .paragh {_x000D_
            /* set the the position to absolute */_x000D_
            position: absolute;_x000D_
            /* set the the position of the helper container into the middle of its space */_x000D_
            top: 50%;_x000D_
            left: 50%;_x000D_
            font-size: 30px;_x000D_
            /* make sure padding and margin do not disturb the calculation of the center point */_x000D_
            padding: 0;_x000D_
            margin: 0;_x000D_
            /* using centers for the transform */_x000D_
            transform-origin: center center;_x000D_
            /* calling calc() function for the calculation to move left and up the element from the center point */_x000D_
            transform: translateX(calc((100% / 2) * (-1))) translateY(calc((100% / 2) * (-1)));_x000D_
        }
_x000D_
<div class="container">_x000D_
    <p class="paragh">Text</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

I hope this help.

Create a Maven project in Eclipse complains "Could not resolve archetype"

First things first, you have to install Maven on your workstation. You need also to install M2E, what you obviously did. Not all distributions of Juno have it pre-installed.

Then configure your Eclipse so it can find your Maven install. In the menu Window -> Preferences, then open the Maven section. In your right panel, you have a list of the Maven installations Eclipse knows. Add your installation and select it instead of the embedded Maven provided with M2E. Don't forget to set the "Global settings from installation directory" field with the path to the settings.xml of your Maven installation.

Which leads us to the settings.xml. If the above doesn't solve your problem, you will have to configure your Maven. More infos here.

Print all but the first three columns

Another way to avoid using the print statement:

 $ awk '{$1=$2=$3=""}sub("^"FS"*","")' file

In awk when a condition is true print is the default action.

What are the new features in C++17?

Language features:

Templates and Generic Code

Lambda

Attributes

Syntax cleanup

Cleaner multi-return and flow control

  • Structured bindings

    • Basically, first-class std::tie with auto
    • Example:
      • const auto [it, inserted] = map.insert( {"foo", bar} );
      • Creates variables it and inserted with deduced type from the pair that map::insert returns.
    • Works with tuple/pair-likes & std::arrays and relatively flat structs
    • Actually named structured bindings in standard
  • if (init; condition) and switch (init; condition)

    • if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
    • Extends the if(decl) to cases where decl isn't convertible-to-bool sensibly.
  • Generalizing range-based for loops

    • Appears to be mostly support for sentinels, or end iterators that are not the same type as begin iterators, which helps with null-terminated loops and the like.
  • if constexpr

    • Much requested feature to simplify almost-generic code.

Misc

Library additions:

Data types

Invoke stuff

File System TS v1

New algorithms

  • for_each_n

  • reduce

  • transform_reduce

  • exclusive_scan

  • inclusive_scan

  • transform_exclusive_scan

  • transform_inclusive_scan

  • Added for threading purposes, exposed even if you aren't using them threaded

Threading

(parts of) Library Fundamentals TS v1 not covered above or below

Container Improvements

Smart pointer changes

Other std datatype improvements:

Misc

Traits

Deprecated

Isocpp.org has has an independent list of changes since C++14; it has been partly pillaged.

Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.

Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.

Additional entries pillaged from SD-6 feature-test list.

clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.

these slides had some features missing elsewhere.

While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:

Removed:

There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:

Papers not yet integrated into above:

  • P0505R0 (constexpr chrono)

  • P0418R2 (atomic tweaks)

  • P0512R0 (template argument deduction tweaks)

  • P0490R0 (structured binding tweaks)

  • P0513R0 (changes to std::hash)

  • P0502R0 (parallel exceptions)

  • P0509R1 (updating restrictions on exception handling)

  • P0012R1 (make exception specifications be part of the type system)

  • P0510R0 (restrictions on variants)

  • P0504R0 (tags for optional/variant/any)

  • P0497R0 (shared ptr tweaks)

  • P0508R0 (structured bindings node handles)

  • P0521R0 (shared pointer use count and unique changes?)

Spec changes:

Further reference:

Difference in make_shared and normal shared_ptr in C++

About efficiency and concernig time spent on allocation, I made this simple test below, I created many instances through these two ways (one at a time):

for (int k = 0 ; k < 30000000; ++k)
{
    // took more time than using new
    std::shared_ptr<int> foo = std::make_shared<int> (10);

    // was faster than using make_shared
    std::shared_ptr<int> foo2 = std::shared_ptr<int>(new int(10));
}

The thing is, using make_shared took the double time compared with using new. So, using new there are two heap allocations instead of one using make_shared. Maybe this is a stupid test but doesn't it show that using make_shared takes more time than using new? Of course, I'm talking about time used only.

How to skip over an element in .map()?

To extrapolate on Felix Kling's comment, you can use .filter() like this:

var sources = images.map(function (img) {
  if(img.src.split('.').pop() === "json") { // if extension is .json
    return null; // skip
  } else {
    return img.src;
  }
}).filter(Boolean);

That will remove falsey values from the array that is returned by .map()

You could simplify it further like this:

var sources = images.map(function (img) {
  if(img.src.split('.').pop() !== "json") { // if extension is .json
    return img.src;
  }
}).filter(Boolean);

Or even as a one-liner using an arrow function, object destructuring and the && operator:

var sources = images.map(({ src }) => src.split('.').pop() !== "json" && src).filter(Boolean);

Using PowerShell to write a file in UTF-8 without the BOM

I figured this wouldn't be UTF, but I just found a pretty simple solution that seems to work...

Get-Content path/to/file.ext | out-file -encoding ASCII targetFile.ext

For me this results in a utf-8 without bom file regardless of the source format.

Using ng-if as a switch inside ng-repeat?

Try to surround strings (hoot, story, article) with quotes ':

<div ng-repeat = "data in comments">
    <div ng-if="data.type == 'hoot' ">
        //different template with hoot data
    </div>
    <div ng-if="data.type == 'story' ">
        //different template with story data
    </div>
    <div ng-if="data.type == 'article' ">
        //different template with article data
    </div> 
</div>

Run "mvn clean install" in Eclipse

If you want to open command prompt inside your eclipse, this can be a useful approach to link cmd with eclipse.

You can follow this link to get the steps in detail with screenshots. How to use cmd prompt inside Eclipse ?

I'm quoting the steps here:

Step 1: Setup a new External Configuration Tool

In the Eclipse tool go to Run -> External Tools -> External Tools Configurations option.

Step 2: Click New Launch Configuration option in Create, manage and run configuration screen

Step 3: New Configuration screen for configuring the command prompt

Step 4: Provide configuration details of the Command Prompt in the Main tab

Name: Give any name to your configuration (Here it is Command_Prompt)
Location: Location of the CMD.exe in your Windows
Working Directory: Any directory where you want to point the Command prompt

Step 5: Tick the check box Allocate console This will ensure the eclipse console is being used as the command prompt for any input or output.

Step 6: Click Run and you are there!! You will land up in the C: directory as a working directory

Best way to detect Mac OS X or Windows computers with JavaScript or jQuery

It's as simple as that:

function isMacintosh() {
  return navigator.platform.indexOf('Mac') > -1
}

function isWindows() {
  return navigator.platform.indexOf('Win') > -1
}

You can do funny things then like:

var isMac = isMacintosh();
var isPC = !isMacintosh();

How to get attribute of element from Selenium?

Python

element.get_attribute("attribute name")

Java

element.getAttribute("attribute name")

Ruby

element.attribute("attribute name")

C#

element.GetAttribute("attribute name");

update to python 3.7 using anaconda

conda create -n py37 -c anaconda anaconda=5.3

seems to be working.

How to determine tables size in Oracle

Here is a query, you can run it in SQL Developer (or SQL*Plus):

SELECT DS.TABLESPACE_NAME, SEGMENT_NAME, ROUND(SUM(DS.BYTES) / (1024 * 1024)) AS MB
  FROM DBA_SEGMENTS DS
  WHERE SEGMENT_NAME IN (SELECT TABLE_NAME FROM DBA_TABLES)
 GROUP BY DS.TABLESPACE_NAME,
       SEGMENT_NAME;

How to access nested elements of json object using getJSONArray method

This is for Nikola.

    public static JSONObject setProperty(JSONObject js1, String keys, String valueNew) throws JSONException {
    String[] keyMain = keys.split("\\.");
    for (String keym : keyMain) {
        Iterator iterator = js1.keys();
        String key = null;
        while (iterator.hasNext()) {
            key = (String) iterator.next();
            if ((js1.optJSONArray(key) == null) && (js1.optJSONObject(key) == null)) {
                if ((key.equals(keym)) && (js1.get(key).toString().equals(valueMain))) {
                    js1.put(key, valueNew);
                    return js1;
                }
            }
            if (js1.optJSONObject(key) != null) {
                if ((key.equals(keym))) {
                    js1 = js1.getJSONObject(key);
                    break;
                }
            }
            if (js1.optJSONArray(key) != null) {
                JSONArray jArray = js1.getJSONArray(key);
                JSONObject j;
                for (int i = 0; i < jArray.length(); i++) {
                    js1 = jArray.getJSONObject(i);
                    break;
                }
            }
        }
    }
    return js1;
}


public static void main(String[] args) throws IOException, JSONException {
    String text = "{ "key1":{ "key2":{ "key3":{ "key4":[ { "fieldValue":"Empty", "fieldName":"Enter Field Name 1" }, { "fieldValue":"Empty", "fieldName":"Enter Field Name 2" } ] } } } }";
    JSONObject json = new JSONObject(text);
    setProperty(json, "ke1.key2.key3.key4.fieldValue", "nikola");
    System.out.println(json.toString(4));

}

If it's help bro,Do not forget to up for my reputation)))

How to install a previous exact version of a NPM package?

In my opinion that is easiest and fastest way:

$ npm -v

4.2.0

$ npm install -g npm@latest-3

...

$ npm -v

3.10.10

PHP 5.4 Call-time pass-by-reference - Easy fix available?

You should be denoting the call by reference in the function definition, not the actual call. Since PHP started showing the deprecation errors in version 5.3, I would say it would be a good idea to rewrite the code.

From the documentation:

There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);.

For example, instead of using:

// Wrong way!
myFunc(&$arg);               # Deprecated pass-by-reference argument
function myFunc($arg) { }

Use:

// Right way!
myFunc($var);                # pass-by-value argument
function myFunc(&$arg) { }

How to efficiently check if variable is Array or Object (in NodeJS & V8)?

If its just about detecting whether or not you're dealing with an Object, I could think of

Object.getPrototypeOf( obj ) === Object.prototype

However, this would probably fail for non-object primitive values. Actually there is nothing wrong with invoking .toString() to retreive the [[cclass]] property. You can even create a nice syntax like

var type = Function.prototype.call.bind( Object.prototype.toString );

and then use it like

if( type( obj ) === '[object Object]' ) { }

It might not be the fastest operation but I don't think the performance leak there is too big.

Warning: Permanently added the RSA host key for IP address

While cloning you might be using SSH in the dropdown list. Change it to Https and then clone.

Reading a text file with SQL Server

if you want to read the file into a table at one time you should use BULK INSERT. ON the other hand if you preffer to parse the file line by line to make your own checks, you should take a look at this web: https://www.simple-talk.com/sql/t-sql-programming/reading-and-writing-files-in-sql-server-using-t-sql/ It is possible that you need to activate your xp_cmdshell or other OLE Automation features. Simple Google it and the script will appear. Hope to be useful.

Avoid duplicates in INSERT INTO SELECT query in SQL Server

A simple DELETE before the INSERT would suffice:

DELETE FROM Table2 WHERE Id = (SELECT Id FROM Table1)
INSERT INTO Table2 (Id, name) SELECT Id, name FROM Table1

Switching Table1 for Table2 depending on which table's Id and name pairing you want to preserve.

Maintain model of scope when changing between views in AngularJS

You can use $locationChangeStart event to store the previous value in $rootScope or in a service. When you come back, just initialize all previously stored values. Here is a quick demo using $rootScope.

enter image description here

_x000D_
_x000D_
var app = angular.module("myApp", ["ngRoute"]);_x000D_
app.controller("tab1Ctrl", function($scope, $rootScope) {_x000D_
    if ($rootScope.savedScopes) {_x000D_
        for (key in $rootScope.savedScopes) {_x000D_
            $scope[key] = $rootScope.savedScopes[key];_x000D_
        }_x000D_
    }_x000D_
    $scope.$on('$locationChangeStart', function(event, next, current) {_x000D_
        $rootScope.savedScopes = {_x000D_
            name: $scope.name,_x000D_
            age: $scope.age_x000D_
        };_x000D_
    });_x000D_
});_x000D_
app.controller("tab2Ctrl", function($scope) {_x000D_
    $scope.language = "English";_x000D_
});_x000D_
app.config(function($routeProvider) {_x000D_
    $routeProvider_x000D_
        .when("/", {_x000D_
            template: "<h2>Tab1 content</h2>Name: <input ng-model='name'/><br/><br/>Age: <input type='number' ng-model='age' /><h4 style='color: red'>Fill the details and click on Tab2</h4>",_x000D_
            controller: "tab1Ctrl"_x000D_
        })_x000D_
        .when("/tab2", {_x000D_
            template: "<h2>Tab2 content</h2> My language: {{language}}<h4 style='color: red'>Now go back to Tab1</h4>",_x000D_
            controller: "tab2Ctrl"_x000D_
        });_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>_x000D_
<body ng-app="myApp">_x000D_
    <a href="#/!">Tab1</a>_x000D_
    <a href="#!tab2">Tab2</a>_x000D_
    <div ng-view></div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

CSS Animation onClick

_x000D_
_x000D_
var  abox = document.getElementsByClassName("box")[0];_x000D_
function allmove(){_x000D_
        abox.classList.remove("move-ltr");_x000D_
        abox.classList.remove("move-ttb");_x000D_
       abox.classList.toggle("move");_x000D_
}_x000D_
function ltr(){_x000D_
        abox.classList.remove("move");_x000D_
        abox.classList.remove("move-ttb");_x000D_
       abox.classList.toggle("move-ltr");_x000D_
}_x000D_
function ttb(){_x000D_
       abox.classList.remove("move-ltr");_x000D_
       abox.classList.remove("move");_x000D_
       abox.classList.toggle("move-ttb");_x000D_
}
_x000D_
.box {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: red;_x000D_
  position: relative;_x000D_
}_x000D_
.move{_x000D_
  -webkit-animation: moveall 5s;_x000D_
  animation: moveall 5s;_x000D_
}_x000D_
.move-ltr{_x000D_
   -webkit-animation: moveltr 5s;_x000D_
  animation: moveltr 5s;_x000D_
}_x000D_
.move-ttb{_x000D_
    -webkit-animation: movettb 5s;_x000D_
  animation: movettb 5s;_x000D_
}_x000D_
@keyframes moveall {_x000D_
  0%   {left: 0px; top: 0px;}_x000D_
  25%  {left: 200px; top: 0px;}_x000D_
  50%  {left: 200px; top: 200px;}_x000D_
  75%  {left: 0px; top: 200px;}_x000D_
  100% {left: 0px; top: 0px;}_x000D_
}_x000D_
@keyframes moveltr {_x000D_
  0%   { left: 0px; top: 0px;}_x000D_
  50%  {left: 200px; top: 0px;}_x000D_
  100% {left: 0px; top: 0px;}_x000D_
}_x000D_
@keyframes movettb {_x000D_
  0%   {left: 0px; top: 0px;}_x000D_
  50%  {top: 200px;left: 0px;}_x000D_
  100% {left: 0px; top: 0px;}_x000D_
}
_x000D_
<div class="box"></div>_x000D_
<button onclick="allmove()">click</button>_x000D_
<button onclick="ltr()">click</button>_x000D_
<button onclick="ttb()">click</button>
_x000D_
_x000D_
_x000D_

Pass array to mvc Action via AJAX

The answer to use the 'traditional' option is correct. I'm just providing some more background info for this who wish to learn more.

From the jQuery documentation:

As of jQuery 1.8, the $.param() method no longer uses jQuery.ajaxSettings.traditional as its default setting and will default to false.

You can also read more here: http://michaelsync.net/2012/04/05/tips-asp-net-mvc-javascriptserializer-3-questions-and-3-answers and http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

HTH

python numpy machine epsilon

It will already work, as David pointed out!

>>> def machineEpsilon(func=float):
...     machine_epsilon = func(1)
...     while func(1)+func(machine_epsilon) != func(1):
...         machine_epsilon_last = machine_epsilon
...         machine_epsilon = func(machine_epsilon) / func(2)
...     return machine_epsilon_last
... 
>>> machineEpsilon(float)
2.220446049250313e-16
>>> import numpy
>>> machineEpsilon(numpy.float64)
2.2204460492503131e-16
>>> machineEpsilon(numpy.float32)
1.1920929e-07

Python append() vs. + operator on lists, why do these give different results?

To explain "why":

The + operation adds the array elements to the original array. The array.append operation inserts the array (or any object) into the end of the original array, which results in a reference to self in that spot (hence the infinite recursion).

The difference here is that the + operation acts specific when you add an array (it's overloaded like others, see this chapter on sequences) by concatenating the element. The append-method however does literally what you ask: append the object on the right-hand side that you give it (the array or any other object), instead of taking its elements.

An alternative

Use extend() if you want to use a function that acts similar to the + operator (as others have shown here as well). It's not wise to do the opposite: to try to mimic append with the + operator for lists (see my earlier link on why).

Little history

For fun, a little history: the birth of the array module in Python in February 1993. it might surprise you, but arrays were added way after sequences and lists came into existence.

How do you move a file?

With TortoiseSVN I just move the file on disk.

When I come to commit my changes I select the missing file and the new one and select "Repair move" from the right click menu:

enter image description here

This means I can let my IDE move round files and use it refactoring tools without losing history.

python pip - install from local dir

All you need to do is run

pip install /opt/mypackage

and pip will search /opt/mypackage for a setup.py, build a wheel, then install it.

The problem with using the -e flag for pip install as suggested in the comments and this answer is that this requires that the original source directory stay in place for as long as you want to use the module. It's great if you're a developer working on the source, but if you're just trying to install a package, it's the wrong choice.

Alternatively, you don't even need to download the repo from Github at all. pip supports installing directly from git repos using a variety of protocols including HTTP, HTTPS, and SSH, among others. See the docs I linked to for examples.

Looping through a DataTable

Please try the following code below:

//Here I am using a reader object to fetch data from database, along with sqlcommand onject (cmd).
//Once the data is loaded to the Datatable object (datatable) you can loop through it using the datatable.rows.count prop.

using (reader = cmd.ExecuteReader())
{
// Load the Data table object
  dataTable.Load(reader);
  if (dataTable.Rows.Count > 0)
  {
    DataColumn col = dataTable.Columns["YourColumnName"];  
    foreach (DataRow row in dataTable.Rows)
    {                                   
       strJsonData = row[col].ToString();
    }
  }
}

How do I get an OAuth 2.0 authentication token in C#

Clearly:

Server side generating a token example

private string GenerateToken(string userName)
{
    var someClaims = new Claim[]{
        new Claim(JwtRegisteredClaimNames.UniqueName, userName),
        new Claim(JwtRegisteredClaimNames.Email, GetEmail(userName)),
        new Claim(JwtRegisteredClaimNames.NameId,Guid.NewGuid().ToString())
    };

    SecurityKey securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_settings.Tokenizer.Key));
    var token = new JwtSecurityToken(
        issuer: _settings.Tokenizer.Issuer,
        audience: _settings.Tokenizer.Audience,
        claims: someClaims,
        expires: DateTime.Now.AddHours(_settings.Tokenizer.ExpiryHours),
        signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
    );

    return new JwtSecurityTokenHandler().WriteToken(token);
}

(note: Tokenizer is my helper class that contains Issuer Audience etc..)

Definitely:

Client side getting a token for authentication

    public async Task<string> GetToken()
    {
        string token = "";
        var siteSettings = DependencyResolver.Current.GetService<SiteSettings>();

        var client = new HttpClient();
        client.BaseAddress = new Uri(siteSettings.PopularSearchRequest.StaticApiUrl);
        client.DefaultRequestHeaders.Accept.Clear();
        //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        StatisticUserModel user = new StatisticUserModel()
        {
            Password = siteSettings.PopularSearchRequest.Password,
            Username = siteSettings.PopularSearchRequest.Username
        };

        string jsonUser = JsonConvert.SerializeObject(user, Formatting.Indented);
        var stringContent = new StringContent(jsonUser, Encoding.UTF8, "application/json");
        var response = await client.PostAsync(siteSettings.PopularSearchRequest.StaticApiUrl + "/api/token/new", stringContent);
        token = await response.Content.ReadAsStringAsync();

        return token;
    }

You can use this token for the authorization (that is in the subsequent requests)

how to fix groovy.lang.MissingMethodException: No signature of method:

To help other bug-hunters. I had this error because the function didn't exist.

I had a spelling error.

LEFT OUTER JOIN in LINQ

Simple solution for the LEFT OUTER JOIN:

var setA = context.SetA;
var setB = context.SetB.Select(st=>st.Id).Distinct().ToList();
var leftOuter  = setA.Where(stA=> !setB.Contains(stA.Id)); 

notes:

  • To improve performance SetB could be converted to a Dictionary (if that is done then you have to change this: !setB.Contains(stA.Id)) or a HashSet
  • When there is more than one field involved this could be achieve using Set operations and a class that implement: IEqualityComparer

CSS: borders between table columns only

You need to set a border-right on the td's then target the last tds in a row to set the border to none. Ways to target:

  1. Set a class on the last td of each row and use that
  2. If it is a set number of cells and only targeting newer browers then 3 cells wide can use td + td + td
  3. Or better (with new browsers) td:last-child

how to return index of a sorted list?

Straight out of the documentation for collections.OrderedDict:

>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

Adapted to the example in the original post:

>>> l=[2,3,1,4,5]
>>> OrderedDict(sorted(enumerate(l), key=lambda x: x[1])).keys()
[2, 0, 1, 3, 4]

See http://docs.python.org/library/collections.html#collections.OrderedDict for details.

Taking inputs with BufferedReader in Java

BufferedReader#read reads single character[0 to 65535 (0x00-0xffff)] from the stream, so it is not possible to read single integer from stream.

            String s= inp.readLine();
            int[] m= new int[2];
            String[] s1 = inp.readLine().split(" ");
            m[0]=Integer.parseInt(s1[0]);
            m[1]=Integer.parseInt(s1[1]);

            // Checking whether I am taking the inputs correctly
            System.out.println(s);
            System.out.println(m[0]);
            System.out.println(m[1]);

You can check also Scanner vs. BufferedReader.

Merge PDF files with PHP

$cmd = "gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=".$new." ".implode(" ", $files);
shell_exec($cmd);

A simplified version of Chauhan's answer

How to remove all white space from the beginning or end of a string?

take a look at Trim() which returns a new string with whitespace removed from the beginning and end of the string it is called on.

Sort list in C# with LINQ

Like this?

In LINQ:

var sortedList = originalList.OrderBy(foo => !foo.AVC)
                             .ToList();

Or in-place:

originalList.Sort((foo1, foo2) => foo2.AVC.CompareTo(foo1.AVC));

As Jon Skeet says, the trick here is knowing that false is considered to be 'smaller' than true.

If you find that you are doing these ordering operations in lots of different places in your code, you might want to get your type Foo to implement the IComparable<Foo> and IComparable interfaces.

FORCE INDEX in MySQL - where do I put it?

The syntax for index hints is documented here:
http://dev.mysql.com/doc/refman/5.6/en/index-hints.html

FORCE INDEX goes right after the table reference:

SELECT * FROM (
    SELECT owner_id,
           product_id,
           start_time,
           price,
           currency,
           name,
           closed,
           active,
           approved,
           deleted,
           creation_in_progress
    FROM db_products FORCE INDEX (products_start_time)
    ORDER BY start_time DESC
) as resultstable
WHERE resultstable.closed = 0
      AND resultstable.active = 1
      AND resultstable.approved = 1
      AND resultstable.deleted = 0
      AND resultstable.creation_in_progress = 0
GROUP BY resultstable.owner_id
ORDER BY start_time DESC

WARNING:

If you're using ORDER BY before GROUP BY to get the latest entry per owner_id, you're using a nonstandard and undocumented behavior of MySQL to do that.

There's no guarantee that it'll continue to work in future versions of MySQL, and the query is likely to be an error in any other RDBMS.

Search the tag for many explanations of better solutions for this type of query.

returning a Void object

There is no generic type which will tell the compiler that a method returns nothing.

I believe the convention is to use Object when inheriting as a type parameter

OR

Propagate the type parameter up and then let users of your class instantiate using Object and assigning the object to a variable typed using a type-wildcard ?:

interface B<E>{ E method(); }

class A<T> implements B<T>{

    public T method(){
        // do something
        return null;
    }
}

A<?> a = new A<Object>();

How to detect the currently pressed key?

Since .NET Framework version 3.0, it is possible to use the Keyboard.IsKeyDown method from the new System.Windows.Input namespace. For instance:

if (((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && Keyboard.IsKeyDown(Key.F))
{
    // CTRL + F is currently pressed
}

Even though it's part of WPF, that method works fine for WinForm applications (provided that you add references to PresentationCore.dll and WindowsBase.dll). Unfortunately, however, the 3.0 and 3.5 versions of the Keyboard.IsKeyDown method did not work for WinForm applications. Therefore, if you do want to use it in a WinForm application, you'll need to be targeting .NET Framework 4.0 or later in order for it to work.

curl: (6) Could not resolve host: application

It's treating the string application as your URL.
This means your shell isn't parsing the command correctly.
My guess is that you copied the string from somewhere, and that when you pasted it, you got some characters that looked like regular quotes, but weren't.
Try retyping the command; you'll only get valid characters from your keyboard. I bet you'll get a much different result from what looks like the same query. As this is probably a shell problem and not a 'curl' problem (you didn't build cURL yourself from source, did you?), it might be good to mention whether you're on Linux/Windows/etc.

html "data-" attribute as javascript parameter

you might use default parameters in your function and then just pass the entire dataset itself, since the dataset is already a DOMStringMap Object

<div data-uid="aaa" data-name="bbb" data-value="ccc"
onclick="fun(this.dataset)">

<script>
const fun = ({uid:'ddd', name:'eee', value:'fff', other:'default'} = {}) { 
    // 
}
</script>

that way, you can deal with any data-values that got set in the html tag, or use defaults if they weren't set - that kind of thing

maybe not in this situation, but in others, it might be advantageous to put all your preferences in a single data-attribute

<div data-all='{"uid":"aaa","name":"bbb","value":"ccc"}'
onclick="fun(JSON.parse(this.dataset.all))">

there are probably more terse ways of doing that, if you already know certain things about the order of the data

<div data-all="aaa,bbb,ccc" onclick="fun(this.dataset.all.split(','))">

PowerShell array initialization

If I don't know the size up front, I use an arraylist instead of an array.

$al = New-Object System.Collections.ArrayList
for($i=0; $i -lt 5; $i++)
{
    $al.Add($i)
}

Clear text input on click with AngularJS

If you want to clean up the whole form, you can use such approach. This is your model into controller:

    $scope.registrationForm = {
    'firstName'     : '',
    'lastName'      : ''
};

Your HTML:

<form class="form-horizontal" name="registrForm" role="form">
   <input type="text" class="form-control"
                       name="firstName"
                       id="firstName"
                       ng-model="registrationForm.firstName"
                       placeholder="First name"
                       required> First name
   <input type="text" class="form-control"
                       name="lastName"
                       id="lastName"
                       ng-model="registrationForm.lastName"
                       placeholder="Last name"
                       required> Last name
</form>

Then, you should clone/save your clear state by:

$scope.originForm = angular.copy($scope.registrationForm);

Your reset function will be:

$scope.resetForm = function(){
    $scope.registrationForm = angular.copy($scope.originForm); // Assign clear state to modified form 
    $scope.registrForm.$setPristine(); // this line will update status of your form, but will not clean your data, where `registrForm` - name of form.
};

In such way you are able to clean up the whole your form

How to check if a column exists in Pandas

Just to suggest another way without using if statements, you can use the get() method for DataFrames. For performing the sum based on the question:

df['sum'] = df.get('A', df['B']) + df['C']

The DataFrame get method has similar behavior as python dictionaries.

phpMyAdmin - The MySQL Extension is Missing

Some linux distributions have a php_mysql and php_mysqli package to install.

Remove from the beginning of std::vector

Given

std::vector<Rule>& topPriorityRules;

The correct way to remove the first element of the referenced vector is

topPriorityRules.erase(topPriorityRules.begin());

which is exactly what you suggested.

Looks like i need to do iterator overloading.

There is no need to overload an iterator in order to erase first element of std::vector.


P.S. Vector (dynamic array) is probably a wrong choice of data structure if you intend to erase from the front.

How to get last items of a list in Python?

Slicing

Python slicing is an incredibly fast operation, and it's a handy way to quickly access parts of your data.

Slice notation to get the last nine elements from a list (or any other sequence that supports it, like a string) would look like this:

num_list[-9:]

When I see this, I read the part in the brackets as "9th from the end, to the end." (Actually, I abbreviate it mentally as "-9, on")

Explanation:

The full notation is

sequence[start:stop:step]

But the colon is what tells Python you're giving it a slice and not a regular index. That's why the idiomatic way of copying lists in Python 2 is

list_copy = sequence[:]

And clearing them is with:

del my_list[:]

(Lists get list.copy and list.clear in Python 3.)

Give your slices a descriptive name!

You may find it useful to separate forming the slice from passing it to the list.__getitem__ method (that's what the square brackets do). Even if you're not new to it, it keeps your code more readable so that others that may have to read your code can more readily understand what you're doing.

However, you can't just assign some integers separated by colons to a variable. You need to use the slice object:

last_nine_slice = slice(-9, None)

The second argument, None, is required, so that the first argument is interpreted as the start argument otherwise it would be the stop argument.

You can then pass the slice object to your sequence:

>>> list(range(100))[last_nine_slice]
[91, 92, 93, 94, 95, 96, 97, 98, 99]

islice

islice from the itertools module is another possibly performant way to get this. islice doesn't take negative arguments, so ideally your iterable has a __reversed__ special method - which list does have - so you must first pass your list (or iterable with __reversed__) to reversed.

>>> from itertools import islice
>>> islice(reversed(range(100)), 0, 9)
<itertools.islice object at 0xffeb87fc>

islice allows for lazy evaluation of the data pipeline, so to materialize the data, pass it to a constructor (like list):

>>> list(islice(reversed(range(100)), 0, 9))
[99, 98, 97, 96, 95, 94, 93, 92, 91]

How to find event listeners on a DOM node when debugging or from the JavaScript code?

I am trying to do that in jQuery 2.1, and with the "$().click() -> $(element).data("events").click;" method it doesn't work.

I realized that only the $._data() functions works in my case :

_x000D_
_x000D_
 $(document).ready(function(){_x000D_
_x000D_
  var node = $('body');_x000D_
  _x000D_
        // Bind 3 events to body click_x000D_
  node.click(function(e) { alert('hello');  })_x000D_
   .click(function(e) { alert('bye');  })_x000D_
   .click(fun_1);_x000D_
_x000D_
        // Inspect the events of body_x000D_
  var events = $._data(node[0], "events").click;_x000D_
  var ev1 = events[0].handler // -> function(e) { alert('hello')_x000D_
  var ev2 = events[1].handler // -> function(e) { alert('bye')_x000D_
  var ev3 = events[2].handler // -> function fun_1()_x000D_
        _x000D_
  $('body')_x000D_
   .append('<p> Event1 = ' + eval(ev1).toString() + '</p>')_x000D_
   .append('<p> Event2 = ' + eval(ev2).toString() + '</p>')_x000D_
   .append('<p> Event3 = ' + eval(ev3).toString() + '</p>');        _x000D_
 _x000D_
 });_x000D_
_x000D_
 function fun_1() {_x000D_
  var txt = 'text del missatge';  _x000D_
  alert(txt);_x000D_
 }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to set array length in c# dynamically

You can create an array dynamically in this way:

 static void Main()
    {
        // Create a string array 2 elements in length:
        int arrayLength = 2;
        Array dynamicArray = Array.CreateInstance(typeof(int), arrayLength);
        dynamicArray.SetValue(234, 0);                              //  ? a[0] = 234;
        dynamicArray.SetValue(444, 1);                              //  ? a[1] = 444;
        int number = (int)dynamicArray.GetValue(0);                      //  ? number = a[0];


        int[] cSharpArray = (int[])dynamicArray;
        int s2 = cSharpArray[0];

    }

Get Public URL for File - Google Cloud Storage - App Engine (Python)

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

You may face this issue if you are running your app on Android's Marshmallow or later version (API level 23 or greater), because of the new Real-time Permissions model introduced in this.

Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. This approach streamlines the app install process, since the user does not need to grant permissions when they install or update the app.

For getting permissions at runtime, you will have to request the user. You can do that in following way.

First request for permissions.

String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        requestPermissions(permissions, WRITE_REQUEST_CODE);

And then you can check the results in

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
       case WRITE_REQUEST_CODE:
         if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
           //Permission granted.
           //Continue with writing files...
         }
       else{
           //Permission denied.
         }
        break;
    }
}

Here is good learning source requesting-runtime-permissions-in-android-marshmallow/

Extend contigency table with proportions (percentages)

Here is another example using the lapply and table functions in base R.

freqList = lapply(select_if(tips, is.factor), 
              function(x) {
                  df = data.frame(table(x))

                  df = data.frame(fct = df[, 1], 
                                  n = sapply(df[, 2], function(y) {
                                      round(y / nrow(dat), 2)
                                    }
                                )
                            )
                  return(df) 
                    }
                )

Use print(freqList) to see the proportion tables (percent of frequencies) for each column/feature/variable (depending on your tradecraft) that is labeled as a factor.

jquery: get elements by class name and add css to each of them

You can try this

 $('div.easy_editor').css({'border-width':'9px', 'border-style':'solid', 'border-color':'red'});

The $('div.easy_editor') refers to a collection of all divs that have the class easy editor already. There is no need to use each() unless there was some function that you wanted to run on each. The css() method actually applies to all the divs you find.

Fitting iframe inside a div

Based on the link provided by @better_use_mkstemp, here's a fiddle where nested iframe resizes to fill parent div: http://jsfiddle.net/orlenko/HNyJS/

Html:

<div id="content">
    <iframe src="http://www.microsoft.com" name="frame2" id="frame2" frameborder="0" marginwidth="0" marginheight="0" scrolling="auto" onload="" allowtransparency="false"></iframe>
</div>
<div id="block"></div>
<div id="header"></div>
<div id="footer"></div>

Relevant parts of CSS:

div#content {
    position: fixed;
    top: 80px;
    left: 40px;
    bottom: 25px;
    min-width: 200px;
    width: 40%;
    background: black;
}

div#content iframe {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    height: 100%;
    width: 100%;
}

How do I make a Git commit in the past?

You can always change a date on your computer, make a commit, then change the date back and push.

How to convert Double to int directly?

double myDb = 12.3;
int myInt = (int) myDb;

Result is: myInt = 12

javaw.exe cannot find path

Just update your eclipse.ini file (you can find it in the root-directory of eclipse) by this:

-vm
path/javaw.exe

for example:

-vm 
C:/Program Files/Java/jdk1.7.0_09/jre/bin/javaw.exe

Angular.js and HTML5 date input value -- how to get Firefox to show a readable date value in a date input?

If using Angular Material Design, you can use the datepicker component there and this will work in Firefox, IE etc.

https://material.angularjs.org/latest/demo/datepicker

Fair warning though - personal experience is that there are problems with this, and seemingly it is being re-worked at present. See here:

https://github.com/angular/material/issues/4856

How to get a URL parameter in Express?

If you want to grab the query parameter value in the URL, follow below code pieces

//url.localhost:8888/p?tagid=1234
req.query.tagid
OR
req.param.tagid

If you want to grab the URL parameter using Express param function

Express param function to grab a specific parameter. This is considered middleware and will run before the route is called.

This can be used for validations or grabbing important information about item.

An example for this would be:

// parameter middleware that will run before the next routes
app.param('tagid', function(req, res, next, tagid) {

// check if the tagid exists
// do some validations
// add something to the tagid
var modified = tagid+ '123';

// save name to the request
req.tagid= modified;

next();
});

// http://localhost:8080/api/tags/98
app.get('/api/tags/:tagid', function(req, res) {
// the tagid was found and is available in req.tagid
res.send('New tag id ' + req.tagid+ '!');
});

Can you autoplay HTML5 videos on the iPad?

iOS 10 update

The ban on autoplay has been lifted as of iOS 10 - but with some restrictions (e.g. A can be autoplayed if there is no audio track).

To see a full list of these restrictions, see the official docs: https://webkit.org/blog/6784/new-video-policies-for-ios/

iOS 9 and before

As of iOS 6.1, it is no longer possible to auto-play videos on the iPad.

My assumption as to why they've disabled the auto-play feature?

Well, as many device owners have data usage/bandwidth limits on their devices, I think Apple felt that the user themselves should decide when they initiate bandwidth usage.


After a bit of research I found the following extract in the Apple documentation in regard to auto-play on iOS devices to confirm my assumption:

"Apple has made the decision to disable the automatic playing of video on iOS devices, through both script and attribute implementations.

In Safari, on iOS (for all devices, including iPad), where the user may be on a cellular network and be charged per data unit, preload and auto-play are disabled. No data is loaded until the user initiates it." - Apple documentation.

Here is a separate warning featured on the Safari HTML5 Reference page about why embedded media cannot be played in Safari on iOS:

Warning: To prevent unsolicited downloads over cellular networks at the user’s expense, embedded media cannot be played automatically in Safari on iOS—the user always initiates playback. A controller is automatically supplied on iPhone or iPod touch once playback in initiated, but for iPad you must either set the controls attribute or provide a controller using JavaScript.


What this means (in terms of code) is that Javascript's play() and load() methods are inactive until the user initiates playback, unless the play() or load() method is triggered by user action (e.g. a click event).

Basically, a user-initiated play button works, but an onLoad="play()" event does not.

For example, this would play the movie:

<input type="button" value="Play" onclick="document.myMovie.play()">

Whereas the following would do nothing on iOS:

<body onload="document.myMovie.play()">

What is the maximum characters for the NVARCHAR(MAX)?

From MSDN Documentation

nvarchar [ ( n | max ) ]

Variable-length Unicode string data. n defines the string length and can be a value from 1 through 4,000. max indicates that the maximum storage size is 2^31-1 bytes (2 GB). The storage size, in bytes, is two times the actual length of data entered + 2 bytes

Create a file if one doesn't exist - C

If fptr is NULL, then you don't have an open file. Therefore, you can't freopen it, you should just fopen it.

FILE *fptr;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
    fptr = fopen("scores.dat", "wb");
}

note: Since the behavior of your program varies depending on whether the file is opened in read or write modes, you most probably also need to keep a variable indicating which is the case.

A complete example

int main()
{
    FILE *fptr;
    char there_was_error = 0;
    char opened_in_read  = 1;
    fptr = fopen("scores.dat", "rb+");
    if(fptr == NULL) //if file does not exist, create it
    {
        opened_in_read = 0;
        fptr = fopen("scores.dat", "wb");
        if (fptr == NULL)
            there_was_error = 1;
    }
    if (there_was_error)
    {
        printf("Disc full or no permission\n");
        return EXIT_FAILURE;
    }
    if (opened_in_read)
        printf("The file is opened in read mode."
               " Let's read some cached data\n");
    else
        printf("The file is opened in write mode."
               " Let's do some processing and cache the results\n");
    return EXIT_SUCCESS;
}

Format an Excel column (or cell) as Text in C#?

Below is some code to format columns A and C as text in SpreadsheetGear for .NET which has an API which is similar to Excel - except for the fact that SpreadsheetGear is frequently more strongly typed. It should not be too hard to figure out how to convert this to work with Excel / COM:

IWorkbook workbook = Factory.GetWorkbook();
IRange cells = workbook.Worksheets[0].Cells;
// Format column A as text.
cells["A:A"].NumberFormat = "@";
// Set A2 to text with a leading '0'.
cells["A2"].Value = "01234567890123456789";
// Format column C as text (SpreadsheetGear uses 0 based indexes - Excel uses 1 based indexes).
cells[0, 2].EntireColumn.NumberFormat = "@";
// Set C3 to text with a leading '0'.
cells[2, 2].Value = "01234567890123456789";
workbook.SaveAs(@"c:\tmp\TextFormat.xlsx", FileFormat.OpenXMLWorkbook);

Disclaimer: I own SpreadsheetGear LLC

DataGridView - how to set column width?

I know this is an old question but no one ever answered the first part, to set width in percent. That can easily be done with FillWeight (MSDN). In case anyone else searching comes across this answer.

You can set DataGridAutoSizeColumnMode to Fill in the designer. By default that gives each column FillWeight of 100. Then in code behind, on FormLoad event or after binding data to grid, you can simply:

gridName.Columns[0].FillWeight = 200;
gridName.Columns[1].FillWeight = 50;

And so on, for whatever proportional weight you want. If you want to do every single column with numbers that add up to 100, for a literal percent width, you can do that too.

It gives a nice full DataGrid where the headers use the whole space, even if the user resizes the window. Looks good on widescreen, 4:3, whatever.

@HostBinding and @HostListener: what do they do and what are they for?

Have you checked these official docs?

HostListener - Declares a host listener. Angular will invoke the decorated method when the host element emits the specified event.

@HostListener - will listen to the event emitted by the host element that's declared with @HostListener.

HostBinding - Declares a host property binding. Angular automatically checks host property bindings during change detection. If a binding changes, it will update the host element of the directive.

@HostBinding - will bind the property to the host element, If a binding changes, HostBinding will update the host element.


NOTE: Both links have been removed recently. The "HostBinding-HostListening" portion of the style guide may be a useful alternative until the links return.


Here's a simple code example to help picture what this means:

DEMO : Here's the demo live in plunker - "A simple example about @HostListener & @HostBinding"

  • This example binds a role property -- declared with @HostBinding -- to the host's element
    • Recall that role is an attribute, since we're using attr.role.
    • <p myDir> becomes <p mydir="" role="admin"> when you view it in developer tools.
  • It then listens to the onClick event declared with @HostListener, attached to the component's host element, changing role with each click.
    • The change when the <p myDir> is clicked is that its opening tag changes from <p mydir="" role="admin"> to <p mydir="" role="guest"> and back.

directives.ts

import {Component,HostListener,Directive,HostBinding,Input} from '@angular/core';

@Directive({selector: '[myDir]'})
export class HostDirective {
  @HostBinding('attr.role') role = 'admin'; 
  @HostListener('click') onClick() {
    this.role= this.role === 'admin' ? 'guest' : 'admin';
  }
}

AppComponent.ts

import { Component,ElementRef,ViewChild } from '@angular/core';
import {HostDirective} from './directives';

@Component({
selector: 'my-app',
template:
  `
  <p myDir>Host Element 
    <br><br>

    We have a (HostListener) listening to this host's <b>click event</b> declared with @HostListener

    <br><br>

    And we have a (HostBinding) binding <b>the role property</b> to host element declared with @HostBinding 
    and checking host's property binding updates.

    If any property change is found I will update it.
  </p>

  <div>View this change in the DOM of the host element by opening developer tools,
    clicking the host element in the UI. 

    The role attribute's changes will be visible in the DOM.</div> 
    `,
  directives: [HostDirective]
})
export class AppComponent {}

Sending and receiving data over a network using TcpClient

Be warned - this is a very old and cumbersome "solution".

By the way, you can use serialization technology to send strings, numbers or any objects which are support serialization (most of .NET data-storing classes & structs are [Serializable]). There, you should at first send Int32-length in four bytes to the stream and then send binary-serialized (System.Runtime.Serialization.Formatters.Binary.BinaryFormatter) data into it.

On the other side or the connection (on both sides actually) you definetly should have a byte[] buffer which u will append and trim-left at runtime when data is coming.

Something like that I am using:

namespace System.Net.Sockets
{
    public class TcpConnection : IDisposable
    {
        public event EvHandler<TcpConnection, DataArrivedEventArgs> DataArrive = delegate { };
        public event EvHandler<TcpConnection> Drop = delegate { };

        private const int IntSize = 4;
        private const int BufferSize = 8 * 1024;

        private static readonly SynchronizationContext _syncContext = SynchronizationContext.Current;
        private readonly TcpClient _tcpClient;
        private readonly object _droppedRoot = new object();
        private bool _dropped;
        private byte[] _incomingData = new byte[0];
        private Nullable<int> _objectDataLength;

        public TcpClient TcpClient { get { return _tcpClient; } }
        public bool Dropped { get { return _dropped; } }

        private void DropConnection()
        {
            lock (_droppedRoot)
            {
                if (Dropped)
                    return;

                _dropped = true;
            }

            _tcpClient.Close();
            _syncContext.Post(delegate { Drop(this); }, null);
        }

        public void SendData(PCmds pCmd) { SendDataInternal(new object[] { pCmd }); }
        public void SendData(PCmds pCmd, object[] datas)
        {
            datas.ThrowIfNull();
            SendDataInternal(new object[] { pCmd }.Append(datas));
        }
        private void SendDataInternal(object data)
        {
            if (Dropped)
                return;

            byte[] bytedata;

            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter bf = new BinaryFormatter();

                try { bf.Serialize(ms, data); }
                catch { return; }

                bytedata = ms.ToArray();
            }

            try
            {
                lock (_tcpClient)
                {
                    TcpClient.Client.BeginSend(BitConverter.GetBytes(bytedata.Length), 0, IntSize, SocketFlags.None, EndSend, null);
                    TcpClient.Client.BeginSend(bytedata, 0, bytedata.Length, SocketFlags.None, EndSend, null);
                }
            }
            catch { DropConnection(); }
        }
        private void EndSend(IAsyncResult ar)
        {
            try { TcpClient.Client.EndSend(ar); }
            catch { }
        }

        public TcpConnection(TcpClient tcpClient)
        {
            _tcpClient = tcpClient;
            StartReceive();
        }

        private void StartReceive()
        {
            byte[] buffer = new byte[BufferSize];

            try
            {
                _tcpClient.Client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, DataReceived, buffer);
            }
            catch { DropConnection(); }
        }

        private void DataReceived(IAsyncResult ar)
        {
            if (Dropped)
                return;

            int dataRead;

            try { dataRead = TcpClient.Client.EndReceive(ar); }
            catch
            {
                DropConnection();
                return;
            }

            if (dataRead == 0)
            {
                DropConnection();
                return;
            }

            byte[] byteData = ar.AsyncState as byte[];
            _incomingData = _incomingData.Append(byteData.Take(dataRead).ToArray());
            bool exitWhile = false;

            while (exitWhile)
            {
                exitWhile = true;

                if (_objectDataLength.HasValue)
                {
                    if (_incomingData.Length >= _objectDataLength.Value)
                    {
                        object data;
                        BinaryFormatter bf = new BinaryFormatter();

                        using (MemoryStream ms = new MemoryStream(_incomingData, 0, _objectDataLength.Value))
                            try { data = bf.Deserialize(ms); }
                            catch
                            {
                                SendData(PCmds.Disconnect);
                                DropConnection();
                                return;
                            }

                        _syncContext.Post(delegate(object T)
                        {
                            try { DataArrive(this, new DataArrivedEventArgs(T)); }
                            catch { DropConnection(); }
                        }, data);

                        _incomingData = _incomingData.TrimLeft(_objectDataLength.Value);
                        _objectDataLength = null;
                        exitWhile = false;
                    }
                }
                else
                    if (_incomingData.Length >= IntSize)
                    {
                        _objectDataLength = BitConverter.ToInt32(_incomingData.TakeLeft(IntSize), 0);
                        _incomingData = _incomingData.TrimLeft(IntSize);
                        exitWhile = false;
                    }
            }
            StartReceive();
        }


        public void Dispose() { DropConnection(); }
    }
}

That is just an example, you should edit it for your use.

Linq select to new object

If you want to be able to perform a lookup on each type to get its frequency then you will need to transform the enumeration into a dictionary.

var types = new[] {typeof(string), typeof(string), typeof(int)};
var x = types
        .GroupBy(type => type)
        .ToDictionary(g => g.Key, g => g.Count());
foreach (var kvp in x) {
    Console.WriteLine("Type {0}, Count {1}", kvp.Key, kvp.Value);
}
Console.WriteLine("string has a count of {0}", x[typeof(string)]);

Java: Check if command line arguments are null

if i want to check if any speicfic position of command line arguement is passed or not then how to check? like for example in some scenarios 2 command line args will be passed and in some only one will be passed then how do it check wheather the specfic commnad line is passed or not?

public class check {

public static void main(String[] args) {
if(args[0].length()!=0)
{
System.out.println("entered first if");
}
if(args[0].length()!=0 && args[1].length()!=0)
{
System.out.println("entered second if");
}
}
}

So in the above code if args[1] is not passed then i get java.lang.ArrayIndexOutOfBoundsException:

so how do i tackle this where i can check if second arguement is passed or not and if passed then enter it. need assistance asap.

SELECT with LIMIT in Codeigniter

Try this...

function nationList($limit=null, $start=null) {
    if ($this->session->userdata('language') == "it") {
        $this->db->select('nation.id, nation.name_it as name');
    }

    if ($this->session->userdata('language') == "en") {
        $this->db->select('nation.id, nation.name_en as name');
    }

    $this->db->from('nation');
    $this->db->order_by("name", "asc");

    if ($limit != '' && $start != '') {
       $this->db->limit($limit, $start);
    }
    $query  = $this->db->get();

    $nation = array();
    foreach ($query->result() as $row) {
        array_push($nation, $row);
    }

    return $nation;     
}

Convert pandas Series to DataFrame

Rather than create 2 temporary dfs you can just pass these as params within a dict using the DataFrame constructor:

pd.DataFrame({'email':sf.index, 'list':sf.values})

There are lots of ways to construct a df, see the docs

What is the purpose of a question mark after a type (for example: int? myVariable)?

It means that the value type in question is a nullable type

Nullable types are instances of the System.Nullable struct. A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, a Nullable<Int32>, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. A Nullable<bool> can be assigned the values true, false, or null. The ability to assign null to numeric and Boolean types is especially useful when you are dealing with databases and other data types that contain elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined.

class NullableExample
{
  static void Main()
  {
      int? num = null;

      // Is the HasValue property true?
      if (num.HasValue)
      {
          System.Console.WriteLine("num = " + num.Value);
      }
      else
      {
          System.Console.WriteLine("num = Null");
      }

      // y is set to zero
      int y = num.GetValueOrDefault();

      // num.Value throws an InvalidOperationException if num.HasValue is false
      try
      {
          y = num.Value;
      }
      catch (System.InvalidOperationException e)
      {
          System.Console.WriteLine(e.Message);
      }
  }
}

How to enter a series of numbers automatically in Excel

Use formula =row(b2)-x, where x will adjust the entries so that the first S/No is marked as 1 and will increment with the rows.

npm check and update package if needed

Check outdated packages

npm outdated

Check and pick packages to update

npx npm-check -u

npm oudated img

npx npm-check -u img

How do you perform address validation?

In the course of developing an in-house address verification service at a German company I used to work for I've come across a number of ways to tackle this issue. I'll do my best to sum up my findings below:

Free, Open Source Software

Clearly, the first approach anyone would take is an open-source one (like openstreetmap.org), which is never a bad idea. But whether or not you can really put this to good and reliable use depends very much on how much you need to rely on the results.

Addresses are an incredibly variable thing. Verifying U.S. addresses is not an easy task, but bearable, but once you're going for Europe, especially the U.K. with their extensive Postal Code system, the open-source approach will simply lack data.

Web Services / APIs

Enterprise-Class Software

Money gets it done, obviously. But not every business or developer can spend ~$0.15 per address lookup (that's $150 for 1,000 API requests) - a very expensive business model the vast majority of address validation APIs have implemented.

What I ended up integrating: streetlayer API

Since I was not willing to take on the programmatic approach of verifying address data manually I finally came to the conclusion that I was in need of an API with a price tag that would not make my boss want to fire me and still deliver solid and reliable international verification results.

Long story short, I ended up integrating an API built by apilayer, called "streetlayer API". I was easily convinced by a simple JSON integration, surprisingly accurate validation results and their developer-friendly pricing. Also, 100 requests/month are entirely free.

Hope this helps!

How to set width and height dynamically using jQuery

I tried all of the suggestions above and none of them worked for me, they changed the clientWidth and clientHeight not the actual width and height.

The jQuery docs for $().width and height methods says: "Note that .width("value") sets the content width of the box regardless of the value of the CSS box-sizing property."

The css approach did the same thing so I had to use the $().attr() methods instead.

_canvas.attr('width', 100);
_canvas.attr('height', 200);

I don't know is this affect me because I was trying to resize a element and it is some how different or not.

How do you initialise a dynamic array in C++?

Two ways:

char *c = new char[length];
std::fill(c, c + length, INITIAL_VALUE);
// just this once, since it's char, you could use memset

Or:

std::vector<char> c(length, INITIAL_VALUE);

In my second way, the default second parameter is 0 already, so in your case it's unnecessary:

std::vector<char> c(length);

[Edit: go vote for Fred's answer, char* c = new char[length]();]

Styling Password Fields in CSS

The best I can find is to set input[type="password"] {font:small-caption;font-size:16px}

Demo:

_x000D_
_x000D_
input {_x000D_
  font: small-caption;_x000D_
  font-size: 16px;_x000D_
}
_x000D_
<input type="password">
_x000D_
_x000D_
_x000D_

Python "extend" for a dictionary

a.update(b)

Will add keys and values from b to a, overwriting if there's already a value for a key.

MySQL DISTINCT on a GROUP_CONCAT()

DISTINCT: will gives you unique values.

SELECT GROUP_CONCAT(DISTINCT(categories )) AS categories FROM table

How to add 30 minutes to a JavaScript Date object?

I know that the topic is way too old. But I am pretty sure that there are some developpers who still need this, so I made this simple script for you. I hope you enjoy it!

Hello back, It's 2020 and I've added some modification hope it will help a lot better now!

_x000D_
_x000D_
function strtotime(date, addTime){
  let generatedTime=date.getTime();
  if(addTime.seconds) generatedTime+=1000*addTime.seconds; //check for additional seconds 
  if(addTime.minutes) generatedTime+=1000*60*addTime.minutes;//check for additional minutes 
  if(addTime.hours) generatedTime+=1000*60*60*addTime.hours;//check for additional hours 
  return new Date(generatedTime);
}

Date.prototype.strtotime = function(addTime){
  return strtotime(new Date(), addTime); 
}

let futureDate = new Date().strtotime({
    hours: 16, //Adding one hour
    minutes: 45, //Adding fourty five minutes
    seconds: 0 //Adding 0 seconds return to not adding any second so  we can remove it.
});
_x000D_
<button onclick="console.log(futureDate)">Travel to the future</button>
_x000D_
_x000D_
_x000D_

How do I use PHP to get the current year?

You can use either date or strftime. In this case I'd say it doesn't matter as a year is a year, no matter what (unless there's a locale that formats the year differently?)

For example:

<?php echo date("Y"); ?>

On a side note, when formatting dates in PHP it matters when you want to format your date in a different locale than your default. If so, you have to use setlocale and strftime. According to the php manual on date:

To format dates in other languages, you should use the setlocale() and strftime() functions instead of date().

From this point of view, I think it would be best to use strftime as much as possible, if you even have a remote possibility of having to localize your application. If that's not an issue, pick the one you like best.

Parse RSS with jQuery

The jQuery-rss project is pretty lightweight and doesn't impose any particular styling.

The syntax can be as simple as

$("#rss-feeds").rss("http://www.recruiter.com/feed/career.xml")

See a working example at http://jsfiddle.net/jhfrench/AFHfn/

How do I find out which keystore was used to sign an app?

You can do this with the apksigner tool that is part of the Android SDK:

apksigner verify --print-certs my_app.apk

You can find apksigner inside the build-tools directory. For example: ~/Library/Android/sdk/build-tools/29.0.1/apksigner

Pass values of checkBox to controller action in asp.net mvc4

For some reason Andrew method of creating the checkbox by hand didn't work for me using Mvc 5. Instead I used this

@Html.CheckBox("checkResp")

to create a checkbox that would play nice with the controller.

SSRS Query execution failed for dataset

I had the similar issue showing the error

For more information about this error navigate to the report server on the local server machine, or enable remote errors Query execution failed for dataset 'PrintInvoice'.

Solution: 1) The error may be with the dataset in some cases, you can always check if the dataset is populating the exact data you are expecting by going to the dataset properties and choosing 'Query Designer' and try 'Run', If you can successfully able to pull the fields you are expecting, then you can be sure that there isn't any problem with the dataset, which takes us to next solution.

2) Even though the error message says "Query Failed Execution for the dataset", another probable chances are with the datasource connection, make sure you have connected to the correct datasource that has the tables you need and you have permissions to access that datasource.

How to break long string to multiple lines

If the long string to multiple lines confuses you. Then you may install mz-tools addin which is a freeware and has the utility which splits the line for you.

Download Mz-tools

If your string looks like below

SqlQueryString = "Insert into Employee values(" & txtEmployeeNo.Value & "','" & txtContractStartDate.Value & "','" & txtSeatNo.Value & "','" & txtFloor.Value & "','" & txtLeaves.Value & "')"

Simply select the string > right click on VBA IDE > Select MZ-tools > Split Lines

enter image description here

Adding Google Play services version to your app's manifest?

In my case i had to install google repository from the SDK manager.

Download file and automatically save it to folder

A much simpler solution would be to download the file using Chrome. In this manner you don't have to manually click on the save button.

using System;
using System.Diagnostics;
using System.ComponentModel;

namespace MyProcessSample
{
    class MyProcess
    {
        public static void Main()
        {
            Process myProcess = new Process();
            myProcess.Start("chrome.exe","http://www.com/newfile.zip");
        }
    }
}

Setting selected values for ng-options bound select elements

You can use the ID field as the equality identifier. You can't use the adhoc object for this case because AngularJS checks references equality when comparing objects.

<select 
    ng-model="Choice.SelectedOption.ID" 
    ng-options="choice.ID as choice.Name for choice in Choice.Options">
</select>

Java - Check if JTextField is empty or not

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

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

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

Reading from memory stream to string

If you'd checked the results of stream.Read, you'd have seen that it hadn't read anything - because you haven't rewound the stream. (You could do this with stream.Position = 0;.) However, it's easier to just call ToArray:

settingsString = LocalEncoding.GetString(stream.ToArray());

(You'll need to change the type of stream from Stream to MemoryStream, but that's okay as it's in the same method where you create it.)

Alternatively - and even more simply - just use StringWriter instead of StreamWriter. You'll need to create a subclass if you want to use UTF-8 instead of UTF-16, but that's pretty easy. See this answer for an example.

I'm concerned by the way you're just catching Exception and assuming that it means something harmless, by the way - without even logging anything. Note that using statements are generally cleaner than writing explicit finally blocks.

How do I reference tables in Excel using VBA?

In addition, it's convenient to define variables referring to objects. For instance,

Sub CreateTable()
    Dim lo as ListObject
    Set lo = ActiveSheet.ListObjects.Add(xlSrcRange, Range("$B$1:$D$16"), , xlYes)
    lo.Name = "Table1"
    lo.TableStyle = "TableStyleLight2"
    ...
End Sub

You will probably find it advantageous at once.

Security of REST authentication schemes

A previous answer only mentioned SSL in the context of data transfer and didn't actually cover authentication.

You're really asking about securely authenticating REST API clients. Unless you're using TLS client authentication, SSL alone is NOT a viable authentication mechanism for a REST API. SSL without client authc only authenticates the server, which is irrelevant for most REST APIs because you really want to authenticate the client.

If you don't use TLS client authentication, you'll need to use something like a digest-based authentication scheme (like Amazon Web Service's custom scheme) or OAuth 1.0a or even HTTP Basic authentication (but over SSL only).

These schemes authenticate that the request was sent by someone expected. TLS (SSL) (without client authentication) ensures that the data sent over the wire remains untampered. They are separate - but complementary - concerns.

For those interested, I've expanded on an SO question about HTTP Authentication Schemes and how they work.

setting global sql_mode in mysql

set global sql_mode="NO_BACKSLASH_ESCAPES,STRICT_TRANS_TABLE,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

How Should I Set Default Python Version In Windows?

Nothing above worked, this is what worked for me:

ftype Python.File=C:\Path\to\python.exe "%1" %*

This command should be run in Command prompt launched as administrator

Warning: even if the path in this command is set to python35, if you have python36 installed it's going to set the default to python36. To prevent this, you can temporarily change the folder name from Python36 to xxPython36, run the command and then remove the change to the Python 36 folder.

Xcode 4: create IPA file instead of .xcarchive

One who has tried all other answers and had no luck the please check this check box, hope it'll help (did the trick for me xcode 6.0.1)

enter image description here

Edit Crystal report file without Crystal Report software

If this is something you are only going to need to do once, have you considered downloading a demo version of Crystal? There's a 30-day trial version available here: http://www.developers.net/businessobjectsshowcase/view/3154

Of course, if you need to edit these files after the 30 day period is over, you would be better off buying Crystal.

Alternatively, if all you need to do is replace a few static literal words, have you tried doing a search and replace in a text editor? (Don't forget to save the original files somewhere safe first!)

Is it possible to use Java 8 for Android development?

Latest news:

Google announce that with Android N and Android Studio 2.1+, platform will support Java 8. Also stable version of studio 2.1 was released.

At last we can use lambda expressions. No more list filter in for loop. Horeeey.

CURRENT_DATE/CURDATE() not working as default DATE value

declare your date column as NOT NULL, but without a default. Then add this trigger:

USE `ddb`;
DELIMITER $$
CREATE TRIGGER `default_date` BEFORE INSERT ON `dtable` FOR EACH ROW
if ( isnull(new.query_date) ) then
 set new.query_date=curdate();
end if;
$$
delimiter ;

How to use multiple databases in Laravel

Using .env >= 5.0 (tested on 5.5)

In .env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database1
DB_USERNAME=root
DB_PASSWORD=secret

DB_CONNECTION_SECOND=mysql
DB_HOST_SECOND=127.0.0.1
DB_PORT_SECOND=3306
DB_DATABASE_SECOND=database2
DB_USERNAME_SECOND=root
DB_PASSWORD_SECOND=secret

In config/database.php

'mysql' => [
    'driver'    => env('DB_CONNECTION'),
    'host'      => env('DB_HOST'),
    'port'      => env('DB_PORT'),
    'database'  => env('DB_DATABASE'),
    'username'  => env('DB_USERNAME'),
    'password'  => env('DB_PASSWORD'),
],

'mysql2' => [
    'driver'    => env('DB_CONNECTION_SECOND'),
    'host'      => env('DB_HOST_SECOND'),
    'port'      => env('DB_PORT_SECOND'),
    'database'  => env('DB_DATABASE_SECOND'),
    'username'  => env('DB_USERNAME_SECOND'),
    'password'  => env('DB_PASSWORD_SECOND'),
],

Note: In mysql2 if DB_username and DB_password is same, then you can use env('DB_USERNAME') which is metioned in .env first few lines.

Without .env <5.0

Define Connections

app/config/database.php

return array(

    'default' => 'mysql',

    'connections' => array(

        # Primary/Default database connection
        'mysql' => array(
            'driver'    => 'mysql',
            'host'      => '127.0.0.1',
            'database'  => 'database1',
            'username'  => 'root',
            'password'  => 'secret'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

        # Secondary database connection
        'mysql2' => array(
            'driver'    => 'mysql',
            'host'      => '127.0.0.1',
            'database'  => 'database2',
            'username'  => 'root',
            'password'  => 'secret'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),
    ),
);

Schema

To specify which connection to use, simply run the connection() method

Schema::connection('mysql2')->create('some_table', function($table)
{
    $table->increments('id'):
});

Query Builder

$users = DB::connection('mysql2')->select(...);

Eloquent

Set the $connection variable in your model

class SomeModel extends Eloquent {

    protected $connection = 'mysql2';

}

You can also define the connection at runtime via the setConnection method or the on static method:

class SomeController extends BaseController {

    public function someMethod()
    {
        $someModel = new SomeModel;

        $someModel->setConnection('mysql2'); // non-static method

        $something = $someModel->find(1);

        $something = SomeModel::on('mysql2')->find(1); // static method

        return $something;
    }

}

Note Be careful about attempting to build relationships with tables across databases! It is possible to do, but it can come with some caveats and depends on what database and/or database settings you have.


From Laravel Docs

Using Multiple Database Connections

When using multiple connections, you may access each connection via the connection method on the DB facade. The name passed to the connection method should correspond to one of the connections listed in your config/database.php configuration file:

$users = DB::connection('foo')->select(...);

You may also access the raw, underlying PDO instance using the getPdo method on a connection instance:

$pdo = DB::connection()->getPdo();

Useful Links

  1. Laravel 5 multiple database connection FROM laracasts.com
  2. Connect multiple databases in laravel FROM tutsnare.com
  3. Multiple DB Connections in Laravel FROM fideloper.com

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

I had this error aswell.

I am working in mysql workbench. When giving the values they have to be inside "". That solved it for me.

How do I import a Swift file from another Swift file?

In Objective-C, if you wanted to use a class in another file you had to import it:

#import "SomeClass.h"

However, in Swift, you don't have to import at all. Simply use it as if it was already imported.

Example

// This is a file named SomeClass.swift

class SomeClass : NSObject {

}

// This is a different file, named OtherClass.swift

class OtherClass : NSObject {
    let object = SomeClass()
}

As you can see, no import was needed. Hope this helps.

ConnectivityManager getNetworkInfo(int) deprecated

You can use:

getActiveNetworkInfo();

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) { 
    // connected to the internet
    if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
        // connected to wifi
    } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
        // connected to mobile data
    }
} else {
    // not connected to the internet
}

Or in a switch case

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) { 
    // connected to the internet
    switch (activeNetwork.getType()) {
        case ConnectivityManager.TYPE_WIFI:
            // connected to wifi
            break;
        case ConnectivityManager.TYPE_MOBILE:
            // connected to mobile data
            break;
        default:
            break;
    }
} else {
    // not connected to the internet
}

Bootstrap Collapse not Collapsing

Maybe your mobile view port is not set. Add following meta tag inside <head></head> to allow menu to work on mobiles.

<meta name=viewport content="width=device-width, initial-scale=1">

Installing cmake with home-brew

  1. Download the latest CMake Mac binary distribution here: https://cmake.org/download/ (current latest is: https://cmake.org/files/v3.17/cmake-3.17.1-Darwin-x86_64.dmg)

  2. Double click the downloaded .dmg file to install it. In the window that pops up, drag the CMake icon into the Application folder.

  3. Add this line to your .bashrc file: PATH="/Applications/CMake.app/Contents/bin":"$PATH"

  4. Reload your .bashrc file: source ~/.bashrc

  5. Verify the latest cmake version is installed: cmake --version

  6. You can launch the CMake GUI by clicking on LaunchPad and typing cmake. Click on the CMake icon that appears.

Address validation using Google Maps API

The answer depends upon the degree of confidence you place in the data and how your data is being used. For example, if you're using it for mailing or shipping, you'll want to be be confident that the data is correct. If you're just using it as another fraud-prevention mechanism then you could potentially allow a degree of error to creep into the data.

If you want any degree of real accuracy, you're need to go with a service that does real address verification and you're going to have to pay for it. As has been mentioned by Adam, address verification and validation at first seems simple and easy, but it's a black hole fraught with challenges and, unless you've some underlying data to work with, virtually impossible to do by yourself. Trust me, you're actually saving money by using a service. You're welcome to go down this road yourself to experience what I mean, but I can guarantee you'll see the light, so to speak, after even a few hours (or days) of spinning your wheels.

I should mention that I'm the founder of SmartyStreets. We do address validation and verification addresses and we offer this for the USA and international as well. I'm more than happy to personally answer any questions you have on the topic of address cleansing, standardization, and validation.

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

@Valkyrie awesome answer. Thought I put in here a case when performing the same with a subquery insides a stored procedure, as I wondered if your answer works in this case, and it did awesome.

...WHERE fieldname COLLATE DATABASE_DEFAULT in (
          SELECT DISTINCT otherfieldname COLLATE DATABASE_DEFAULT
          FROM ...
          WHERE ...
        )

Docker error cannot delete docker container, conflict: unable to remove repository reference

Noticed this is a 2-years old question, but still want to share my workaround for this particular question:

Firstly, run docker container ls -a to list all the containers you have and pinpoint the want you want to delete.

Secondly, delete the one with command docker container rm <CONTAINER ID> (If the container is currently running, you should stop it first, run docker container stop <CONTAINER ID> to gracefully stop the specified container, if it does not stop it for whatever the reason is, alternatively you can run docker container kill <CONTAINER ID> to force shutdown of the specified container).

Thirdly, remove the container by running docker container rm <CONTAINER ID>.

Lastly you can run docker image ls -a to view all the images and delete the one you want to by running docker image rm <hash>.

Proper MIME type for OTF fonts

As from March 2013 IANA.ORG recommends for .otf:
application/font-sfnt

Other fonts:

.eot  ->  application/vnd.ms-fontobject (as from December 2005)
.otf  ->  application/font-sfnt         (as from March 2013)
.svg  ->  image/svg+xml                 (as from August 2011)
.ttf  ->  application/font-sfnt         (as from March 2013)
.woff ->  application/font-woff         (as from January 2013)

See more...

R dates "origin" must be supplied

by the way, the zoo package, if it is loaded, overrides the base as.Date() with its own which, by default, provides origin="1970-01-01".

(i mention this in case you find that sometimes you need to add the origin, and sometimes you don't.)

Difference between the 'controller', 'link' and 'compile' functions when defining a directive

As complement to Mark's answer, the compile function does not have access to scope, but the link function does.

I really recommend this video; Writing Directives by Misko Hevery (the father of AngularJS), where he describes differences and some techniques. (Difference between compile function and link function at 14:41 mark in the video).

How to use new PasswordEncoder from Spring Security

I had a similar issue. I needed to keep the legacy encrypted passwords (Base64/SHA-1/Random salt Encoded) as users will not want to change their passwords or re-register. However I wanted to use the BCrypt encoder moving forward too.

My solution was to write a bespoke decoder that checks to see which encryption method was used first before matching (BCrypted ones start with $).

To get around the salt issue, I pass into the decoder a concatenated String of salt + encrypted password via my modified user object.

Decoder

@Component
public class LegacyEncoder implements PasswordEncoder {

    private static final String BCRYP_TYPE = "$";
    private static final PasswordEncoder BCRYPT = new BCryptPasswordEncoder();

    @Override
    public String encode(CharSequence rawPassword) {

    return BCRYPT.encode(rawPassword);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {

    if (encodedPassword.startsWith(BCRYP_TYPE)) {
        return BCRYPT.matches(rawPassword, encodedPassword);
    }

    return sha1SaltMatch(rawPassword, encodedPassword);
    }

    @SneakyThrows
    private boolean sha1SaltMatch(CharSequence rawPassword, String encodedPassword) {

    String[] saltHash = encodedPassword.split(User.SPLIT_CHAR);

    // Legacy code from old system   
    byte[] b64salt = Base64.getDecoder().decode(saltHash[0].getBytes());
    byte[] validHash = Base64.getDecoder().decode(saltHash[1]);
    byte[] checkHash = Utility.getHash(5, rawPassword.toString(), b64salt);

    return Arrays.equals(checkHash, validHash);
    }

}

User Object

public class User implements UserDetails {

    public static final String SPLIT_CHAR = ":";

    @Id
    @Column(name = "user_id", nullable = false)
    private Integer userId;

    @Column(nullable = false, length = 60)
    private String password;

    @Column(nullable = true, length = 32)
    private String salt;

.
.

    @PostLoad
    private void init() {

    username = emailAddress; //To comply with UserDetails
    password = salt == null ? password : salt + SPLIT_CHAR + password;
    }        

You can also add a hook to re-encode the password in the new BCrypt format and replace it. Thus phasing out the old method.

In the shell, what does " 2>&1 " mean?

Note that 1>&2 cannot be used interchangeably with 2>&1.

Imagine your command depends on piping, for example:
docker logs 1b3e97c49e39 2>&1 | grep "some log"
grepping will happen across both stderr and stdout since stderr is basically merged into stdout.

However, if you try:
docker logs 1b3e97c49e39 1>&2 | grep "some log",
grepping will not really search anywhere at all because Unix pipe is connecting processes via connecting stdout | stdin, and stdout in the second case was redirected to stderr in which Unix pipe has no interest.

How to clear the canvas for redrawing

Use clearRect method by passing x,y co-ordinates and height and width of canvas. ClearRect will clear whole canvas as :

canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);

Getting a list of associative array keys

Just a quick note. Be wary of using for..in if you use a library (jQuery, Prototype, etc.), as most of them add methods to created Objects (including dictionaries).

This will mean that when you loop over them, method names will appear as keys. If you are using a library, look at the documentation and look for an enumerable section, where you will find the right methods for iteration of your objects.

Update Git submodule to latest commit on origin

The git submodule update command actually tells Git that you want your submodules to each check out the commit already specified in the index of the superproject. If you want to update your submodules to the latest commit available from their remote, you will need to do this directly in the submodules.

So in summary:

# Get the submodule initially
git submodule add ssh://bla submodule_dir
git submodule init

# Time passes, submodule upstream is updated
# and you now want to update

# Change to the submodule directory
cd submodule_dir

# Checkout desired branch
git checkout master

# Update
git pull

# Get back to your project root
cd ..

# Now the submodules are in the state you want, so
git commit -am "Pulled down update to submodule_dir"

Or, if you're a busy person:

git submodule foreach git pull origin master

Basic calculator in Java

maybe its better using the case instead of if dunno if this eliminates the error, but its cleaner i think.. switch (operation){case +: System.out.println("your answer is" + (num1 + num2));break;case -: System.out.println("your answer is" - (num1 - num2));break; ...

Measure execution time for a Java method

As proposed nanoTime () is very precise on short time scales. When this precision is required you need to take care about what you really measure. Especially not to measure the nanotime call itself

long start1 = System.nanoTime();
// maybe add here a call to a return to remove call up time, too.
// Avoid optimization 
long start2 = System.nanoTime();
myCall(); 
long stop = System.nanoTime();
long diff = stop - 2*start2 + start1;

System.out.println(diff + " ns");

By the way, you will measure different values for the same call due to

  • other load on your computer (background, network, mouse movement, interrupts, task switching, threads)
  • cache fillings (cold, warm)
  • jit compiling (no optimization, performance hit due to running the compiler, performance boost due to compiler (but sometimes code with jit is slower than without!))

How to get back Lost phpMyAdmin Password, XAMPP

Reinstalling the software fixes the issue, just make sure not to delete the htdocs folder in the process.

Condition within JOIN or WHERE

I prefer the JOIN to join full tables/Views and then use the WHERE To introduce the predicate of the resulting set.

It feels syntactically cleaner.

How to avoid "cannot load such file -- utils/popen" from homebrew on OSX

In my case I just needed to remove Homebrew's executable using:

sudo rm -f `which brew`

Then reinstall Homebrew:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Call and receive output from Python script in Java?

You can include the Jython library in your Java Project. You can download the source code from the Jython project itself.

Jython does offers support for JSR-223 which basically lets you run a Python script from Java.

You can use a ScriptContext to configure where you want to send your output of the execution.

For instance, let's suppose you have the following Python script in a file named numbers.py:

for i in range(1,10):
    print(i)

So, you can run it from Java as follows:

public static void main(String[] args) throws ScriptException, IOException {

    StringWriter writer = new StringWriter(); //ouput will be stored here

    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptContext context = new SimpleScriptContext();

    context.setWriter(writer); //configures output redirection
    ScriptEngine engine = manager.getEngineByName("python");
    engine.eval(new FileReader("numbers.py"), context);
    System.out.println(writer.toString()); 
}

And the output will be:

1
2
3
4
5
6
7
8
9

As long as your Python script is compatible with Python 2.5 you will not have any problems running this with Jython.

Retrieve a single file from a repository

I solved in this way:

git archive --remote=ssh://[email protected]/user/mi-repo.git BranchName /path-to-file/file_name | tar -xO /path-to-file/file_name > /path-to-save-the-file/file_name

If you want, you could replace "BranchName" for "HEAD"

CSS content property: is it possible to insert HTML instead of Text?

As almost noted in comments to @BoltClock's answer, in modern browsers, you can actually add some html markup to pseudo-elements using the (url()) in combination with svg's <foreignObject> element.

You can either specify an URL pointing to an actual svg file, or create it with a dataURI version (data:image/svg+xml; charset=utf8, + encodeURIComponent(yourSvgMarkup))

But note that it is mostly a hack and that there are a lot of limitations :

  • You can not load any external resources from this markup (no CSS, no images, no media etc.).
  • You can not execute script.
  • Since this won't be part of the DOM, the only way to alter it, is to pass the markup as a dataURI, and edit this dataURI in document.styleSheets. for this part, DOMParser and XMLSerializer may help.
  • While the same operation allows us to load url-encoded media in <img> tags, this won't work in pseudo-elements (at least as of today, I don't know if it is specified anywhere that it shouldn't, so it may be a not-yet implemented feature).

Now, a small demo of some html markup in a pseudo element :

_x000D_
_x000D_
/* _x000D_
**  original svg code :_x000D_
*_x000D_
*<svg width="200" height="60"_x000D_
*     xmlns="http://www.w3.org/2000/svg">_x000D_
*_x000D_
* <foreignObject width="100%" height="100%" x="0" y="0">_x000D_
* <div xmlns="http://www.w3.org/1999/xhtml" style="color: blue">_x000D_
*  I am <pre>HTML</pre>_x000D_
* </div>_x000D_
* </foreignObject>_x000D_
*</svg>_x000D_
*_x000D_
*/
_x000D_
#log::after {_x000D_
  content: url('data:image/svg+xml;%20charset=utf8,%20%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20height%3D%2260%22%20width%3D%22200%22%3E%0A%0A%20%20%3CforeignObject%20y%3D%220%22%20x%3D%220%22%20height%3D%22100%25%22%20width%3D%22100%25%22%3E%0A%09%3Cdiv%20style%3D%22color%3A%20blue%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxhtml%22%3E%0A%09%09I%20am%20%3Cpre%3EHTML%3C%2Fpre%3E%0A%09%3C%2Fdiv%3E%0A%20%20%3C%2FforeignObject%3E%0A%3C%2Fsvg%3E');_x000D_
}
_x000D_
<p id="log">hi</p>
_x000D_
_x000D_
_x000D_

With MySQL, how can I generate a column containing the record index in a table?

Here comes the structure of template I used:

  select
          /*this is a row number counter*/
          ( select @rownum := @rownum + 1 from ( select @rownum := 0 ) d2 ) 
          as rownumber,
          d3.*
  from 
  ( select d1.* from table_name d1 ) d3

And here is my working code:

select     
           ( select @rownum := @rownum + 1 from ( select @rownum := 0 ) d2 ) 
           as rownumber,
           d3.*
from
(   select     year( d1.date ), month( d1.date ), count( d1.id )
    from       maindatabase d1
    where      ( ( d1.date >= '2013-01-01' ) and ( d1.date <= '2014-12-31' ) )
    group by   YEAR( d1.date ), MONTH( d1.date ) ) d3

Hibernate dialect for Oracle Database 11g?

At least in case of EclipseLink 10g and 11g differ. Since 11g it is not recommended to use first_rows hint for pagination queries.

See "Is it possible to disable jpa hints per particular query". Such a query should not be used in 11g.

SELECT * FROM (
  SELECT /*+ FIRST_ROWS */ a.*, ROWNUM rnum  FROM (
    SELECT * FROM TABLES INCLUDING JOINS, ORDERING, etc.) a
  WHERE ROWNUM <= 10 )
WHERE rnum > 0;

But there can be other nuances.

How can I make a JPA OneToOne relation lazy

If the relation must not be bidirectional then an @ElementCollection might be easier than using a lazy One2Many collection.

How to copy folders to docker image from Dockerfile?

Replace the * with a /

So instead of

COPY * <destination>

use

COPY / <destination>

How to resolve git error: "Updates were rejected because the tip of your current branch is behind"

This worked for me:

git branch

Copy the current branch name to clipboard

git pull origin <paste-branch-name>
git push

How to do a recursive find/replace of a string with awk or sed?

Using combination of grep and sed

for pp in $(grep -Rl looking_for_string)
do
    sed -i 's/looking_for_string/something_other/g' "${pp}"
done

CSS two divs next to each other

The method suggested by @roe and @MohitNanda work, but if the right div is set as float:right;, then it must come first in the HTML source. This breaks the left-to-right read order, which could be confusing if the page is displayed with styles turned off. If that's the case, it might be better to use a wrapper div and absolute positioning:

<div id="wrap" style="position:relative;">
    <div id="left" style="margin-right:201px;border:1px solid red;">left</div>
    <div id="right" style="position:absolute;width:200px;right:0;top:0;border:1px solid blue;">right</div>
</div>

Demonstrated:

left right

Edit: Hmm, interesting. The preview window shows the correctly formatted divs, but the rendered post item does not. Sorry then, you'll have to try it for yourself.

Int to Char in C#

int i = 65;
char c = Convert.ToChar(i);

How to list branches that contain a given commit?

You may run:

git log <SHA1>..HEAD --ancestry-path --merges

From comment of last commit in the output you may find original branch name

Example:

       c---e---g--- feature
      /         \
-a---b---d---f---h---j--- master

git log e..master --ancestry-path --merges

commit h
Merge: g f
Author: Eugen Konkov <>
Date:   Sat Oct 1 00:54:18 2016 +0300

    Merge branch 'feature' into master

How do I rename the extension for a bunch of files?

Try this

rename .html .txt *.html 

usage:

rename [find] [replace_with] [criteria]

Select a Column in SQL not in Group By

What you are asking, Sir, is as the answer of RedFilter. This answer as well helps in understanding why group by is somehow a simpler version or partition over: SQL Server: Difference between PARTITION BY and GROUP BY since it changes the way the returned value is calculated and therefore you could (somehow) return columns group by can not return.

Check for internet connection with Swift

Updated version of @martin's answer for Swift 5+ using Combine. This one also includes unavailibity reason check for iOS 14.

import Combine
import Network

enum NetworkType {
    case wifi
    case cellular
    case loopBack
    case wired
    case other
}

final class ReachabilityService: ObservableObject {

    @Published var reachabilityInfos: NWPath?
    @Published var isNetworkAvailable: Bool?
    @Published var typeOfCurrentConnection: NetworkType?

    private let monitor = NWPathMonitor()
    private let backgroundQueue = DispatchQueue.global(qos: .background)

    init() {
        setUp()
    }

    init(with interFaceType: NWInterface.InterfaceType) {
        setUp()
    }

    deinit {
        monitor.cancel()
    }
}

private extension ReachabilityService {

    func setUp() {

        monitor.pathUpdateHandler = { [weak self] path in
            self?.reachabilityInfos = path
            switch path.status {
            case .satisfied:
                print("ReachabilityService: satisfied")
                self?.isNetworkAvailable = true
                break
            case .unsatisfied:
                print("ReachabilityService: unsatisfied")

                if #available(iOS 14.2, *) {
                    switch path.unsatisfiedReason {

                    case .notAvailable:
                        print("ReachabilityService: unsatisfiedReason: notAvailable")
                        break
                    case .cellularDenied:
                        print("ReachabilityService: unsatisfiedReason: cellularDenied")
                        break
                    case .wifiDenied:
                        print("ReachabilityService: unsatisfiedReason: wifiDenied")
                        break
                    case .localNetworkDenied:
                        print("ReachabilityService: unsatisfiedReason: localNetworkDenied")
                        break
                    @unknown default:
                        print("ReachabilityService: unsatisfiedReason: default")
                    }
                } else {
                    // Fallback on earlier versions
                }

                self?.isNetworkAvailable = false
                break
            case .requiresConnection:
                print("ReachabilityService: requiresConnection")
                self?.isNetworkAvailable = false
                break
            @unknown default:
                print("ReachabilityService: default")
                self?.isNetworkAvailable = false
            }
            if path.usesInterfaceType(.wifi) {
                self?.typeOfCurrentConnection = .wifi
            } else if path.usesInterfaceType(.cellular) {
                self?.typeOfCurrentConnection = .cellular
            } else if path.usesInterfaceType(.loopback) {
                self?.typeOfCurrentConnection = .loopBack
            } else if path.usesInterfaceType(.wiredEthernet) {
                self?.typeOfCurrentConnection = .wired
            } else if path.usesInterfaceType(.other) {
                self?.typeOfCurrentConnection = .other
            }
        }

        monitor.start(queue: backgroundQueue)
    }
}

Usage:

In your view model:

private let reachability = ReachabilityService()

init() {
    reachability.$isNetworkAvailable.sink { [weak self] isConnected in
        self?.isConnected = isConnected ?? false
    }.store(in: &cancelBag)
}

In your controller:

viewModel.$isConnected.sink { [weak self] isConnected in
    print("isConnected: \(isConnected)")
    DispatchQueue.main.async {
        //Update your UI in here
    }
}.store(in: &bindings)

Uncaught TypeError: Object #<Object> has no method 'movingBoxes'

Please keep in mind that only a few elements can be self-closing, most others have to be closed through adding an explicit end tag. In the above case, the first script tag was not closed properly, the end script tag of the second script then closed the script section, causing only the first script to be loaded as external script source and ignoring the second script.

More info about which tags can be self-closed, have a look at the W3C drafts for HTML5 (although the definition was no different in earlier HTML-versions):

http://www.w3.org/TR/html5/syntax.html#end-tags (8.1.2.1, Point 6)

How to change the color of progressbar in C# .NET 3.5?

Since the previous answers don't appear to work in with Visual Styles. You'll probably need to create your own class or extend the progress bar:

public class NewProgressBar : ProgressBar
{
    public NewProgressBar()
    {
        this.SetStyle(ControlStyles.UserPaint, true);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        Rectangle rec = e.ClipRectangle;

        rec.Width = (int)(rec.Width * ((double)Value / Maximum)) - 4;
        if(ProgressBarRenderer.IsSupported)
           ProgressBarRenderer.DrawHorizontalBar(e.Graphics, e.ClipRectangle);
        rec.Height = rec.Height - 4;
        e.Graphics.FillRectangle(Brushes.Red, 2, 2, rec.Width, rec.Height);
    }
}

EDIT: Updated code to make the progress bar use the visual style for the background

How to hide Soft Keyboard when activity starts

Use the following functions to show/hide the keyboard:

/**
 * Hides the soft keyboard
 */
public void hideSoftKeyboard() {
    if(getCurrentFocus()!=null) {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    }
}

/**
 * Shows the soft keyboard
 */
public void showSoftKeyboard(View view) {
    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
    view.requestFocus();
    inputMethodManager.showSoftInput(view, 0);
}

Clearing a string buffer/builder after loop

One option is to use the delete method as follows:

StringBuffer sb = new StringBuffer();
for (int n = 0; n < 10; n++) {
   sb.append("a");

   // This will clear the buffer
   sb.delete(0, sb.length());
}

Another option (bit cleaner) uses setLength(int len):

sb.setLength(0);

See Javadoc for more info:

How to use router.navigateByUrl and router.navigate in Angular

router.navigate vs router.navigateByUrl

router.navigate is just a convenience method that wraps router.navigateByUrl, it boils down to:

navigate(commands: any[], extras) {
    return router.navigateByUrl(router.createUrlTree(commands, extras), extras);
}

As mentioned in other answers router.navigateByUrl will only accept absolute URLs:

// This will work
router.navigateByUrl("http://localhost/team/33/user/11")
// This WON'T work even though relativeTo parameter is in the signature
router.navigateByUrl("../22", {relativeTo: route})

All the relative calculations are done by router.createUrlTree and router.navigate. Array syntax is used to treat every array element as a URL modifying "command". E.g. ".." - go up, "path" - go down, {expand: true} - add query param, etc.. You can use it like this:

// create /team/33/user/11
router.navigate(['/team', 33, 'user', 11]);

// assuming the current url is `/team/33/user/11` and the route points to `user/11`

// navigate to /team/33/user/11/details
router.navigate(['details'], {relativeTo: route});

// navigate to /team/33/user/22
router.navigate(['../22'], {relativeTo: route});

// navigate to /team/44/user/22
router.navigate(['../../team/44/user/22'], {relativeTo: route});

That {relativeTo: route} parameter is important as that's what router will use as the root for relative operations.

Get it through your component's constructor:

  // In my-awesome.component.ts:

  constructor(private route: ActivatedRoute, private router: Router) {}
  
  // Example call
  onNavigateClick() {
    // Navigates to a parent component
    this.router.navigate([..], { relativeTo: this.route })
  }

routerLink directive

Nicest thing about this directive is that it will retrieve the ActivatedRoute for you. Under the hood it's using already familiar:

router.navigateByUrl(router.createUrlTree(commands, { relativeTo: route }), { relativeTo: route });

Following variants will produce identical result:

[routerLink]="['../..']"

// if the string parameter is passed it will be wrapped into an array
routerLink="../.."

What is the best way to get all the divisors of a number?

For me this works fine and is also clean (Python 3)

def divisors(number):
    n = 1
    while(n<number):
        if(number%n==0):
            print(n)
        else:
            pass
        n += 1
    print(number)

Not very fast but returns divisors line by line as you wanted, also you can do list.append(n) and list.append(number) if you really want to

How to remove entry from $PATH on mac

  1. echo $PATH and copy it's value
  2. export PATH=""
  3. export PATH="/path/you/want/to/keep"

No Main class found in NetBeans

You need to rename your main class to Main, it cannot be anything else.

It does not matter how many files as packages and classes you create, you must name your main class Main.

That's all.

Textfield with only bottom border

Probably a duplicate of this post: A customized input text box in html/html5

_x000D_
_x000D_
input {_x000D_
  border: 0;_x000D_
  outline: 0;_x000D_
  background: transparent;_x000D_
  border-bottom: 1px solid black;_x000D_
}
_x000D_
<input></input>
_x000D_
_x000D_
_x000D_

ASP.NET MVC5/IIS Express unable to debug - Code Not Running

Resolution fix: For me, the problem was related to active chrome sessions. I closed all of my chrome browser sessions and then tried building to chrome again. I am using Visual Studio Professional 2017 version 15.3.2. The VS application I was running into build errors with was a WebAPI project. When trying to click the green play button, I was getting dialog error stating "Unable to start the program 'http://localhost:18980/'. An operation is not legal in the current state. Hopefully this post helps someone.

WCF gives an unsecured or incorrectly secured fault error

Try changing your security mode to "transport".

You have a mismatch between the security tag and the transport tag.

How do I convert a single character into it's hex ascii value in python

To use the hex encoding in Python 3, use

>>> import codecs
>>> codecs.encode(b"c", "hex")
b'63'

In legacy Python, there are several other ways of doing this:

>>> hex(ord("c"))
'0x63'
>>> format(ord("c"), "x")
'63'
>>> "c".encode("hex")
'63'

Matrix multiplication in OpenCV

You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.

Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple * operator:

C = A * B

Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul() function:

output = A.mul(B);

no overload for matches delegate 'system.eventhandler'

Yes there is a problem with Click event handler (klik) - First argument must be an object type and second must be EventArgs.

public void klik(object sender, EventArgs e) {
  //
}

If you want to paint on a form or control then use CreateGraphics method.

public void klik(object sender, EventArgs e) {
    Bitmap c = this.DrawMandel();
    Graphics gr = CreateGraphics();  // Graphics gr=(sender as Button).CreateGraphics();
    gr.DrawImage(b, 150, 200);
}

How to make g++ search for header files in a specific directory?

A/code.cpp

#include <B/file.hpp>

A/a/code2.cpp

#include <B/file.hpp>

Compile using:

g++ -I /your/source/root /your/source/root/A/code.cpp
g++ -I /your/source/root /your/source/root/A/a/code2.cpp

Edit:

You can use environment variables to change the path g++ looks for header files. From man page:

Some additional environments variables affect the behavior of the preprocessor.

   CPATH
   C_INCLUDE_PATH
   CPLUS_INCLUDE_PATH
   OBJC_INCLUDE_PATH

Each variable's value is a list of directories separated by a special character, much like PATH, in which to look for header files. The special character, "PATH_SEPARATOR", is target-dependent and determined at GCC build time. For Microsoft Windows-based targets it is a semicolon, and for almost all other targets it is a colon.

CPATH specifies a list of directories to be searched as if specified with -I, but after any paths given with -I options on the command line. This environment variable is used regardless of which language is being preprocessed.

The remaining environment variables apply only when preprocessing the particular language indicated. Each specifies a list of directories to be searched as if specified with -isystem, but after any paths given with -isystem options on the command line.

In all these variables, an empty element instructs the compiler to search its current working directory. Empty elements can appear at the beginning or end of a path. For instance, if the value of CPATH is ":/special/include", that has the same effect as -I. -I/special/include.

There are many ways you can change an environment variable. On bash prompt you can do this:

$ export CPATH=/your/source/root
$ g++ /your/source/root/A/code.cpp
$ g++ /your/source/root/A/a/code2.cpp

You can of course add this in your Makefile etc.

How to convert URL parameters to a JavaScript object?

This is the simple version, obviously you'll want to add some error checking:

var obj = {};
var pairs = queryString.split('&');
for(i in pairs){
    var split = pairs[i].split('=');
    obj[decodeURIComponent(split[0])] = decodeURIComponent(split[1]);
}

Run exe file with parameters in a batch file

This should work:

start "" "c:\program files\php\php.exe" D:\mydocs\mp\index.php param1 param2

The start command interprets the first argument as a window title if it contains spaces. In this case, that means start considers your whole argument a title and sees no command. Passing "" (an empty title) as the first argument to start fixes the problem.

How do you get the length of a string?

HTML

<div class="selector">Text mates</div>

SCRIPT

alert(jQuery('.selector').text().length);

RESULT

10

How do I extract text that lies between parentheses (round brackets)?

input.Remove(input.IndexOf(')')).Substring(input.IndexOf('(') + 1);

Why powershell does not run Angular commands?

open windows powershell, run as administrater and SetExecution policy as Unrestricted then it will work.

Position Absolute + Scrolling

So gaiour is right, but if you're looking for a full height item that doesn't scroll with the content, but is actually the height of the container, here's the fix. Have a parent with a height that causes overflow, a content container that has a 100% height and overflow: scroll, and a sibling then can be positioned according to the parent size, not the scroll element size. Here is the fiddle: http://jsfiddle.net/M5cTN/196/

and the relevant code:

html:

<div class="container">
  <div class="inner">
    Lorem ipsum ...
  </div>
  <div class="full-height"></div>
</div>

css:

.container{
  height: 256px;
  position: relative;
}
.inner{
  height: 100%;
  overflow: scroll;
}
.full-height{
  position: absolute;
  left: 0;
  width: 20%;
  top: 0;
  height: 100%;
}

Npm Error - No matching version found for

Probably not the case of everybody but I had the same problem. I was using the last, in my case, the error was because I was using jfrog manage from the company where I am working.

 npm config list

The result was

; cli configs
metrics-registry = "https://COMPANYNAME.jfrog.io/COMPANYNAM/api/npm/npm/"
scope = ""
user-agent = "npm/6.3.0 node/v8.11.2 win32 x64"

; userconfig C:\Users\USER\.npmrc
always-auth = true
email = "XXXXXXXXX"
registry = "https://COMPANYNAME.jfrog.io/COMPANYNAME/api/npm/npm/"

; builtin config undefined
prefix = "C:\\Users\\XXXXX\\AppData\\Roaming\\npm"

; node bin location = C:\Program Files\nodejs\node.exe
; cwd = C:\WINDOWS\system32
; HOME = C:\Users\XXXXXX
; "npm config ls -l" to show all defaults.

I solve the problem by using the global metrics.

Change image in HTML page every few seconds

Change setTimeout("changeImage()", 30000); to setInterval("changeImage()", 30000); and remove var timerid = setInterval(changeImage, 30000);.

Uses of Action delegate in C#

You can use actions for short event handlers:

btnSubmit.Click += (sender, e) => MessageBox.Show("You clicked save!");

React Native absolute positioning horizontal centre

<View style={{...StyleSheet.absoluteFillObject, justifyContent: 'center', alignItems: 'center'}}>
  <Text>CENTERD TEXT</Text>
</View>

And add this

import {StyleSheet} from 'react-native';

How to fetch FetchType.LAZY associations with JPA and Hibernate in a Spring Controller

You have some options

  • Write a method on repository that return a initialized entity as R.J suggested.

More work, best performance.

  • Use OpenEntityManagerInViewFilter to keep session open for the entire request.

Less work, usually acceptable in web enviroments.

  • Use a helper class to initialize entities when required.

Less work, useful when OEMIV is not at option, for example in a Swing application, but may be useful too on repository implementations to initialize any entity in one shot.

For the last option, I wrote a utility class, JpaUtils to initilize entities at some deph.

For example:

@Transactional
public class RepositoryHelper {

    @PersistenceContext
    private EntityManager em;

    public void intialize(Object entity, int depth) {
        JpaUtils.initialize(em, entity, depth);
    }
}

Java regex email

Regex for Facebook-like validation:

public static final String REGEX_EMAIL_VALIDATION = "^[\\w-\\+]+(\\.[\\w]+)*@[\\w-]+(\\.[\\w]+)*(\\.[a-zA-Z]{2,})$";

Dto for Unit tests(with Lombok):

@Data
@Accessors(chain = true)
@FieldDefaults(level = AccessLevel.PRIVATE)
public class UserCreateDto {

    @NotNull
    @Pattern(regexp = REGEX_EMAIL_VALIDATION)
    @Size(min = 1, max = 254)
    String email;
}

Valid/invalid emails below with Unit tests:

public class UserCreateValidationDtoTest {

private static final String[] VALID_EMAILS = new String[]{"[email protected]", "[email protected]",
        "[email protected]", "[email protected]", "[email protected]",
        "[email protected]", "[email protected]", "[email protected]",
        "[email protected]", "[email protected]", "[email protected]"};
private static final String[] INVALID_EMAILS = new String[]{"[email protected]", "email@111",
        "email", "[email protected]", "email123@gmail.", "[email protected]", "[email protected]",
        "[email protected]", "email()*@gmAil.com", "eEmail()*@gmail.com", "email@%*.com", "[email protected]",
        "[email protected]", "email@[email protected]", "[email protected]."};
private Validator validator;

@Before
public void setUp() throws Exception {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    validator = factory.getValidator();
}

@Test
public void emailValidationShouldBeValid() throws Exception {
    Arrays.stream(VALID_EMAILS)
            .forEach(email -> {
                        Set<ConstraintViolation<UserCreateDto>> violations = validateEmail(
                                new UserCreateDto().setEmail(email));
                        System.out.println("Email: " + email + ", violations: " + violations);
                        Assert.assertTrue(violations.isEmpty());
                    }
            );
}

@Test
public void emailValidationShouldBeNotValid() throws Exception {
    Arrays.stream(INVALID_EMAILS)
            .forEach(email -> {
                        Set<ConstraintViolation<UserCreateDto>> violations = validateEmail(
                                new UserCreateDto().setEmail(email));
                        System.out.println("Email: " + email + ", violations: " + violations);
                        Assert.assertTrue(!violations.isEmpty());
                    }
            );
}


private Set<ConstraintViolation<UserCreateDto>> validateEmail(UserCreateDto user) {
    String emailFieldName = "email";
    return validator.validateProperty(user, emailFieldName);
}

}

What does "Git push non-fast-forward updates were rejected" mean?

GitHub has a nice section called "Dealing with “non-fast-forward” errors"

This error can be a bit overwhelming at first, do not fear.
Simply put, git cannot make the change on the remote without losing commits, so it refuses the push.
Usually this is caused by another user pushing to the same branch. You can remedy this by fetching and merging the remote branch, or using pull to perform both at once.

In other cases this error is a result of destructive changes made locally by using commands like git commit --amend or git rebase.
While you can override the remote by adding --force to the push command, you should only do so if you are absolutely certain this is what you want to do.
Force-pushes can cause issues for other users that have fetched the remote branch, and is considered bad practice. When in doubt, don’t force-push.


Git cannot make changes on the remote like a fast-forward merge, which a Visual Git Reference illustrates like:

alt text

This is not exactly your case, but helps to see what "fast-forward" is (where the HEAD of a branch is simply moved to a new more recent commit).


The "branch master->master (non-fast-forward) Already-up-to-date" is usually for local branches which don't track their remote counter-part.
See for instance this SO question "git pull says up-to-date but git push rejects non-fast forward".
Or the two branches are connected, but in disagreement with their respective history:
See "Never-ending GIT story - what am I doing wrong here?"

This means that your subversion branch and your remote git master branch do not agree on something.
Some change was pushed/committed to one that is not in the other.
Fire up gitk --all, and it should give you a clue as to what went wrong - look for "forks" in the history.

How do I parse a URL query parameters, in Javascript?

Today (2.5 years after this answer) you can safely use Array.forEach. As @ricosrealm suggests, decodeURIComponent was used in this function.

function getJsonFromUrl(url) {
  if(!url) url = location.search;
  var query = url.substr(1);
  var result = {};
  query.split("&").forEach(function(part) {
    var item = part.split("=");
    result[item[0]] = decodeURIComponent(item[1]);
  });
  return result;
}

actually it's not that simple, see the peer-review in the comments, especially:

  • hash based routing (@cmfolio)
  • array parameters (@user2368055)
  • proper use of decodeURIComponent and non-encoded = (@AndrewF)
  • non-encoded + (added by me)

For further details, see MDN article and RFC 3986.

Maybe this should go to codereview SE, but here is safer and regexp-free code:

function getJsonFromUrl(url) {
  if(!url) url = location.href;
  var question = url.indexOf("?");
  var hash = url.indexOf("#");
  if(hash==-1 && question==-1) return {};
  if(hash==-1) hash = url.length;
  var query = question==-1 || hash==question+1 ? url.substring(hash) : 
  url.substring(question+1,hash);
  var result = {};
  query.split("&").forEach(function(part) {
    if(!part) return;
    part = part.split("+").join(" "); // replace every + with space, regexp-free version
    var eq = part.indexOf("=");
    var key = eq>-1 ? part.substr(0,eq) : part;
    var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
    var from = key.indexOf("[");
    if(from==-1) result[decodeURIComponent(key)] = val;
    else {
      var to = key.indexOf("]",from);
      var index = decodeURIComponent(key.substring(from+1,to));
      key = decodeURIComponent(key.substring(0,from));
      if(!result[key]) result[key] = [];
      if(!index) result[key].push(val);
      else result[key][index] = val;
    }
  });
  return result;
}

This function can parse even URLs like

var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a",  "c",  "[x]":"b"]}

var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
  console.log(key,":",obj[key]);
}
/*
  0 : a a
  1 : c
  [x] : b
*/

Unable to add window -- token android.os.BinderProxy is not valid; is your activity running?

I faced exactly the same issue. Calling '(!isFinishing())' prevented the crash, but it could not display the 'alert' message.

Then I tried making calling function 'static', where alert is displayed. After that, no crash happened and message is also getting displayed.

For ex:

public static void connect_failure() {      
        Log.i(FW_UPD_APP, "Connect failed");

        new AlertDialog.Builder(MyActivity)
        .setTitle("Title")
        .setMessage("Message")
        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) { 
                  //do nothing
            }
         })
        .setIcon(R.drawable.the_image).show();      
    }

IE9 JavaScript error: SCRIPT5007: Unable to get value of the property 'ui': object is null or undefined

I was having same issue in IE9. I followed the above answer and I added the line:

<meta http-equiv="X-UA-Compatible" content="IE=8;FF=3;OtherUA=4" />

in my <head> and it worked.

How to update specific key's value in an associative array in PHP?

The best approach is using a lambda within "array_walk" native function to make the required changes:

    array_walk($data, function (&$value, $key) {
            if($key == 'transaction_date'){ 
                  $value = date('d/m/Y', $value); 
            }
    });

The value is updated in the array as it's passed with as a reference "&".

How to change credentials for SVN repository in Eclipse?

I was able unable to locate the svn.simple file, but was able to change credentials using the following three steps:

Checkout project from SVN

enter image description here

Select the repository you need to change the credentials on (note: you will not perform an checkout, but this will bring you to the screen to enter a username/password combination).

enter image description here

Finally, enter the new username and password credentials:

enter image description here

It's a bit confusing, because you begin the process of initializing a new project, but you're only resetting the repository credentials.

Default keystore file does not exist?

For Mac/Linux debug keystore, the Android docs have:

keytool -exportcert -list -v \
-alias androiddebugkey -keystore ~/.android/debug.keystore

But there is something that may not be obvious: If you put the backslash, make sure to do a shift + return in terminal after the backslash so that the second that starts with -alias is on a new line. Simply pasting as-is will not work.

Your terminal (if successful) will look something like this:

$ keytool -exportcert -list -v \
? -alias androiddebugkey -keystore ~/.android/debug.keystore
Enter keystore password: 

The default debug password is: android

Side note: In Android Studio you can manage signing in:

File > Project Structure > Modules - (Your App) > Signing

laravel the requested url was not found on this server

In httpd.conf file you need to remove #

#LoadModule rewrite_module modules/mod_rewrite.so

after removing # line will look like this:

LoadModule rewrite_module modules/mod_rewrite.so

And Apache restart

How to manually include external aar package using new Gradle Android Build System

In my case I have some depencies in my library and when I create an aar from it I failed, because of missed depencies, so my solution is to add all depencies from my lib with an arr file.

So my project level build.gradle looks so:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.2'
    }
}

allprojects {
    repositories {
        mavenCentral()
        //add it to be able to add depency to aar-files from libs folder in build.gradle(yoursAppModule)
        flatDir {
            dirs 'libs'
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

build.gradle(modile app) so:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.example.sampleapp"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    //your project depencies
    ...
    //add lib via aar-depency
    compile(name: 'aarLibFileNameHere', ext: 'aar')
    //add all its internal depencies, as arr don't have it
    ...
}

and library build.gradle:

apply plugin: 'com.android.library'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    //here goes library projects dependencies, which you must include
    //in yours build.gradle(modile app) too
    ...
}

Secure Web Services: REST over HTTPS vs SOAP + WS-Security. Which is better?

If your RESTFul call sends XML Messages back and forth embedded in the Html Body of the HTTP request, you should be able to have all the benefits of WS-Security such as XML encryption, Cerificates, etc in your XML messages while using whatever security features are available from http such as SSL/TLS encryption.

Concatenation of strings in Lua

Concatenation:

The string concatenation operator in Lua is denoted by two dots ('..'). If both operands are strings or numbers, then they are converted to strings according to the rules mentioned in §2.2.1. Otherwise, the "concat" metamethod is called (see §2.8).

from: http://www.lua.org/manual/5.1/manual.html#2.5.4

X11/Xlib.h not found in Ubuntu

Andrew White's answer is sufficient to get you moving. Here's a step-by-step for beginners.

A simple get started:

Create test.cpp: (This will be built and run to verify you got things set up right.)

#include <X11/Xlib.h>
#include <unistd.h>


main()
{
  // Open a display.
  Display *d = XOpenDisplay(0);

  if ( d )
    {
      // Create the window
      Window w = XCreateWindow(d, DefaultRootWindow(d), 0, 0, 200,
                   100, 0, CopyFromParent, CopyFromParent,
                   CopyFromParent, 0, 0);

      // Show the window
      XMapWindow(d, w);
      XFlush(d);

      // Sleep long enough to see the window.
      sleep(10);
    }
  return 0;
}

(Source: LinuxGazette)

Try: g++ test.cpp -lX11 If it builds to a.out, try running it. If you see a simple window drawn, you have the necessary libraries, and some other root problem is afoot.

If your response is:

    test.cpp:1:22: fatal error: X11/Xlib.h: No such file or directory
    compilation terminated.

you need to install X11 development libraries. sudo apt-get install libx11-dev

Retry g++ test.cpp -lX11

If it works, you're golden.

Tested using a fresh install of libX11-dev_2%3a1.5.0-1_i386.deb

How to import/include a CSS file using PHP code and not HTML code?

Just put

echo "<link rel='stylesheet' type='text/css' href='CSS/main.css'>";

inside the php code, then your style is incuded. Worked for me, I tried.

How to use not contains() in xpath?

XPath queries are case sensitive. Having looked at your example (which, by the way, is awesome, nobody seems to provide examples anymore!), I can get the result you want just by changing "business", to "Business"

//production[not(contains(category,'Business'))]

I have tested this by opening the XML file in Chrome, and using the Developer tools to execute that XPath queries, and it gave me just the Film category back.

How to check if the user can go back in browser history or not

There is another way to check - check the referrer. The first page usually will have an empty referrer...

if (document.referrer == "") {
    window.close()
} else {
    history.back()
}

How do I add the Java API documentation to Eclipse?

Choose one class you want to view its documentation and press Ctrl+click over it, the Javadoc page will inform you that there is no Javadoc file attached and bellow will see a button named "Attach File". Press that button and browse to the directory where JDK is installed, normally for Win is C:\Program files\Java\jdk_xxx and inside this folder there is a src.zip file - sleect it and press OK and all is done - you already have Javadoc attached.

Javascript "Not a Constructor" Exception while creating objects

In my case I was using the prototype name as the object name. For e.g.

function proto1()
{}

var proto1 = new proto1();

It was a silly mistake but might be of help to someone like me ;)

APK signing error : Failed to read key from keystore

Most likely that your key alias does not exist for your keystore file.

This answer should fix your signing issue ;)

How to change the author and committer name and e-mail of multiple commits in Git?

This answer uses git-filter-branch, for which the docs now give this warning:

git filter-branch has a plethora of pitfalls that can produce non-obvious manglings of the intended history rewrite (and can leave you with little time to investigate such problems since it has such abysmal performance). These safety and performance issues cannot be backward compatibly fixed and as such, its use is not recommended. Please use an alternative history filtering tool such as git filter-repo. If you still need to use git filter-branch, please carefully read SAFETY (and PERFORMANCE) to learn about the land mines of filter-branch, and then vigilantly avoid as many of the hazards listed there as reasonably possible.

Changing the author (or committer) would require re-writing all of the history. If you're okay with that and think it's worth it then you should check out git filter-branch. The man page includes several examples to get you started. Also note that you can use environment variables to change the name of the author, committer, dates, etc. -- see the "Environment Variables" section of the git man page.

Specifically, you can fix all the wrong author names and emails for all branches and tags with this command (source: GitHub help):

#!/bin/sh

git filter-branch --env-filter '
OLD_EMAIL="[email protected]"
CORRECT_NAME="Your Correct Name"
CORRECT_EMAIL="[email protected]"
if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
    export GIT_COMMITTER_NAME="$CORRECT_NAME"
    export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
    export GIT_AUTHOR_NAME="$CORRECT_NAME"
    export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags

Button button = findViewById(R.id.button) always resolves to null in Android Studio

This is because findViewById() searches in the activity_main layout, while the button is located in the fragment's layout fragment_main.

Move that piece of code in the onCreateView() method of the fragment:

//...

View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button)rootView.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        onButtonClick((Button) view);
    }
});

Notice that now you access it through rootView view:

Button buttonClick = (Button)rootView.findViewById(R.id.button);

otherwise you would get again NullPointerException.

What is the difference between sscanf or atoi to convert a string to an integer?

To @R.. I think it's not enough to check errno for error detection in strtol call.

long strtol (const char *String, char **EndPointer, int Base)

You'll also need to check EndPointer for errors.

Waiting till the async task finish its work

wait until this call is finish its executing

You will need to call AsyncTask.get() method for getting result back and make wait until doInBackground execution is not complete. but this will freeze Main UI thread if you not call get method inside a Thread.

To get result back in UI Thread start AsyncTask as :

String str_result= new RunInBackGround().execute().get();

What is the recommended way to make a numeric TextField in JavaFX?

Here is a simple class that handles some basic validations on TextField, using TextFormatter introduced in JavaFX 8u40

EDIT:

(Code added regarding Floern's comment)

import java.text.DecimalFormatSymbols;
import java.util.regex.Pattern;

import javafx.beans.NamedArg;
import javafx.scene.control.TextFormatter;
import javafx.scene.control.TextFormatter.Change;

public class TextFieldValidator {

    private static final String CURRENCY_SYMBOL   = DecimalFormatSymbols.getInstance().getCurrencySymbol();
    private static final char   DECIMAL_SEPARATOR = DecimalFormatSymbols.getInstance().getDecimalSeparator();

    private final Pattern       INPUT_PATTERN;

    public TextFieldValidator(@NamedArg("modus") ValidationModus modus, @NamedArg("countOf") int countOf) {
        this(modus.createPattern(countOf));
    }

    public TextFieldValidator(@NamedArg("regex") String regex) {
        this(Pattern.compile(regex));
    }

    public TextFieldValidator(Pattern inputPattern) {
        INPUT_PATTERN = inputPattern;
    }

    public static TextFieldValidator maxFractionDigits(int countOf) {
        return new TextFieldValidator(maxFractionPattern(countOf));
    }

    public static TextFieldValidator maxIntegers(int countOf) {
        return new TextFieldValidator(maxIntegerPattern(countOf));
    }

    public static TextFieldValidator integersOnly() {
        return new TextFieldValidator(integersOnlyPattern());
    }

    public TextFormatter<Object> getFormatter() {
        return new TextFormatter<>(this::validateChange);
    }

    private Change validateChange(Change c) {
        if (validate(c.getControlNewText())) {
            return c;
        }
        return null;
    }

    public boolean validate(String input) {
        return INPUT_PATTERN.matcher(input).matches();
    }

    private static Pattern maxFractionPattern(int countOf) {
        return Pattern.compile("\\d*(\\" + DECIMAL_SEPARATOR + "\\d{0," + countOf + "})?");
    }

    private static Pattern maxCurrencyFractionPattern(int countOf) {
        return Pattern.compile("^\\" + CURRENCY_SYMBOL + "?\\s?\\d*(\\" + DECIMAL_SEPARATOR + "\\d{0," + countOf + "})?\\s?\\" +
                CURRENCY_SYMBOL + "?");
    }

    private static Pattern maxIntegerPattern(int countOf) {
        return Pattern.compile("\\d{0," + countOf + "}");
    }

    private static Pattern integersOnlyPattern() {
        return Pattern.compile("\\d*");
    }

    public enum ValidationModus {

        MAX_CURRENCY_FRACTION_DIGITS {
            @Override
            public Pattern createPattern(int countOf) {
                return maxCurrencyFractionPattern(countOf);
            }
        },

        MAX_FRACTION_DIGITS {
            @Override
            public Pattern createPattern(int countOf) {
                return maxFractionPattern(countOf);
            }
        },
        MAX_INTEGERS {
            @Override
            public Pattern createPattern(int countOf) {
                return maxIntegerPattern(countOf);
            }
        },

        INTEGERS_ONLY {
            @Override
            public Pattern createPattern(int countOf) {
                return integersOnlyPattern();
            }
        };

        public abstract Pattern createPattern(int countOf);
    }

}

You can use it like this:

textField.setTextFormatter(new TextFieldValidator(ValidationModus.INTEGERS_ONLY).getFormatter());

or you can instantiate it in a fxml file, and apply it to a customTextField with the according properties.

app.fxml:

<fx:define>
    <TextFieldValidator fx:id="validator" modus="INTEGERS_ONLY"/>
</fx:define>

CustomTextField.class:

public class CustomTextField {

private TextField textField;

public CustomTextField(@NamedArg("validator") TextFieldValidator validator) {
        this();
        textField.setTextFormatter(validator.getFormatter());
    }
}

Code on github

Script parameters in Bash

Use the variables "$1", "$2", "$3" and so on to access arguments. To access all of them you can use "$@", or to get the count of arguments $# (might be useful to check for too few or too many arguments).

Get Bitmap attached to ImageView

Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();

Simplest way to do grouped barplot

There are several ways to do plots in R; lattice is one of them, and always a reasonable solution, +1 to @agstudy. If you want to do this in base graphics, you could try the following:

Reasonstats <- read.table(text="Category         Reason  Species
                                 Decline        Genuine       24
                                Improved        Genuine       16
                                Improved  Misclassified       85
                                 Decline  Misclassified       41
                                 Decline      Taxonomic        2
                                Improved      Taxonomic        7
                                 Decline        Unclear       41
                                Improved        Unclear      117", header=T)

ReasonstatsDec <- Reasonstats[which(Reasonstats$Category=="Decline"),]
ReasonstatsImp <- Reasonstats[which(Reasonstats$Category=="Improved"),]
Reasonstats3   <- cbind(ReasonstatsImp[,3], ReasonstatsDec[,3])
colnames(Reasonstats3) <- c("Improved", "Decline")
rownames(Reasonstats3) <- ReasonstatsImp$Reason

windows()
  barplot(t(Reasonstats3), beside=TRUE, ylab="number of species", 
          cex.names=0.8, las=2, ylim=c(0,120), col=c("darkblue","red"))
  box(bty="l")

enter image description here

Here's what I did: I created a matrix with two columns (because your data were in columns) where the columns were the species counts for Decline and for Improved. Then I made those categories the column names. I also made the Reasons the row names. The barplot() function can operate over this matrix, but wants the data in rows rather than columns, so I fed it a transposed version of the matrix. Lastly, I deleted some of your arguments to your barplot() function call that were no longer needed. In other words, the problem was that your data weren't set up the way barplot() wants for your intended output.

Java swing application, close one window and open another when button is clicked

        final File open = new File("PicDic.exe");
        if (open.exists() == true) {
            if (Desktop.isDesktopSupported()) {
                javax.swing.SwingUtilities.invokeLater(new Runnable() {

                    public void run() {
                        try {
                            Desktop.getDesktop().open(open);
                        } catch (IOException ex) {
                            return;
                        }
                    }
                });

                javax.swing.SwingUtilities.invokeLater(new Runnable() {

                    public void run() {
                        //DocumentEditorView.this.getFrame().dispose();
                        System.exit(0);
                    }

                });
            } else {
                JOptionPane.showMessageDialog(this.getFrame(), "Desktop is not support to open editor\n You should try manualy");
            }
        } else {
            JOptionPane.showMessageDialog(this.getFrame(), "PicDic.exe is not found");
        }

//you can start another apps by using it and can slit your whole project in many apps. it will work lot

PDO closing connection

Its more than just setting the connection to null. That may be what the documentation says, but that is not the truth for mysql. The connection will stay around for a bit longer (Ive heard 60s, but never tested it)

If you want to here the full explanation see this comment on the connections https://www.php.net/manual/en/pdo.connections.php#114822

To force the close the connection you have to do something like

$this->connection = new PDO();
$this->connection->query('KILL CONNECTION_ID()');
$this->connection = null;

How to unpackage and repackage a WAR file

you can update your war from the command line using java commands as mentioned here:

jar -uvf test.war yourclassesdir 

Other useful commands:

Command to unzip/explode the war file

jar -xvf test.war

Command to create the war file

jar -cvf test.war yourclassesdir 

Eg:

jar -cvf test.war *
jar -cvf test.war WEB-INF META-INF