Programs & Examples On #Jespa

Jespa is a Java software library that provides advanced integration between Microsoft Active Directory and Java applications.

How to remove item from a JavaScript object

_x000D_
_x000D_
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

this deletes test.blue

Bad operand type for unary +: 'str'

The code works for me. (after adding missing except clause / import statements)

Did you put \ in the original code?

urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/' \
              + stock + '/chartdata;type=quote;range=5d/csv'

If you omit it, it could be a cause of the exception:

>>> stock = 'GOOG'
>>> urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'
>>> + stock + '/chartdata;type=quote;range=5d/csv'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'str'

BTW, string(e) should be str(e).

super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object

Also, if you can't change class B, you can fix the error by using multiple inheritance.

class B:
    def meth(self, arg):
        print arg

class C(B, object):
    def meth(self, arg):
        super(C, self).meth(arg)

print C().meth(1)

Clearing state es6 React

In most cases you dont need a deep copy, rarely initial state is object of objects, so using spread operator which babel transpiles to the object.assign should be fine.

So, inside constructor you would have:

    class MyComponent extends Component {
        constructor(props) {
            super(props)
            this.state = {
                key: value,
                key2: value
            }
            this.initialState = { ...this.state } 
        }
    }

From there you can use

this.setState(this.initialState);

to reset. But if for some reason your initial state is more complex object, use some library.

aspx page to redirect to a new page

<%@ Page Language="C#" %>
<script runat="server">
  protected override void OnLoad(EventArgs e)
  {
      Response.Redirect("new.aspx");
  }
</script>

Converting Date and Time To Unix Timestamp

If you just need a good date-parsing function, I would look at date.js. It will take just about any date string you can throw at it, and return you a JavaScript Date object.

Once you have a Date object, you can call its getTime() method, which will give you milliseconds since January 1, 1970. Just divide that result by 1000 to get the unix timestamp value.

In code, just include date.js, then:

var unixtime = Date.parse("24-Nov-2009 17:57:35").getTime()/1000

Disable automatic sorting on the first column when using jQuery DataTables

In the newer version of datatables (version 1.10.7) it seems things have changed. The way to prevent DataTables from automatically sorting by the first column is to set the order option to an empty array.

You just need to add the following parameter to the DataTables options:

"order": [] 

Set up your DataTable as follows in order to override the default setting:

$('#example').dataTable( {
    "order": [],
    // Your other options here...
} );

That will override the default setting of "order": [[ 0, 'asc' ]].

You can find more details regarding the order option here: https://datatables.net/reference/option/order

How to run mvim (MacVim) from Terminal?

In addition, if you want to use MacVim (or GVim) as $VISUAL or $EDITOR, you should be aware that by default MacVim will fork a new process from the parent, resulting in the MacVim return value not reaching the parent process. This may confuse other applications, but Git seems to check the status of a temporary commit message file, which bypasses this limitation. In general, it is a good practice to export VISUAL='mvim -f' to ensure MacVim will not fork a new process when called, which should give you what you want when using it with your shell environment.

How can I generate UUID in C#

I don't know about methods; however, the type to GUID can be done via:

Guid iid = System.Runtime.InteropServices.Marshal.GenerateGuidForType(typeof(IFoo));

http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.generateguidfortype.aspx

Mongoose and multiple database in single node.js project

Pretty late but this might help someone. The current answers assumes you are using the same file for your connections and models.

In real life, there is a high chance that you are splitting your models into different files. You can use something like this in your main file:

mongoose.connect('mongodb://localhost/default');

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
  console.log('connected');
});

which is just how it is described in the docs. And then in your model files, do something like the following:

import mongoose, { Schema } from 'mongoose';

const userInfoSchema = new Schema({
  createdAt: {
    type: Date,
    required: true,
    default: new Date(),
  },
  // ...other fields
});

const myDB = mongoose.connection.useDb('myDB');

const UserInfo = myDB.model('userInfo', userInfoSchema);

export default UserInfo;

Where myDB is your database name.

What is the difference between a stored procedure and a view?

A view is a simple way to save a complex SELECT in the database.

A store procedure is used when simple SQL just isn't enough. Store procedures contain variables, loops and calls to other stored procedures. It's a programming language, not a query language.

  1. Views are static. Think of them as new tables with a certain layout and the data in them is created on the fly using the query you created it with. As with any SQL table, you can sort and filter it with WHERE, GROUP BY and ORDER BY.

  2. The depends on what you do.

  3. The depends on the database. Simple views just run the query and filter the result. But databases like Oracle allow to create a "materialized" view which is basically a table which is updated automatically when the underlying data of the view changes.

    A materialized view allows you to create indexes on the columns of the view (especially on the computed columns which don't exist anywhere in the database).

  4. I don't understand what you're talking about.

In jQuery how can I set "top,left" properties of an element with position values relative to the parent and not the document?

I found that if the value passed is a string type, it must be followed by 'px' (i.e. 90px), where if the value is an integer, it will append the px automatically. the width and height properties are more forgiving (either type works).

var x = "90";
var y = "120"
$(selector).css( { left: x, top: y } )        //doesn't work
$(selector).css( { left: x + "px", top: y + "px" } )        //does work

x = 90;
y = 120;
$(selector).css( { left: x, top: y } )        //does work

Unable to connect to SQL Express "Error: 26-Error Locating Server/Instance Specified)

I found this url to be very useful: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/2cdcab2e-ea49-4fd5-b2b8-13824ab4619b/help-server-not-listening-on-1433

In particular, my problem was that I did not enable the TCP/IP in Sql Server Configuration Manager->SQL Server Network Configuration->Protocols for SQLEXPRESS.

Once you open it, you have to go to the IP Addresses tab and for me, changing IPAll to TCP port 1433 and deleting the TCP Dynamic Ports value worked.

Follow the other steps to make sure 1433 is listening (Use netstat -an to make sure 0.0.0.0:1433 is LISTENING.), and that you can telnet to the port from the client machine.

Finally, I second the suggestion to remove the \SQLEXPRESS from the connection.

EDIT: I should note I am using SQL Server 2014 Express.

General error: 1364 Field 'user_id' doesn't have a default value

There are two solutions for this issue.

First, is to create fields with default values set in datatable. It could be empty string, which is fine for MySQL server running in strict mode.

Second, if you started to get this error just recently, after MySQL/MariaDB upgrade, like I did, and in case you already have large project with a lot to fix, all you need to do is to edit MySQL/MariaDB configuration file (for example /etc/my.cnf) and disable strict mode for tables:

[mysqld]
sql_mode=NO_ENGINE_SUBSTITUTION

This error started to happen quite recently, due to new strict mode enabled by default. Removing STRICT_TRANS_TABLES from sql_mode configuration key, makes it work as before.

How can I strip first and last double quotes?

Below function will strip the empty spces and return the strings without quotes. If there are no quotes then it will return same string(stripped)

def removeQuote(str):
str = str.strip()
if re.search("^[\'\"].*[\'\"]$",str):
    str = str[1:-1]
    print("Removed Quotes",str)
else:
    print("Same String",str)
return str

How to use workbook.saveas with automatic Overwrite

To split the difference of opinion

I prefer:

   xls.DisplayAlerts = False    
   wb.SaveAs fullFilePath, AccessMode:=xlExclusive, ConflictResolution:=xlLocalSessionChanges
   xls.DisplayAlerts = True

Set width to match constraints in ConstraintLayout

If you want TextView in the center of parent..
Your main layout is Constraint Layout

<androidx.appcompat.widget.AppCompatTextView
     android:layout_width="0dp"
     android:layout_height="wrap_content"
     android:text="@string/logout"
     app:layout_constraintLeft_toLeftOf="parent"
     app:layout_constraintRight_toRightOf="parent"
     android:gravity="center">
</androidx.appcompat.widget.AppCompatTextView>

How do I improve ASP.NET MVC application performance?

I did all the answers above and it just didn't solve my problem.

Finally, I solved my slow site loading problem with setting PrecompileBeforePublish in Publish Profile to true. If you want to use msbuild you can use this argument:

 /p:PrecompileBeforePublish=true

It really help a lot. Now my MVC ASP.NET loads 10 times faster.

AngularJs $http.post() does not send data

This has finally been addressed in angular 1.4 using $httpParamSerializerJQLike

See https://github.com/angular/angular.js/issues/6039

.controller('myCtrl', function($http, $httpParamSerializerJQLike) {
$http({
  method: 'POST',
  url: baseUrl,
  data: $httpParamSerializerJQLike({
    "user":{
      "email":"[email protected]",
      "password":"123456"
    }
  }),
  headers:
    'Content-Type': 'application/x-www-form-urlencoded'
})})

How can I remove a pytz timezone from a datetime object?

To remove a timezone (tzinfo) from a datetime object:

# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)

If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.

# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)

Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime object to insert into the database. The solution is to convert your datetime.datetime object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime objects where one is timezone aware and another is timezone naive.

##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################

arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

arrowDt = arrowObj.to("utc").datetime

# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)

# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()

# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3

# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True

How is Docker different from a virtual machine?

The docker documentation (and self-explanation) makes a distinction between "virtual machines" vs. "containers". They have the tendency to interpret and use things in a little bit uncommon ways. They can do that because it is up to them, what do they write in their documentation, and because the terminology for virtualization is not yet really exact.

Fact is what the Docker documentation understands on "containers", is paravirtualization (sometimes "OS-Level virtualization") in the reality, contrarily the hardware virtualization, which is docker not.

Docker is a low quality paravirtualisation solution. The container vs. VM distinction is invented by the docker development, to explain the serious disadvantages of their product.

The reason, why it became so popular, is that they "gave the fire to the ordinary people", i.e. it made possible the simple usage of typically server ( = Linux) environments / software products on Win10 workstations. This is also a reason for us to tolerate their little "nuance". But it does not mean that we should also believe it.

The situation is made yet more cloudy by the fact that docker on Windows hosts used an embedded Linux in HyperV, and its containers have run in that. Thus, docker on Windows uses a combined hardware and paravirtualization solution.

In short, Docker containers are low-quality (para)virtual machines with a huge advantage and a lot of disadvantages.

Angular CLI SASS options

Quoted from Officials github repo here -

To use one just install for example

npm install node-sass

and rename .css files in your project to .scss or .sass. They will be compiled automatically. The Angular2App's options argument has sassCompiler, lessCompiler, stylusCompiler and compassCompiler options that are passed directly to their respective CSS preprocessors.

See here

HTML - How to do a Confirmation popup to a Submit button and then send the request?

<script type='text/javascript'>

function foo() {


var user_choice = window.confirm('Would you like to continue?');


if(user_choice==true) {


window.location='your url';  // you can also use element.submit() if your input type='submit' 


} else {


return false;


}
}

</script>

<input type="button" onClick="foo()" value="save">

Long Press in JavaScript?

You can use taphold event of jQuery mobile API.

jQuery("a").on("taphold", function( event ) { ... } )

How do I concatenate strings?

I think that concat method and + should be mentioned here as well:

assert_eq!(
  ("My".to_owned() + " " + "string"),
  ["My", " ", "string"].concat()
);

and there is also concat! macro but only for literals:

let s = concat!("test", 10, 'b', true);
assert_eq!(s, "test10btrue");

Can I use git diff on untracked files?

For my interactive day-to-day gitting (where I diff the working tree against the HEAD all the time, and would like to have untracked files included in the diff), add -N/--intent-to-add is unusable, because it breaks git stash.

So here's my git diff replacement. It's not a particularly clean solution, but since I really only use it interactively, I'm OK with a hack:

d() {
    if test "$#" = 0; then
        (
            git diff --color
            git ls-files --others --exclude-standard |
                while read -r i; do git diff --color -- /dev/null "$i"; done
        ) | `git config --get core.pager`
    else
        git diff "$@"
    fi
}

Typing just d will include untracked files in the diff (which is what I care about in my workflow), and d args... will behave like regular git diff.

Notes:

  • We're using the fact here that git diff is really just individual diffs concatenated, so it's not possible to tell the d output from a "real diff" -- except for the fact that all untracked files get sorted last.
  • The only problem with this function is that the output is colorized even when redirected; but I can't be bothered to add logic for that.
  • I couldn't find any way to get untracked files included by just assembling a slick argument list for git diff. If someone figures out how to do this, or if maybe a feature gets added to git at some point in the future, please leave a note here!

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

Using angular-google-maps

$scope.bounds = new google.maps.LatLngBounds();
for (var i = $scope.markers.length - 1; i >= 0; i--) {
    $scope.bounds.extend(new google.maps.LatLng($scope.markers[i].coords.latitude, $scope.markers[i].coords.longitude));
};    
$scope.control.getGMap().fitBounds($scope.bounds);
$scope.control.getGMap().setCenter($scope.bounds.getCenter());

How to perform element-wise multiplication of two lists?

Use np.multiply(a,b):

import numpy as np
a = [1,2,3,4]
b = [2,3,4,5]
np.multiply(a,b)

Using CMake with GNU Make: How can I see the exact commands?

It is convenient to set the option in the CMakeLists.txt file as:

set(CMAKE_VERBOSE_MAKEFILE ON)

How to return a 200 HTTP Status Code from ASP.NET MVC 3 controller

In your controller you'd return an HttpStatusCodeResult like this...

[HttpPost]
public ActionResult SomeMethod(...your method parameters go here...)
{
   // todo: put your processing code here

   //If not using MVC5
   return new HttpStatusCodeResult(200);

   //If using MVC5
   return new HttpStatusCodeResult(HttpStatusCode.OK);  // OK = 200
}

How to set focus on an input field after rendering?

This is not longer the best answer. As of v0.13, this.refs may not available until AFTER componentDidMount() runs, in some odd cases.

Just add the autoFocus tag to your input field, as FakeRainBrigand showed above.

Why is my asynchronous function returning Promise { <pending> } instead of a value?

I know this question was asked 2 years ago, but I run into the same issue and the answer for the problem is since ES2017, that you can simply await the functions return value (as of now, only works in async functions), like:

let AuthUser = function(data) {
  return google.login(data.username, data.password).then(token => { return token } )
}

let userToken = await AuthUser(data)
console.log(userToken) // your data

Static variables in JavaScript

I have universal method:

  • create object like: stat_flags = {};
  • use it with adding fields on the fly: flags.popup_save_inited = true;
  • next time ask is there flag you need in the object and do your logic

Example:

class ACTGeneratedPages {
    constructor(table_data, html_table_id) {
        this.flags = {};//static flags for any processes

        //any your code here

    }

    call_popup(post_id) {

        let _this = this;
        document.getElementById('act-popup-template').style.display = 'block';

        if (!this.flags.popup_save_inited) {//second time listener will not be attached
            document.querySelector('.act-modal-save').addEventListener('click', function (e) {
                //saving data code here
                return false;
            });
        }

        this.flags.popup_save_inited = true;//set flag here
    }

}

Get JSON data from external URL and display it in a div as plain text

To display the Json data using Robin Hartman code. You need to add, the below line.

The code he gave gives you Object, object. this code retrieves the data in a better way.

result.innerText =JSON.stringify(data);

How do I clone a range of array elements to a new array?

string[] arr = { "Parrot" , "Snake" ,"Rabbit" , "Dog" , "cat" };

arr = arr.ToList().GetRange(0, arr.Length -1).ToArray();

Split data frame string column into multiple columns

5 years later adding the obligatory data.table solution

library(data.table) ## v 1.9.6+ 
setDT(before)[, paste0("type", 1:2) := tstrsplit(type, "_and_")]
before
#    attr          type type1 type2
# 1:    1   foo_and_bar   foo   bar
# 2:   30 foo_and_bar_2   foo bar_2
# 3:    4   foo_and_bar   foo   bar
# 4:    6 foo_and_bar_2   foo bar_2

We could also both make sure that the resulting columns will have correct types and improve performance by adding type.convert and fixed arguments (since "_and_" isn't really a regex)

setDT(before)[, paste0("type", 1:2) := tstrsplit(type, "_and_", type.convert = TRUE, fixed = TRUE)]

A good Sorted List for Java

You need no sorted list. You need no sorting at all.

I need to add/remove keys from the list when object is added / removed from database.

But not immediately, the removal can wait. Use an ArrayList containing the ID's all alive objects plus at most some bounded percentage of deleted objects. Use a separate HashSet to keep track of deleted objects.

private List<ID> mostlyAliveIds = new ArrayList<>();
private Set<ID> deletedIds = new HashSet<>();

I want to randomly select few dozens of element from the whole list.

ID selectOne(Random random) {
    checkState(deletedIds.size() < mostlyAliveIds.size());
    while (true) {
        int index = random.nextInt(mostlyAliveIds.size());
        ID id = mostlyAliveIds.get(index);
        if (!deletedIds.contains(ID)) return ID;
    }
}

Set<ID> selectSome(Random random, int count) {
    checkArgument(deletedIds.size() <= mostlyAliveIds.size() - count);
    Set<ID> result = new HashSet<>();
    while (result.size() < count) result.add(selectOne(random));
}

For maintaining the data, do something like

void insert(ID id) {
    if (!deletedIds.remove(id)) mostlyAliveIds.add(ID);
} 

void delete(ID id) {
    if (!deletedIds.add(id)) {
         throw new ImpossibleException("Deleting a deleted element);
    }
    if (deletedIds.size() > 0.1 * mostlyAliveIds.size()) {
        mostlyAliveIds.removeAll(deletedIds);
        deletedIds.clear();
    }
}

The only tricky part is the insert which has to check if an already deleted ID was resurrected.

The delete ensures that no more than 10% of elements in mostlyAliveIds are deleted IDs. When this happens, they get all removed in one sweep (I didn't check the JDK sources, but I hope, they do it right) and the show goes on.

With no more than 10% of dead IDs, the overhead of selectOne is no more than 10% on the average.

I'm pretty sure that it's faster than any sorting as the amortized complexity is O(n).

Send response to all clients except sender

For namespaces within rooms looping the list of clients in a room (similar to Nav's answer) is one of only two approaches I've found that will work. The other is to use exclude. E.G.

socket.on('message',function(data) {
    io.of( 'namespace' ).in( data.roomID ).except( socket.id ).emit('message',data);
}

No increment operator (++) in Ruby?

I don't think that notation is available because—unlike say PHP or C—everything in Ruby is an object.

Sure you could use $var=0; $var++ in PHP, but that's because it's a variable and not an object. Therefore, $var = new stdClass(); $var++ would probably throw an error.

I'm not a Ruby or RoR programmer, so I'm sure someone can verify the above or rectify it if it's inaccurate.

how to get the selected index of a drop down

If you are actually looking for the index number (and not the value) of the selected option then it would be

document.forms[0].elements["CCards"].selectedIndex 
/* You may need to change document.forms[0] to reference the correct form */

or using jQuery

$('select[name="CCards"]')[0].selectedIndex 

How to configure custom PYTHONPATH with VM and PyCharm?

In pycharm 5 follow this, https://www.jetbrains.com/pycharm/help/configuring-python-interpreter-for-a-project.html

1)Open the Settings dialog box, and click Project Interpreter page.
2)In the Projects pane, choose the desired project.
3)For the selected project, choose SDK from the list of available Python interpreters and virtual environments.

Can Windows Containers be hosted on linux?

No, you cannot run windows containers directly on Linux.

But you can run Linux on Windows.

Windows Server/10 comes packaged with base image of ubuntu OS (after september 2016 beta service pack). That is the reason you can run linux on windows and not other wise. Check out here. https://thenewstack.io/finally-linux-containers-really-will-run-windows-linuxkit/

You can change between OS containers Linux and windows by right clicking on the docker in tray menu.

enter image description here

enter image description here

How do I return to an older version of our code in Subversion?

Just use this line

svn update -r yourOldRevesion

You can know your current revision by using:

svn info

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

Simply use this to get date before 300 days, replace 300 with your days:

Date date = new Date(); // Or where ever you get it from
Date daysAgo = new DateTime(date).minusDays(300).toDate();

Here,

DateTime is org.joda.time.DateTime;

Date is java.util.Date

how to open Jupyter notebook in chrome on windows

I found an easier solution that may help beginners to coding.

go to

C:\Users\'-your user-'\AppData\Roaming\jupyter\runtime

and find a file named

nbserver-6176-open.html

then

Right-click > open with > Choose default program...

Here, what ever you choose would be saved on your Windows to open all HTML files; therefore when you run Jupyter notebook, it would open in the program you want.

What is the difference between exit(0) and exit(1) in C?

The difference is the value returned to the environment is 0 in the former case and 1 in the latter case:

$ ./prog_with_exit_0
$ echo $?
0
$

and

$ ./prog_with_exit_1
$ echo $?
1
$

Also note that the macros value EXIT_SUCCESS and EXIT_FAILURE used as an argument to exit function are implementation defined but are usually set to respectively 0 and a non-zero number. (POSIX requires EXIT_SUCCESS to be 0). So usually exit(0) means a success and exit(1) a failure.

An exit function call with an argument in main function is equivalent to the statement return with the same argument.

How to parse XML in Bash?

Command-line tools that can be called from shell scripts include:

  • 4xpath - command-line wrapper around Python's 4Suite package

  • XMLStarlet

  • xpath - command-line wrapper around Perl's XPath library

    sudo apt-get install libxml-xpath-perl
    
  • Xidel - Works with URLs as well as files. Also works with JSON

I also use xmllint and xsltproc with little XSL transform scripts to do XML processing from the command line or in shell scripts.

Bootstrap Carousel : Remove auto slide

You can do this 2 ways, via js or html (easist)

  1. Via js
$('.carousel').carousel({
  interval: false,
});

That will make the auto sliding stop because there no Milliseconds added and will never slider next.

  1. Via Html By adding data-interval="false" and removing data-ride="carousel"
<div id="carouselExampleCaptions" class="carousel slide" data-ride="carousel">

becomes:

<div id="carouselExampleCaptions" class="carousel slide" data-interval="false">

updated based on @webMan's comment

curl: (35) SSL connect error

curl 7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.19.1 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2

You are using a very old version of curl. My guess is that you run into the bug described 6 years ago. Fix is to update your curl.

Accessing a property in a parent Component

On Angular 6, I access parent properties by injecting the parent via constructor. Not the best solution but it works:

 constructor(@Optional() public parentComponentInjectionObject: ParentComponent){
    // And access like this:
    parentComponentInjectionObject.thePropertyYouWantToAccess;
}

OS detecting makefile

That's the job that GNU's automake/autoconf are designed to solve. You might want to investigate them.

Alternatively you can set environment variables on your different platforms and make you Makefile conditional against them.

Increase max execution time for php

Add these lines of code in your htaccess file. I hope it will solve your problem.

<IfModule mod_php5.c>
php_value max_execution_time 259200
</IfModule>

How to exit from Python without traceback?

I would do it this way:

import sys

def do_my_stuff():
    pass

if __name__ == "__main__":
    try:
        do_my_stuff()
    except SystemExit, e:
        print(e)

Use :hover to modify the css of another class?

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

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

[Edit]

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

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

Try using:

conda install python-graphviz

The graphviz executable sit on a different path from your conda directory, if you use pip install graphviz.

Add button to a layout programmatically

If you just have included a layout file at the beginning of onCreate() inside setContentView and want to get this layout to add new elements programmatically try this:

ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);

then you can create a new Button for example and just add it:

Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 
                                    LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);

How to get evaluated attributes inside a custom directive

For an attribute value that needs to be interpolated in a directive that is not using an isolated scope, e.g.,

<input my-directive value="{{1+1}}">

use Attributes' method $observe:

myApp.directive('myDirective', function () {
  return function (scope, element, attr) {
    attr.$observe('value', function(actual_value) {
      element.val("value = "+ actual_value);
    })
 }
});

From the directive page,

observing interpolated attributes: Use $observe to observe the value changes of attributes that contain interpolation (e.g. src="{{bar}}"). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined.

If the attribute value is just a constant, e.g.,

<input my-directive value="123">

you can use $eval if the value is a number or boolean, and you want the correct type:

return function (scope, element, attr) {
   var number = scope.$eval(attr.value);
   console.log(number, number + 1);
});

If the attribute value is a string constant, or you want the value to be string type in your directive, you can access it directly:

return function (scope, element, attr) {
   var str = attr.value;
   console.log(str, str + " more");
});

In your case, however, since you want to support interpolated values and constants, use $observe.

std::string to float or double

I had the same problem in Linux

double s2f(string str)
{
 istringstream buffer(str);
 double temp;
 buffer >> temp;
 return temp;
}

it works.

Nginx upstream prematurely closed connection while reading response header from upstream, for large requests

You can increase the timeout in node like so.

app.post('/slow/request', function(req, res){ req.connection.setTimeout(100000); //100 seconds ... }

generate random double numbers in c++

This should be performant, thread-safe and flexible enough for many uses:

#include <random>
#include <iostream>

template<typename Numeric, typename Generator = std::mt19937>
Numeric random(Numeric from, Numeric to)
{
    thread_local static Generator gen(std::random_device{}());

    using dist_type = typename std::conditional
    <
        std::is_integral<Numeric>::value
        , std::uniform_int_distribution<Numeric>
        , std::uniform_real_distribution<Numeric>
    >::type;

    thread_local static dist_type dist;

    return dist(gen, typename dist_type::param_type{from, to});
}

int main(int, char*[])
{
    for(auto i = 0U; i < 20; ++i)
        std::cout << random<double>(0.0, 0.3) << '\n';
}

Angular 5, HTML, boolean on checkbox is checked

Work with checkboxes using observables

You could even choose to use a behaviourSubject to utilize the power of observables so you can start a certain chain of reaction starting at the isChecked$ observable.

In your component.ts:

public isChecked$ = new BehaviorSubject(false);
toggleChecked() {
  this.isChecked$.next(!this.isChecked$.value)
}

In your template

<input type="checkbox" [checked]="isChecked$ | async" (change)="toggleChecked()">

Find and replace strings in vim on multiple lines

To answer this question:

:40,50s/foo/bar/g

replace foo with bar in these lines between the 40th line and the 50th line(inclusive), when execute this command you can currently in any line.

:50,40s/foo/bar/g

also works, vim will ask you for comfirm and then do the replacement for you as if you have input the first command.

:,50s/foo/bar/g

replace foo with bar in these lines between the line you are currently in and the 50th line(inclusive). (if you are in a line AFTER the 50th line vim will ask for confirm again)

To clearity the difference between vim and the vrapper plugin of Eclipse:

Note that in varpper

:,50s/foo/bar/g command will NOT work.

:50,40s/foo/bar/g will work without asking for comfirmation.

(For Vrapper Version 0.74.0 or older).

Eclipse error: "The import XXX cannot be resolved"

Add the jar files in class path instead of module path. Worked for me.

Using async/await for multiple tasks

Since the API you're calling is async, the Parallel.ForEach version doesn't make much sense. You shouldnt use .Wait in the WaitAll version since that would lose the parallelism Another alternative if the caller is async is using Task.WhenAll after doing Select and ToArray to generate the array of tasks. A second alternative is using Rx 2.0

What are the obj and bin folders (created by Visual Studio) used for?

The obj folder holds object, or intermediate, files, which are compiled binary files that haven't been linked yet. They're essentially fragments that will be combined to produce the final executable. The compiler generates one object file for each source file, and those files are placed into the obj folder.

The bin folder holds binary files, which are the actual executable code for your application or library.

Each of these folders are further subdivided into Debug and Release folders, which simply correspond to the project's build configurations. The two types of files discussed above are placed into the appropriate folder, depending on which type of build you perform. This makes it easy for you to determine which executables are built with debugging symbols, and which were built with optimizations enabled and ready for release.

Note that you can change where Visual Studio outputs your executable files during a compile in your project's Properties. You can also change the names and selected options for your build configurations.

Assigning variables with dynamic names in Java

This is not how you do things in Java. There are no dynamic variables in Java. Java variables have to be declared in the source code1.

Depending on what you are trying to achieve, you should use an array, a List or a Map; e.g.

int n[] = new int[3];
for (int i = 0; i < 3; i++) {
    n[i] = 5;
}

List<Integer> n = new ArrayList<Integer>();
for (int i = 1; i < 4; i++) {
    n.add(5);
}

Map<String, Integer> n = new HashMap<String, Integer>();
for (int i = 1; i < 4; i++) {
    n.put("n" + i, 5);
}

It is possible to use reflection to dynamically refer to variables that have been declared in the source code. However, this only works for variables that are class members (i.e. static and instance fields). It doesn't work for local variables. See @fyr's "quick and dirty" example.

However doing this kind of thing unnecessarily in Java is a bad idea. It is inefficient, the code is more complicated, and since you are relying on runtime checking it is more fragile. And this is not "variables with dynamic names". It is better described as dynamic access to variables with static names.


1 - That statement is slightly inaccurate. If you use BCEL or ASM, you can "declare" the variables in the bytecode file. But don't do it! That way lies madness!

When do you use POST and when do you use GET?

i dont see a problem using get though, i use it for simple things where it makes sense to keep things on the query string.

Using it to update state - like a GET of delete.php?id=5 to delete a page - is very risky. People found that out when Google's web accelerator started prefetching URLs on pages - it hit all the 'delete' links and wiped out peoples' data. Same thing can happen with search engine spiders.

How to force a script reload and re-execute?

I know that is to late, but I want to share my answer. What I did it's save de script's tags in a HTML file, locking up the scripts on my Index file in a div with an id, something like this.

<div id="ScriptsReload"><script src="js/script.js"></script></div>

and when I wanted to refresh I just used.

$("#ScriptsReload").load("html_with_scripts_tags.html", "", function(
    response,
    status,
    request
  ) {

  });

Maven: How do I activate a profile from command line?

Activation by system properties can be done as follows

<activation>
    <property>
        <name>foo</name>
        <value>bar</value>
    </property>
</activation>

And run the mvn build with -D to set system property

mvn clean install -Dfoo=bar

This method also helps select profiles in transitive dependency of project artifacts.

Algorithm to calculate the number of divisors of a given number

Dmitriy is right that you'll want the Sieve of Atkin to generate the prime list but I don't believe that takes care of the whole issue. Now that you have a list of primes you'll need to see how many of those primes act as a divisor (and how often).

Here's some python for the algo Look here and search for "Subject: math - need divisors algorithm". Just count the number of items in the list instead of returning them however.

Here's a Dr. Math that explains what exactly it is you need to do mathematically.

Essentially it boils down to if your number n is:
n = a^x * b^y * c^z
(where a, b, and c are n's prime divisors and x, y, and z are the number of times that divisor is repeated) then the total count for all of the divisors is:
(x + 1) * (y + 1) * (z + 1).

Edit: BTW, to find a,b,c,etc you'll want to do what amounts to a greedy algo if I'm understanding this correctly. Start with your largest prime divisor and multiply it by itself until a further multiplication would exceed the number n. Then move to the next lowest factor and times the previous prime ^ number of times it was multiplied by the current prime and keep multiplying by the prime until the next will exceed n... etc. Keep track of the number of times you multiply the divisors together and apply those numbers into the formula above.

Not 100% sure about my algo description but if that isn't it it's something similar .

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

I can't set "UTF-8 with BOM" in the corner button either, but I can change it from the menu bar.

"File"->"Save with encoding"->"UTF-8 with BOM"

Replace a character at a specific index in a string?

this will work

   String myName="domanokz";
   String p=myName.replace(myName.charAt(4),'x');
   System.out.println(p);

Output : domaxokz

ListView inside ScrollView is not scrolling on Android

You shouldn't put a ListView inside a ScrollView because the ListView class implements its own scrolling and it just doesn't receive gestures because they all are handled by the parent ScrollView. I strongly recommend you to simplify your layout somehow. For example you can add views you want to be scrolled to the ListView as headers or footers.

UPDATE:

Starting from API Level 21 (Lollipop) nested scroll containers are officially supported by Android SDK. There're a bunch of methods in View and ViewGroup classes which provide this functionality. To make nested scrolling work on the Lollipop you have to enable it for a child scroll view by adding android:nestedScrollingEnabled="true" to its XML declaration or by explicitly calling setNestedScrollingEnabled(true).

If you want to make nested scrolling work on pre-Lollipop devices, which you probably do, you have to use corresponding utility classes from the Support library. First you have to replace you ScrollView with NestedScrollView. The latter implements both NestedScrollingParent and NestedScrollingChild so it can be used as a parent or a child scroll container.

But ListView doesn't support nested scrolling, therefore you need to subclass it and implement NestedScrollingChild. Fortunately, the Support library provides NestedScrollingChildHelper class, so you just have to create an instance of this class and call its methods from the corresponding methods of your view class.

Define variable to use with IN operator (T-SQL)

As no one mentioned it before, starting from Sql Server 2016 you can also use json arrays and OPENJSON (Transact-SQL):

declare @filter nvarchar(max) = '[1,2]'

select *
from dbo.Test as t
where
    exists (select * from openjson(@filter) as tt where tt.[value] = t.id)

You can test it in sql fiddle demo

You can also cover more complicated cases with json easier - see Search list of values and range in SQL using WHERE IN clause with SQL variable?

How to get a vCard (.vcf file) into Android contacts from website

What i have also noticed is that you have to save the file as Unicode, UTF-8, no BOM in an Windows format with CRLF (Carriage Return, Line Feed). Because if you don't, the import will break. (Saying something about weird chars in the file)

Good luck :) Sid

How to check if directory exist using C++ and winAPI

If linking to the shell Lightweight API (shlwapi.dll) is ok for you, you can use the PathIsDirectory function

PHP Fatal error: Class 'PDO' not found

What is the full source of the file Mysql.php. Based on the output of the php info list, it sounds like you may be trying to reference a global class from within a namespace.

If the file Mysql.php has a statement "namespace " in it, use \PDO in place of PDO - this will tell PHP to look for a global class, rather than looking in the local namespace.

ORDER BY using Criteria API

You need to create an alias for the mother.kind. You do this like so.

Criteria c = session.createCriteria(Cat.class);
c.createAlias("mother.kind", "motherKind");
c.addOrder(Order.asc("motherKind.value"));
return c.list();

How can I check the system version of Android?

Build.Version is the place go to for this data. Here is a code snippet for how to format it.

public String getAndroidVersion() {
    String release = Build.VERSION.RELEASE;
    int sdkVersion = Build.VERSION.SDK_INT;
    return "Android SDK: " + sdkVersion + " (" + release +")";
}

Looks like this "Android SDK: 19 (4.4.4)"

How do I connect to my existing Git repository using Visual Studio Code?

Another option is to use the built-in Command Palette, which will walk you right through cloning a Git repository to a new directory.

From Using Version Control in VS Code:

You can clone a Git repository with the Git: Clone command in the Command Palette (Windows/Linux: Ctrl + Shift + P, Mac: Command + Shift + P). You will be asked for the URL of the remote repository and the parent directory under which to put the local repository.

At the bottom of Visual Studio Code you'll get status updates to the cloning. Once that's complete an information message will display near the top, allowing you to open the folder that was created.

Note that Visual Studio Code uses your machine's Git installation, and requires 2.0.0 or higher.

Why can't I have abstract static methods in C#?

Here is a situation where there is definitely a need for inheritance for static fields and methods:

abstract class Animal
{
  protected static string[] legs;

  static Animal() {
    legs=new string[0];
  }

  public static void printLegs()
  {
    foreach (string leg in legs) {
      print(leg);
    }
  }
}


class Human: Animal
{
  static Human() {
    legs=new string[] {"left leg", "right leg"};
  }
}


class Dog: Animal
{
  static Dog() {
    legs=new string[] {"left foreleg", "right foreleg", "left hindleg", "right hindleg"};
  }
}


public static void main() {
  Dog.printLegs();
  Human.printLegs();
}


//what is the output?
//does each subclass get its own copy of the array "legs"?

Styling a disabled input with css only

Let's just say you have 3 buttons:

<input type="button" disabled="disabled" value="hello world">
<input type="button" disabled value="hello world">
<input type="button" value="hello world">

To style the disabled button you can use the following css:

input[type="button"]:disabled{
    color:#000;
}

This will only affect the button which is disabled.

To stop the color changing when hovering you can use this too:

input[type="button"]:disabled:hover{
    color:#000;
}

You can also avoid this by using a css-reset.

A simple scenario using wait() and notify() in java

Example

public class myThread extends Thread{
     @override
     public void run(){
        while(true){
           threadCondWait();// Circle waiting...
           //bla bla bla bla
        }
     }
     public synchronized void threadCondWait(){
        while(myCondition){
           wait();//Comminucate with notify()
        }
     }

}
public class myAnotherThread extends Thread{
     @override
     public void run(){
        //Bla Bla bla
        notify();//Trigger wait() Next Step
     }

}

SqlException: DB2 SQL error: SQLCODE: -302, SQLSTATE: 22001, SQLERRMC: null

You can find the codes in the DB2 Information Center. Here's a definition of the -302 from the z/OS Information Center:

THE VALUE OF INPUT VARIABLE OR PARAMETER NUMBER position-number IS INVALID OR TOO LARGE FOR THE TARGET COLUMN OR THE TARGET VALUE

On Linux/Unix/Windows DB2, you'll look under SQL Messages to find your error message. If the code is positive, you'll look for SQLxxxxW, if it's negative, you'll look for SQLxxxxN, where xxxx is the code you're looking up.

Accessing the index in 'for' loops?

This serves the purpose well enough:

list1 = [10, 'sumit', 43.21, 'kumar', '43', 'test', 3]
for x in list1:
    print('index:', list1.index(x), 'value:', x)

HTML meta tag for content language

Html5 also recommend to use <html lang="es-ES"> The small letter lang tag only specifies: language code The large letter specifies: country code

This is really useful for ie.Chrome, when the browser is proposing to translate web content(ie google translate)

How to connect to mysql with laravel?

Laravel makes it very easy to manage your database connections through app/config/database.php.

As you noted, it is looking for a database called 'database'. The reason being that this is the default name in the database configuration file.

'mysql' => array(
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'database', <------ Default name for database
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
),

Change this to the name of the database that you would like to connect to like this:

'mysql' => array(
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'my_awesome_data', <------ change name for database
    'username'  => 'root',            <------ remember credentials
    'password'  => '',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
),

Once you have this configured correctly you will easily be able to access your database!

Happy Coding!

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

Important to know in what file it comes to this error (in you example it is META-INF/LICENSE.txt) , in my case it was in META-INF/LICENSE [without ".txt"], and then in the file META-INF/ASL2.0 so I added to my build.gradle this lines:

android {
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/ASL2.0'
    }
}

Very important (!) -> add the name of the file in the same style, that you see it in the error message: the text is case sensitive, and there is a difference between *.txt and *(without "txt").

Tomcat request timeout

Add tomcat in Eclipse

In Eclipse, as tomcat server, double click "Tomcat v7.0 Server at Localhost", Change the properties as shown in time out settings 45 to whatever sec you like

Javascript set img src

Also, one way to solve this is to use document.createElement and create your html img and set its attributes like this.

var image = document.createElement("img");
var imageParent = document.getElementById("Id of HTML element to append the img");
image.id = "Id";
image.className = "class";
image.src = searchPic.src;
imageParent.appendChild(image);

REMARK: One point is that Javascript community right now encourages developers to use document selectors such as querySelector, getElementById and getElementsByClassName rather than document["pic1"].

How do I right align div elements?

If you have multiple divs that you want aligned side by side at the right end of the parent div, set text-align: right; on the parent div.

PHP Redirect with POST data

I know this is an old question, but I have yet another alternative solution with jQuery:

var actionForm = $('<form>', {'action': 'nextpage.php', 'method': 'post'}).append($('<input>', {'name': 'action', 'value': 'delete', 'type': 'hidden'}), $('<input>', {'name': 'id', 'value': 'some_id', 'type': 'hidden'}));
actionForm.submit();

The above code uses jQuery to create a form tag, appending hidden fields as post fields, and submit it at last. The page will forward to the form target page with the POST data attached.

p.s. JavaScript & jQuery are required for this case. As suggested by the comments of the other answers, you can make use of <noscript> tag to create a standard HTML form in case JS is disabled.

Update a local branch with the changes from a tracked remote branch

You have set the upstream of that branch

(see:

git branch -f --track my_local_branch origin/my_remote_branch
# OR (if my_local_branch is currently checked out):
$ git branch --set-upstream-to my_local_branch origin/my_remote_branch

(git branch -f --track won't work if the branch is checked out: use the second command git branch --set-upstream-to instead, or you would get "fatal: Cannot force update the current branch.")

That means your branch is already configured with:

branch.my_local_branch.remote origin
branch.my_local_branch.merge my_remote_branch

Git already has all the necessary information.
In that case:

# if you weren't already on my_local_branch branch:
git checkout my_local_branch 
# then:
git pull

is enough.


If you hadn't establish that upstream branch relationship when it came to push your 'my_local_branch', then a simple git push -u origin my_local_branch:my_remote_branch would have been enough to push and set the upstream branch.
After that, for the subsequent pulls/pushes, git pull or git push would, again, have been enough.

HTML5 Audio Looping

I did it this way,

<audio controls="controls" loop="loop">
<source src="someSound.ogg" type="audio/ogg" />
</audio>

and it looks like this

enter image description here

Python, add items from txt file into a list

#function call
read_names(names.txt)
#function def
def read_names(filename): 
with open(filename, 'r') as fileopen:
    name_list = [line.strip() for line in fileopen]
    print (name_list)

Script to get the HTTP status code of a list of urls?

wget --spider -S "http://url/to/be/checked" 2>&1 | grep "HTTP/" | awk '{print $2}'

prints only the status code for you

How to convert List<Integer> to int[] in Java?

try also Dollar (check this revision):

import static com.humaorie.dollar.Dollar.*
...

List<Integer> source = ...;
int[] ints = $(source).convert().toIntArray();

Violation Long running JavaScript task took xx ms

In order to identify the source of the problem, run your application, and record it in Chrome's Performance tab.

There you can check various functions that took a long time to run. In my case, the one that correlated with warnings in console was from a file which was loaded by the AdBlock extension, but this could be something else in your case.

Check these files and try to identify if this is some extension's code or yours. (If it is yours, then you have found the source of your problem.)

How to get the last characters in a String in Java, regardless of String size

String inputstr = "abcd: efg: 1006746"
int startindex = inputstr.length() - 10;
String outputtendigitstr = inputstr.substring(startindex);

Make sure you check string length is more than 10.

Mipmaps vs. drawable folders

The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.

According to this Google blogpost:

It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.

When referencing the mipmap- folders ensure you are using the following reference:

android:icon="@mipmap/ic_launcher"

The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.

How do I rename a MySQL schema?

If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE

Edit: On the model overview it's under Physical Schemata

Screenshot:

enter image description here

Android Studio cannot resolve R in imported project?

For me, with Android Studio 1.5.1, the solution was to recreate the whole project with a slightly different name.

I think it didn't handle the app name "Kommentator_AS", because several places the package was named"Kommentator" instead.

How to read all files in a folder from Java?

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class AvoidNullExp {

public static void main(String[] args) {

    List<File> fileList =new ArrayList<>();
     final File folder = new File("g:/master");
     new AvoidNullExp().listFilesForFolder(folder, fileList);
}

    public void listFilesForFolder(final File folder,List<File> fileList) {
        File[] filesInFolder = folder.listFiles();
        if (filesInFolder != null) {
            for (final File fileEntry : filesInFolder) {
                if (fileEntry.isDirectory()) {
                    System.out.println("DIR : "+fileEntry.getName());
                listFilesForFolder(fileEntry,fileList);
            } else {
                System.out.println("FILE : "+fileEntry.getName());
                fileList.add(fileEntry);
            }
         }
        }
     }


}

Sorting string array in C#

If you have problems with numbers (say 1, 2, 10, 12 which will be sorted 1, 10, 12, 2) you can use LINQ:

var arr = arr.OrderBy(x=>x).ToArray();

Retrieve data from website in android app

You can do the HTML parsing but it is not at all recommended instead ask the website owners to provide web services then you can parse that information.

React Native fetch() Network Request Failed

I was using localhost for the address, which was obviously wrong. After replacing it with the IP address of the server (in the network that emulator is), it worked perfectly.

Edit

In Android Emulator, the address of the development machine is 10.0.2.2. More explanation here

For Genymotion, the address is 10.0.3.2. More info here

SELECT using 'CASE' in SQL

which platform ?

SELECT 
  CASE 
    WHEN FRUIT = 'A' THEN 'APPLE' 
    ELSE FRUIT ='B' THEN 'BANANA' 
   END AS FRUIT     
FROM FRUIT_TABLE;

HorizontalAlignment=Stretch, MaxWidth, and Left aligned at the same time?

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" MaxWidth="200"/>
    </Grid.ColumnDefinitions>

    <TextBox Background="Azure" Text="Hello" />
</Grid>

Check for false

Checking if something isn't false... So it's true, just if you're doing something that is quantum physics.

if(!(borrar() === false))

or

if(borrar() === true)

Android: Access child views from a ListView

This assumes you know the position of the element in the ListView :

  View element = listView.getListAdapter().getView(position, null, null);

Then you should be able to call getLeft() and getTop() to determine the elements on screen position.

Java HTTPS client certificate authentication

Finally managed to solve all the issues, so I'll answer my own question. These are the settings/files I've used to manage to get my particular problem(s) solved;

The client's keystore is a PKCS#12 format file containing

  1. The client's public certificate (in this instance signed by a self-signed CA)
  2. The client's private key

To generate it I used OpenSSL's pkcs12 command, for example;

openssl pkcs12 -export -in client.crt -inkey client.key -out client.p12 -name "Whatever"

Tip: make sure you get the latest OpenSSL, not version 0.9.8h because that seems to suffer from a bug which doesn't allow you to properly generate PKCS#12 files.

This PKCS#12 file will be used by the Java client to present the client certificate to the server when the server has explicitly requested the client to authenticate. See the Wikipedia article on TLS for an overview of how the protocol for client certificate authentication actually works (also explains why we need the client's private key here).

The client's truststore is a straight forward JKS format file containing the root or intermediate CA certificates. These CA certificates will determine which endpoints you will be allowed to communicate with, in this case it will allow your client to connect to whichever server presents a certificate which was signed by one of the truststore's CA's.

To generate it you can use the standard Java keytool, for example;

keytool -genkey -dname "cn=CLIENT" -alias truststorekey -keyalg RSA -keystore ./client-truststore.jks -keypass whatever -storepass whatever
keytool -import -keystore ./client-truststore.jks -file myca.crt -alias myca

Using this truststore, your client will try to do a complete SSL handshake with all servers who present a certificate signed by the CA identified by myca.crt.

The files above are strictly for the client only. When you want to set-up a server as well, the server needs its own key- and truststore files. A great walk-through for setting up a fully working example for both a Java client and server (using Tomcat) can be found on this website.

Issues/Remarks/Tips

  1. Client certificate authentication can only be enforced by the server.
  2. (Important!) When the server requests a client certificate (as part of the TLS handshake), it will also provide a list of trusted CA's as part of the certificate request. When the client certificate you wish to present for authentication is not signed by one of these CA's, it won't be presented at all (in my opinion, this is weird behaviour, but I'm sure there's a reason for it). This was the main cause of my issues, as the other party had not configured their server properly to accept my self-signed client certificate and we assumed that the problem was at my end for not properly providing the client certificate in the request.
  3. Get Wireshark. It has great SSL/HTTPS packet analysis and will be a tremendous help debugging and finding the problem. It's similar to -Djavax.net.debug=ssl but is more structured and (arguably) easier to interpret if you're uncomfortable with the Java SSL debug output.
  4. It's perfectly possible to use the Apache httpclient library. If you want to use httpclient, just replace the destination URL with the HTTPS equivalent and add the following JVM arguments (which are the same for any other client, regardless of the library you want to use to send/receive data over HTTP/HTTPS):

    -Djavax.net.debug=ssl
    -Djavax.net.ssl.keyStoreType=pkcs12
    -Djavax.net.ssl.keyStore=client.p12
    -Djavax.net.ssl.keyStorePassword=whatever
    -Djavax.net.ssl.trustStoreType=jks
    -Djavax.net.ssl.trustStore=client-truststore.jks
    -Djavax.net.ssl.trustStorePassword=whatever

Running PHP script from the command line

I was looking for a resolution to this issue in Windows, and it seems to be that if you don't have the environments vars ok, you need to put the complete directory. For eg. with a file in the same directory than PHP:

F:\myfolder\php\php.exe -f F:\myfolder\php\script.php

Laravel 5.2 redirect back with success message

You should remove web middleware from routes.php. Adding web middleware manually causes session and request related problems in Laravel 5.2.27 and higher.

If it didn't help (still, keep routes.php without web middleware), you can try little bit different approach:

return redirect()->back()->with('message', 'IT WORKS!');

Displaying message if it exists:

@if(session()->has('message'))
    <div class="alert alert-success">
        {{ session()->get('message') }}
    </div>
@endif

Chosen Jquery Plugin - getting selected values

I believe the problem occurs when targeting by ID, because Chosen will copy the ID from the original select onto it's newly created div, leaving you with 2 elements of the same (now not-unique) ID on the current page.

When targeting Chosen by ID, use a selector specific to the select:

$( 'select#yourID' ).on( 'change', function() {
    console.log( $( this ).val() );
} );

...instead of...

$( '#yourID' ).on( 'change', function() {
    console.log( $( this ).val() );
} );

This works because Chosen mirrors its selected items back to the original (now hidden) select element, even in multi-mode.

(It also continues to work with or without Chosen, say... if you decide to go a different direction in your application.)

Debian 8 (Live-CD) what is the standard login and password?

Although this is an old question, I had the same question when using the Standard console version. The answer can be found in the Debian Live manual under the section 10.1 Customizing the live user. It says:

It is also possible to change the default username "user" and the default password "live".

I tried the username user and password live and it did work. If you want to run commands as root you can preface each command with sudo

Xcode - iPhone - profile doesn't match any valid certificate-/private-key pair in the default keychain

My problem was my Target profile didn't have the proper code signing option selected:

Target Menu -> Code Signing -> Code Signing Identity

Choose "iPhone developer" then select the provisional profile you created.

How to make a HTML Page in A4 paper size page(s)?

I saw this solution after searching at google, search for "A4 CSS page template" (codepen.io). It shows an A4 (A3,A5, also portrait) sized area in the browser, using the <page> tag. Inside this tag the content is shown, but absolute position is still with respect to browser area.

_x000D_
_x000D_
body {_x000D_
  background: rgb(204,204,204); _x000D_
}_x000D_
page {_x000D_
  background: white;_x000D_
  display: block;_x000D_
  margin: 0 auto;_x000D_
  margin-bottom: 0.5cm;_x000D_
  box-shadow: 0 0 0.5cm rgba(0,0,0,0.5);_x000D_
}_x000D_
page[size="A4"] {  _x000D_
  width: 21cm;_x000D_
  height: 29.7cm; _x000D_
}_x000D_
page[size="A4"][layout="portrait"] {_x000D_
  width: 29.7cm;_x000D_
  height: 21cm;  _x000D_
}_x000D_
@media print {_x000D_
  body, page {_x000D_
    margin: 0;_x000D_
    box-shadow: 0;_x000D_
  }_x000D_
}
_x000D_
<page size="A4">A4</page>_x000D_
<page size="A4" layout="portrait">A4 portrait</page>
_x000D_
_x000D_
_x000D_

This works for me without any other css/js-library to be included. Works for current browsers (IE, FF, Chrome).

How to programmatically log out from Facebook SDK 3.0 without using Facebook login/logout button?

Facebook provides two ways to login and logout from an account. One is to use LoginButton and the other is to use LoginManager. LoginButton is just a button which on clicked, the logging in is accomplished. On the other side LoginManager does this on its own. In your case you have use LoginManager to logout automatically.

LoginManager.getInstance().logout() does this work for you.

Create a new txt file using VB.NET

You also might want to check if the file already exists to avoid replacing the file by accident (unless that is the idea of course:

Dim filepath as String = "C:\my files\2010\SomeFileName.txt"
If Not System.IO.File.Exists(filepath) Then
   System.IO.File.Create(filepath).Dispose()
End If

How do I make CMake output into a 'bin' dir?

Use the EXECUTABLE_OUTPUT_PATH CMake variable to set the needed path. For details, refer to the online CMake documentation:

CMake 2.8.8 Documentation

Using sed to mass rename files

The backslash-paren stuff means, "while matching the pattern, hold on to the stuff that matches in here." Later, on the replacement text side, you can get those remembered fragments back with "\1" (first parenthesized block), "\2" (second block), and so on.

How to use Google Translate API in my Java application?

Use java-google-translate-text-to-speech instead of Google Translate API v2 Java.

About java-google-translate-text-to-speech

Api unofficial with the main features of Google Translate in Java.

Easy to use!

It also provide text to speech api. If you want to translate the text "Hello!" in Romanian just write:

Translator translate = Translator.getInstance();
String text = translate.translate("Hello!", Language.ENGLISH, Language.ROMANIAN);
System.out.println(text); // "Buna ziua!" 

It's free!

As @r0ast3d correctly said:

Important: Google Translate API v2 is now available as a paid service. The courtesy limit for existing Translate API v2 projects created prior to August 24, 2011 will be reduced to zero on December 1, 2011. In addition, the number of requests your application can make per day will be limited.

This is correct: just see the official page:

Google Translate API is available as a paid service. See the Pricing and FAQ pages for details.

BUT, java-google-translate-text-to-speech is FREE!

Example!

I've created a sample application that demonstrates that this works. Try it here: https://github.com/IonicaBizau/text-to-speech

In PowerShell, how do I define a function in a file and call it from the PowerShell commandline?

Assuming you have a module file called Dummy-Name.psm1 which has a method called Function-Dumb()

Import-Module "Dummy-Name.psm1";
Get-Command -Module "Function-Dumb";
#
#
Function-Dumb;

Windows batch: echo without new line

You can remove the newline using "tr" from gnuwin32 (coreutils package)

@echo off
set L=First line
echo %L% | tr -d "\r\n"
echo Second line
pause

By the way, if you are doing lots of scripting, gnuwin32 is a goldmine.

What is the best IDE for PHP?

Geany is a great lightweight editor -- like Notepad++ for Linux, only better. I find this, combined with a few shell scripts and symlinks for linking modules into a web source tree, make developing on Linux easy and fun.

How to override trait function and call it from the overridden function?

An alternative approach if interested - with an extra intermediate class to use the normal OOO way. This simplifies the usage with parent::methodname

trait A {
    function calc($v) {
        return $v+1;
    }
}

// an intermediate class that just uses the trait
class IntClass {
    use A;
}

// an extended class from IntClass
class MyClass extends IntClass {
    function calc($v) {
        $v++;
        return parent::calc($v);
    }
}

Java: Rotating Images

This is how you can do it. This code assumes the existance of a buffered image called 'image' (like your comment says)

// The required drawing location
int drawLocationX = 300;
int drawLocationY = 300;

// Rotation information

double rotationRequired = Math.toRadians (45);
double locationX = image.getWidth() / 2;
double locationY = image.getHeight() / 2;
AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);

// Drawing the rotated image at the required drawing locations
g2d.drawImage(op.filter(image, null), drawLocationX, drawLocationY, null);

Regular expressions inside SQL Server

In order to match a digit, you can use [0-9].

So you could use 5[0-9][0-9][0-9][0-9][0-9][0-9] and [0-9][0-9][0-9][0-9]7[0-9][0-9][0-9]. I do this a lot for zip codes.

How to get rid of `deprecated conversion from string constant to ‘char*’` warnings in GCC?

Replace

char *str = "hello";

with

char *str = (char*)"hello";

or if you are calling in function:

foo("hello");

replace this with

foo((char*) "hello");

How to scroll to an element?

Follow these steps:

1) Install:

npm install react-scroll-to --save

2) Import the package:

import { ScrollTo } from "react-scroll-to";

3) Usage:

class doc extends Component {
  render() {
    return(
      <ScrollTo>
        {({ scroll }) => (
          <a onClick={() => scroll({ x: 20, y: 500, , smooth: true })}>Scroll to Bottom</a>
        )}
      </ScrollTo>
    )
  }
}

Safely remove migration In Laravel

If the migration has been run (read: migrated) then you should roll back your migration to clear the history from your database table. Once you're rolled back you should be able to safely delete your migration file and then proceed with migrating again.

How to move all files including hidden files into parent directory via *

By using the find command in conjunction with the mv command, you can prevent the mv command from trying to move directories (e.g. .. and .) and subdirectories. Here's one option:

find /path/subfolder -maxdepth 1 -type f -name '*' -exec mv -n {} /path \;

There are problems with some of the other answers provided. For example, each of the following will try to move subdirectories from the source path:

1) mv /path/subfolder/* /path/ ; mv /path/subfolder/.* /path/
2) mv /path/subfolder/{.,}* /path/ 
3) mv /source/path/{.[!.],}* /destination/path

Also, 2) includes the . and .. files and 3) misses files like ..foobar, ...barfoo, etc.

You could use, mv /source/path/{.[!.],..?,}* /destination/path, which would include the files missed by 3), but it would still try to move subdirectories. Using the find command with the mv command as I describe above eliminates all these problems.

How to convert Seconds to HH:MM:SS using T-SQL

Using SQL Server 2008

declare @Seconds as int = 3600;
SELECT CONVERT(time(0), DATEADD(SECOND, @Seconds, 0)) as 'hh:mm:ss'

What is the difference between Select and Project Operations

In Relational algebra 'Selection' and 'Projection' are different operations, but the SQL SELECT combines these operations in a single statement.

Select retrieves the tuples (rows) in a relation (table) for which the condition in 'predicate' section (WHERE clause) stands true.

Project retrieves the attributes (columns) specified.

The following SQL SELECT query:

select field1,field2 from table1 where field1 = 'Value';

is a combination of both Projection and Selection operations of relational algebra.

Count table rows

As mentioned by Santosh, I think this query is suitably fast, while not querying all the table.

To return integer result of number of data records, for a specific tablename in a particular database:

select TABLE_ROWS from information_schema.TABLES where TABLE_SCHEMA = 'database' 
AND table_name='tablename';

Try-catch-finally-return clarification

Here is some code that show how it works.

class Test
{
    public static void main(String args[]) 
    { 
        System.out.println(Test.test()); 
    }

    public static String test()
    {
        try {
            System.out.println("try");
            throw new Exception();
        } catch(Exception e) {
            System.out.println("catch");
            return "return"; 
        } finally {  
            System.out.println("finally");
            return "return in finally"; 
        }
    }
}

The results is:

try
catch
finally
return in finally

Conditionally ignoring tests in JUnit 4

You should checkout Junit-ext project. They have RunIf annotation that performs conditional tests, like:

@Test
@RunIf(DatabaseIsConnected.class)
public void calculateTotalSalary() {
    //your code there
}

class DatabaseIsConnected implements Checker {
   public boolean satisify() {
        return Database.connect() != null;
   }
}

[Code sample taken from their tutorial]

Adding multiple columns AFTER a specific column in MySQL

One possibility would be to not bother about reordering the columns in the table and simply modify it by add the columns. Then, create a view which has the columns in the order you want -- assuming that the order is truly important. The view can be easily changed to reflect any ordering that you want. Since I can't imagine that the order would be important for programmatic applications, the view should suffice for those manual queries where it might be important.

What is setBounds and how do I use it?

You can use setBounds(x, y, width, height) to specify the position and size of a GUI component if you set the layout to null. Then (x, y) is the coordinate of the upper-left corner of that component.

How to install python3 version of package via pip on Ubuntu?

If you have pip installed in both pythons, and both are in your path, just use:

$ pip-2.7 install PACKAGENAME
$ pip-3.2 install PACKAGENAME

References:

This is a duplicate of question #2812520

How to change the buttons text using javascript

innerText is the current correct answer for this. The other answers are outdated and incorrect.

document.getElementById('ShowButton').innerText = 'Show filter';

innerHTML also works, and can be used to insert HTML.

How to set a value to a file input in HTML?

Define in html:

<input type="hidden" name="image" id="image"/>

In JS:

ajax.jsonRpc("/consulta/dni", 'call', {'document_number': document_number})
    .then(function (data) {
        if (data.error){
            ...;
        }
        else {
            $('#image').val(data.image);
        }
    })

After:

<input type="hidden" name="image" id="image" value="/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8U..."/>
<button type="submit">Submit</button>

How to filter JSON Data in JavaScript or jQuery?

The following code works for me:

_x000D_
_x000D_
var data = [{"name":"Lenovo Thinkpad 41A4298","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41A2222","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"},_x000D_
{"name":"Lenovo Thinkpad 41A424448","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"},_x000D_
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"},_x000D_
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"},_x000D_
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}]_x000D_
_x000D_
var data_filter = data.filter( element => element.website =="yahoo")_x000D_
console.log(data_filter)
_x000D_
_x000D_
_x000D_

How to simulate a button click using code?

Android's callOnClick() (added in API 15) can sometimes be a better choice in my experience than performClick(). If a user has selection sounds enabled, then performClick() could cause the user to hear two continuous selection sounds that are somewhat layered on top of each other which can be jarring. (One selection sound for the user's first button click, and then another for the other button's OnClickListener that you're calling via code.)

How to write MySQL query where A contains ( "a" or "b" )

Two options:

  1. Use the LIKE keyword, along with percent signs in the string

    select * from table where field like '%a%' or field like '%b%'.
    

    (note: If your search string contains percent signs, you'll need to escape them)

  2. If you're looking for more a complex combination of strings than you've specified in your example, you could regular expressions (regex):

    See the MySQL manual for more on how to use them: http://dev.mysql.com/doc/refman/5.1/en/regexp.html

Of these, using LIKE is the most usual solution -- it's standard SQL, and in common use. Regex is less commonly used but much more powerful.

Note that whichever option you go with, you need to be aware of possible performance implications. Searching for sub-strings like this will mean that the query will have to scan the entire table. If you have a large table, this could make for a very slow query, and no amount of indexing is going to help.

If this is an issue for you, and you'r going to need to search for the same things over and over, you may prefer to do something like adding a flag field to the table which specifies that the string field contains the relevant sub-strings. If you keep this flag field up-to-date when you insert of update a record, you could simply query the flag when you want to search. This can be indexed, and would make your query much much quicker. Whether it's worth the effort to do that is up to you, it'll depend on how bad the performance is using LIKE.

how to read a text file using scanner in Java?

I would recommend loading the file as Resource and converting the input stream into string. This would give you the flexibility to load the file anywhere relative to the classpath

Best way to check if a Data Table has a null value in it

I will do like....

(!DBNull.Value.Equals(dataSet.Tables[6].Rows[0]["_id"]))

How to merge specific files from Git branches

What I've done is a bit manual, but I:

  1. Merged the branches normally; Reverted the merge with revert;
  2. Checked out all my files to HEAD~1, that is, their state in the merge commit;
  3. Rebased my commits to hide this hackery from the commit history.

Ugly? Yes. Easy to remember? Also yes.

How to convert BigInteger to String in java

Use m.toString() or String.valueOf(m). String.valueOf uses toString() but is null safe.

Why split the <script> tag when writing it with document.write()?

I think is for prevent the browser's HTML parser from interpreting the <script>, and mainly the </script> as the closing tag of the actual script, however I don't think that using document.write is a excellent idea for evaluating script blocks, why don't use the DOM...

var newScript = document.createElement("script");
...

How to split a string to 2 strings in C

You can do:

char str[] ="Stackoverflow Serverfault";
char piece1[20] = ""
    ,piece2[20] = "";
char * p;

p = strtok (str," "); // call the strtok with str as 1st arg for the 1st time.
if (p != NULL) // check if we got a token.
{
    strcpy(piece1,p); // save the token.
    p = strtok (NULL, " "); // subsequent call should have NULL as 1st arg.
    if (p != NULL) // check if we got a token.
        strcpy(piece2,p); // save the token.
}
printf("%s :: %s\n",piece1,piece2); // prints Stackoverflow :: Serverfault

If you expect more than one token its better to call the 2nd and subsequent calls to strtok in a while loop until the return value of strtok becomes NULL.

What is the easiest way to remove the first character from a string?

I prefer this:

str = "[12,23,987,43"
puts str[1..-1]
>> 12,23,987,43

Calling one Bash script from another Script passing it arguments with quotes and spaces

Quote your args in Testscript 1:

echo "TestScript1 Arguments:"
echo "$1"
echo "$2"
echo "$#"
./testscript2 "$1" "$2"

Cannot overwrite model once compiled Mongoose

If you are using Serverless offline and don't want to use --skipCacheInvalidation, you can very well use:

module.exports = mongoose.models.Users || mongoose.model('Users', UsersSchema);

How to enable scrolling on website that disabled scrolling?

adding overflow:visible !important; to the body element worked for me.

How to ping multiple servers and return IP address and Hostnames using batch script?

the problem with ping is if the host is not alive often your local machine will return an answer that the pinged host is not available, thus the errorcode of ping will be 0 and your code will run in error because not recognizing the down state.

better do it this way

ping -n 4 %1 | findstr TTL
if %errorlevel%==0 (goto :eof) else (goto :error)

this way you look for a typical string ttl which is always in the well done ping result and check error on this findstr instead of irritating ping

overall this looks like this:

@echo off
SetLocal


set log=path/to/logfile.txt
set check=path/to/checkfile.txt

:start
echo. some echo date >>%log%

:check
for /f %%r in (%check%) do (call :ping %%r)
goto :eof

:ping
ping -n 4 %1 | findstr TTL
if %errorlevel%==0 (goto :eof) else (goto :error)

:error
echo. some errormessage to >>%log%
echo. some blat to mail?

:eof
echo. some good message to >>%log%

nginx error "conflicting server name" ignored

There should be only one localhost defined, check sites-enabled or nginx.conf.

C compile error: "Variable-sized object may not be initialized"

int size=5;
int ar[size ]={O};

/* This  operation gives an error -  
variable sized array may not be 
initialised.  Then just try this. 
*/
int size=5,i;
int ar[size];
for(i=0;i<size;i++)
{
    ar[i]=0;
}

How to change TIMEZONE for a java.util.Calendar/Date

In Java, Dates are internally represented in UTC milliseconds since the epoch (so timezones are not taken into account, that's why you get the same results, as getTime() gives you the mentioned milliseconds).
In your solution:

Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long gmtTime = cSchedStartCal.getTime().getTime();

long timezoneAlteredTime = gmtTime + TimeZone.getTimeZone("Asia/Calcutta").getRawOffset();
Calendar cSchedStartCal1 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
cSchedStartCal1.setTimeInMillis(timezoneAlteredTime);

you just add the offset from GMT to the specified timezone ("Asia/Calcutta" in your example) in milliseconds, so this should work fine.

Another possible solution would be to utilise the static fields of the Calendar class:

//instantiates a calendar using the current time in the specified timezone
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
//change the timezone
cSchedStartCal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
//get the current hour of the day in the new timezone
cSchedStartCal.get(Calendar.HOUR_OF_DAY);

Refer to stackoverflow.com/questions/7695859/ for a more in-depth explanation.

How to use enums as flags in C++?

I'd like to elaborate on Uliwitness answer, fixing his code for C++98 and using the Safe Bool idiom, for lack of the std::underlying_type<> template and the explicit keyword in C++ versions below C++11.

I also modified it so that the enum values can be sequential without any explicit assignment, so you can have

enum AnimalFlags_
{
    HasClaws,
    CanFly,
    EatsFish,
    Endangered
};
typedef FlagsEnum<AnimalFlags_> AnimalFlags;

seahawk.flags = AnimalFlags() | CanFly | EatsFish | Endangered;

You can then get the raw flags value with

seahawk.flags.value();

Here's the code.

template <typename EnumType, typename Underlying = int>
class FlagsEnum
{
    typedef Underlying FlagsEnum::* RestrictedBool;

public:
    FlagsEnum() : m_flags(Underlying()) {}

    FlagsEnum(EnumType singleFlag):
        m_flags(1 << singleFlag)
    {}

    FlagsEnum(const FlagsEnum& original):
        m_flags(original.m_flags)
    {}

    FlagsEnum& operator |=(const FlagsEnum& f) {
        m_flags |= f.m_flags;
        return *this;
    }

    FlagsEnum& operator &=(const FlagsEnum& f) {
        m_flags &= f.m_flags;
        return *this;
    }

    friend FlagsEnum operator |(const FlagsEnum& f1, const FlagsEnum& f2) {
        return FlagsEnum(f1) |= f2;
    }

    friend FlagsEnum operator &(const FlagsEnum& f1, const FlagsEnum& f2) {
        return FlagsEnum(f1) &= f2;
    }

    FlagsEnum operator ~() const {
        FlagsEnum result(*this);
        result.m_flags = ~result.m_flags;
        return result;
    }

    operator RestrictedBool() const {
        return m_flags ? &FlagsEnum::m_flags : 0;
    }

    Underlying value() const {
        return m_flags;
    }

protected:
    Underlying  m_flags;
};

How do I create HTML table using jQuery dynamically?

An example with a little less stringified html:

var container = $('#my-container'),
  table = $('<table>');

users.forEach(function(user) {
  var tr = $('<tr>');
  ['ID', 'Name', 'Address'].forEach(function(attr) {
    tr.append('<td>' + user[attr] + '</td>');
  });
  table.append(tr);
});

container.append(table);

How to change navbar/container width? Bootstrap 3

I just solved this issue myself. You were on the right track.

@media (min-width: 1200px) {
    .container{
        max-width: 970px;
    }
}

Here we say: On viewports 1200px or larger - set container max-width to 970px. This will overwrite the standard class that currently sets max-width to 1170px for that range.

NOTE: Make sure you include this AFTER the bootstrap.css stuff (everyone has made this little mistake in the past).

Hope this helps.. good luck!

difference between primary key and unique key

A Primary key is a unique key.

Each table must have at most ONE primary key but it can have multiple unique key. A primary key is used to uniquely identify a table row. A primary key cannot be NULL since NULL is not a value.

iOS: UIButton resize according to text length

In UIKit, there are additions to the NSString class to get from a given NSString object the size it'll take up when rendered in a certain font.

Docs was here. Now it's here under Deprecated.

In short, if you go:

CGSize stringsize = [myString sizeWithFont:[UIFont systemFontOfSize:14]]; 
//or whatever font you're using
[button setFrame:CGRectMake(10,0,stringsize.width, stringsize.height)];

...you'll have set the button's frame to the height and width of the string you're rendering.

You'll probably want to experiment with some buffer space around that CGSize, but you'll be starting in the right place.

How to recursively find and list the latest modified files in a directory with subdirectories and times

This command works on Mac OS X:

find "$1" -type f -print0 | xargs -0 gstat --format '%Y :%y %n' | sort -nr | cut -d: -f2- | head

On Linux, as the original poster asked, use stat instead of gstat.

This answer is, of course, user37078's outstanding solution, promoted from comment to full answer. I mixed in CharlesB's insight to use gstat on Mac OS X. I got coreutils from MacPorts rather than Homebrew, by the way.

And here's how I packaged this into a simple command ~/bin/ls-recent.sh for reuse:

#!/bin/bash
# ls-recent: list files in a directory tree, most recently modified first
#
# Usage: ls-recent path [-10 | more]
#
# Where "path" is a path to target directory, "-10" is any argument to pass
# to "head" to limit the number of entries, and "more" is a special argument
# in place of "-10" which calls the pager "more" instead of "head".
if [ "more" = "$2" ]; then
   H=more; N=''
else
   H=head; N=$2
fi

find "$1" -type f -print0 |xargs -0 gstat --format '%Y :%y %n' \
    |sort -nr |cut -d: -f2- |$H $N

.NET NewtonSoft JSON deserialize map to a different property name

Adding to Jacks solution. I need to Deserialize using the JsonProperty and Serialize while ignoring the JsonProperty (or vice versa). ReflectionHelper and Attribute Helper are just helper classes that get a list of properties or attributes for a property. I can include if anyone actually cares. Using the example below you can serialize the viewmodel and get "Amount" even though the JsonProperty is "RecurringPrice".

    /// <summary>
    /// Ignore the Json Property attribute. This is usefule when you want to serialize or deserialize differently and not 
    /// let the JsonProperty control everything.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class IgnoreJsonPropertyResolver<T> : DefaultContractResolver
    {
        private Dictionary<string, string> PropertyMappings { get; set; }

        public IgnoreJsonPropertyResolver()
        {
            this.PropertyMappings = new Dictionary<string, string>();
            var properties = ReflectionHelper<T>.GetGetProperties(false)();
            foreach (var propertyInfo in properties)
            {
                var jsonProperty = AttributeHelper.GetAttribute<JsonPropertyAttribute>(propertyInfo);
                if (jsonProperty != null)
                {
                    PropertyMappings.Add(jsonProperty.PropertyName, propertyInfo.Name);
                }
            }
        }

        protected override string ResolvePropertyName(string propertyName)
        {
            string resolvedName = null;
            var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
            return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
        }
    }

Usage:

        var settings = new JsonSerializerSettings();
        settings.DateFormatString = "YYYY-MM-DD";
        settings.ContractResolver = new IgnoreJsonPropertyResolver<PlanViewModel>();
        var model = new PlanViewModel() {Amount = 100};
        var strModel = JsonConvert.SerializeObject(model,settings);

Model:

public class PlanViewModel
{

    /// <summary>
    ///     The customer is charged an amount over an interval for the subscription.
    /// </summary>
    [JsonProperty(PropertyName = "RecurringPrice")]
    public double Amount { get; set; }

    /// <summary>
    ///     Indicates the number of intervals between each billing. If interval=2, the customer would be billed every two
    ///     months or years depending on the value for interval_unit.
    /// </summary>
    public int Interval { get; set; } = 1;

    /// <summary>
    ///     Number of free trial days that can be granted when a customer is subscribed to this plan.
    /// </summary>
    public int TrialPeriod { get; set; } = 30;

    /// <summary>
    /// This indicates a one-time fee charged upfront while creating a subscription for this plan.
    /// </summary>
    [JsonProperty(PropertyName = "SetupFee")]
    public double SetupAmount { get; set; } = 0;


    /// <summary>
    /// String representing the type id, usually a lookup value, for the record.
    /// </summary>
    [JsonProperty(PropertyName = "TypeId")]
    public string Type { get; set; }

    /// <summary>
    /// Billing Frequency
    /// </summary>
    [JsonProperty(PropertyName = "BillingFrequency")]
    public string Period { get; set; }


    /// <summary>
    /// String representing the type id, usually a lookup value, for the record.
    /// </summary>
    [JsonProperty(PropertyName = "PlanUseType")]
    public string Purpose { get; set; }
}

Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

If you have a hard time remembering the default values (I know I have...) here's a short extract from BalusC's answer:

Component    | Submit          | Refresh
------------ | --------------- | --------------
f:ajax       | execute="@this" | render="@none"
p:ajax       | process="@this" | update="@none"
p:commandXXX | process="@form" | update="@none"

Launch custom android application from android browser

For example, You have next things:

A link to open your app: http://example.com

The package name of your app: com.example.mypackage

Then you need to do next:

  1. Add an intent filter to your Activity (Can be any activity you want. For more info check the documentation).

    <activity
         android:name=".MainActivity">
    
         <intent-filter android:label="@string/filter_title_view_app_from_web">
             <action android:name="android.intent.action.VIEW" />
             <category android:name="android.intent.category.DEFAULT" />
             <category android:name="android.intent.category.BROWSABLE" />
             <!-- Accepts URIs that begin with "http://example.com" -->
    
             <data
                 android:host="example.com"
                 android:scheme="http" />
         </intent-filter>
    
         <intent-filter>
             <action android:name="android.intent.action.MAIN" />
             <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
    
     </activity> 
    
  2. Create a HTML file to test the link or use this methods.

    Open your Activity directly (just open your Activity, without a choosing dialog).

    Open this link with browser or your programm (by choosing dialog).

  3. Use Mobile Chrome to test

  4. That's it.

And its not necessary to publish app in market to test deep linking =)

Also, for more information, check documentation and useful presentation.

Unable to compile class for JSP: The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

I recently get across the same issue. I was using IntelliJx64 with Tomcat7.0.32 with jdk.8.0.102. There was no issue then. I was able to directly access my deployment localhost:[port] without adding [mywebapp] or /ROOT.

When I tried to migrate to eclipse neon, I came across the same bug that is discussed when I tried to set the path as empty string. When I enforced execution environment to Java7 and set modules to empty it did not solve toe issue. However, when I changed my tomcat installation to 7.072 and manually changed context path configuration to path="" the problem was solved in eclipse. (You can manipulate the path via double click server and switching to module tab too.)

My wonder is how come IntelliJ was not giving any issues with the same bug which was supposed to be related to tomcat installation version?

There also seems to be a relation with the IDE in use.

2D Euclidean vector rotations

you should remove the vars from the function:

x = x * cs - y * sn; // now x is something different than original vector x
y = x * sn + y * cs;

create new coordinates becomes, to avoid calculation of x before it reaches the second line:

px = x * cs - y * sn; 
py = x * sn + y * cs;

How to set environment variables in PyCharm?

I was able to figure out this using a PyCharm plugin called EnvFile. This plugin, basically allows setting environment variables to run configurations from one or multiple files.

The installation is pretty simple:

Preferences > Plugins > Browse repositories... > Search for "Env File" > Install Plugin.

Then, I created a file, in my project root, called environment.env which contains:

DATABASE_URL=postgres://127.0.0.1:5432/my_db_name
DEBUG=1

Then I went to Run->Edit Configurations, and I followed the steps in the next image:

Set Environment Variables

In 3, I chose the file environment.env, and then I could just click the play button in PyCharm, and everything worked like a charm.

Where can I find documentation on formatting a date in JavaScript?

Formatting and especially parsing dates in JavaScript can be a bit of a headache. Not all browsers handle dates in the same way. So while it's useful to know the base methods, its more practical to use a helper library.

The XDate javascript library by Adam Shaw has been around since mid-2011 and is still under active development. It has fantastic documentation, a great API, formatting, tries to remain backwards-compatible and even supports localized strings.

Link to changing the locale strings: https://gist.github.com/1221376

Simulate user input in bash script

You should find the 'expect' command will do what you need it to do. Its widely available. See here for an example : http://www.thegeekstuff.com/2010/10/expect-examples/

(very rough example)

#!/usr/bin/expect
set pass "mysecret"

spawn /usr/bin/passwd

expect "password: "
send "$pass"
expect "password: "
send "$pass"

Swift - Split string over multiple lines

Swift 4 includes support for multi-line string literals. In addition to newlines they can also contain unescaped quotes.

var text = """
    This is some text
    over multiple lines
    """

Older versions of Swift don't allow you to have a single literal over multiple lines but you can add literals together over multiple lines:

var text = "This is some text\n"
         + "over multiple lines\n"

How to embed a video into GitHub README.md?

I combine Alexandre Jasmin and Gab Le Roux answers like this:

[![Demo CountPages alpha](https://share.gifyoutube.com/KzB6Gb.gif)](https://www.youtube.com/watch?v=ek1j272iAmc)

Demo:

Demo CountPages alpha

You can see this demo on github.

I used gifyoutube here, but I recommend using a local gif converter (like ffmpeg, see how) instead of an online one.

To record your screen to gif directly, you may want to check ScreenToGif.

How to include quotes in a string

The Code:

string myString = "Hello " + ((char)34) + " World." + ((char)34);

Output will be:

Hello "World."

Matplotlib legends in subplot

This does what you want and overcomes some of the problems in other answers:

import matplotlib.pyplot as plt

labels = ["HHZ 1", "HHN", "HHE"]
colors = ["r","g","b"]

f,axs = plt.subplots(3, sharex=True, sharey=True)

# ---- loop over axes ----
for i,ax in enumerate(axs):
  axs[i].plot([0,1],[1,0],color=colors[i],label=labels[i])
  axs[i].legend(loc="upper right")

plt.show()

... produces ... subplots

Angular 4 - get input value

<form (submit)="onSubmit()">
   <input [(ngModel)]="playerName">
</form>

let playerName: string;
onSubmit() {
  return this.playerName;
}

Oracle Insert via Select from multiple tables where one table may not have a row

It was not clear to me in the question if ts.tax_status_code is a primary or alternate key or not. Same thing with recipient_code. This would be useful to know.

You can deal with the possibility of your bind variable being null using an OR as follows. You would bind the same thing to the first two bind variables.

If you are concerned about performance, you would be better to check if the values you intend to bind are null or not and then issue different SQL statement to avoid the OR.

insert into account_type_standard 
(account_type_Standard_id, tax_status_id, recipient_id)
(
select 
   account_type_standard_seq.nextval,
   ts.tax_status_id, 
   r.recipient_id
from tax_status ts, recipient r
where (ts.tax_status_code = ? OR (ts.tax_status_code IS NULL and ? IS NULL))
and (r.recipient_code = ? OR (r.recipient_code IS NULL and ? IS NULL))

List of ANSI color escape sequences

For these who don't get proper results other than mentioned languages, if you're using C# to print a text into console(terminal) window you should replace "\033" with "\x1b". In Visual Basic it would be Chrw(27).

Simple pagination in javascript

Following is the Logic which accepts count from user and performs pagination in Javascript. It prints alphabets. Hope it helps!!. Thankyou.

_x000D_
_x000D_
/*_x000D_
*****_x000D_
USER INPUT : NUMBER OF SUGGESTIONS._x000D_
*****_x000D_
*/_x000D_
_x000D_
var recordSize = prompt('please, enter the Record Size');_x000D_
console.log(recordSize);_x000D_
_x000D_
_x000D_
/*_x000D_
*****_x000D_
POPULATE SUGGESTIONS IN THE suggestion_set LIST._x000D_
*****_x000D_
*/_x000D_
var suggestion_set = [];_x000D_
counter = 0;_x000D_
_x000D_
asscicount = 65;_x000D_
do{_x000D_
if(asscicount <= 90){_x000D_
 var temp = String.fromCharCode(asscicount);_x000D_
 suggestion_set.push(temp);_x000D_
 asscicount += 1;     _x000D_
}else{_x000D_
 asscicount = 65;_x000D_
 var temp = String.fromCharCode(asscicount);_x000D_
 suggestion_set.push(temp); _x000D_
 asscicount += 1;     _x000D_
}_x000D_
counter += 1;_x000D_
}while(counter < recordSize);_x000D_
_x000D_
console.log(suggestion_set); _x000D_
_x000D_
_x000D_
_x000D_
/*_x000D_
*****_x000D_
LOGIC FOR PAGINATION_x000D_
*****_x000D_
*/_x000D_
_x000D_
var totalRecords = recordSize, pageSize = 6;_x000D_
var q = Math.floor(totalRecords/pageSize);_x000D_
var r = totalRecords%pageSize;_x000D_
var itr = 1;_x000D_
_x000D_
if(r==0 ||r==1 ||r==2) {_x000D_
itr=q;_x000D_
}_x000D_
else {_x000D_
itr=q+1;_x000D_
}_x000D_
console.log(itr);_x000D_
_x000D_
var output = "", pageCnt=1, newPage=false;_x000D_
_x000D_
if(totalRecords <= pageSize+2) {_x000D_
output += "\n";_x000D_
_x000D_
 for(var i=0; i < totalRecords; i++){_x000D_
  output += suggestion_set[i] + "\t";_x000D_
 }_x000D_
}_x000D_
_x000D_
else {_x000D_
 output += "\n";_x000D_
 for(var i=0; i<totalRecords; i++) {_x000D_
  //output += (i+1) + "\t";_x000D_
  if(pageCnt==1){_x000D_
  output += suggestion_set[i] + "\t";_x000D_
  if((i+1)==(pageSize+1)) {_x000D_
  output += "Next" + "\t";_x000D_
  pageCnt++;_x000D_
  newPage=true;_x000D_
 }_x000D_
}_x000D_
else {_x000D_
if(newPage) {_x000D_
output += "\n" + "Previous" + "\t";_x000D_
newPage = false;_x000D_
}_x000D_
output += suggestion_set[i] + "\t";_x000D_
if((i+1)==(pageSize*pageCnt+1) && (pageSize*pageCnt+1)<totalRecords) {_x000D_
if((i+2) == (pageSize*pageCnt+2) && pageCnt==itr) {_x000D_
output += (suggestion_set[i] + 1) + "\t";_x000D_
break;_x000D_
}_x000D_
else {_x000D_
output += "Next" + "\t";_x000D_
pageCnt++;_x000D_
newPage=true;_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
console.log(output);
_x000D_
_x000D_
_x000D_

Error ITMS-90717: "Invalid App Store Icon"

I had this problem and it was because my app store icon wasn't explicitly listed in my config.xml. Once I added the line

<icon height="1024" src="www/res/icon/ios/icon-1024.png" width="1024" />,

cordova copied it over correctly without adding an alpha channel.

How to get the last char of a string in PHP?

Or by direct string access:

$string[strlen($string)-1];

Note that this doesn't work for multibyte strings. If you need to work with multibyte string, consider using the mb_* string family of functions.

As of PHP 7.1.0 negative numeric indices are also supported, e.g just $string[-1];

How can I detect whether an iframe is loaded?

I imagine this like that:

<html>
<head>
<script>
var frame_loaded = 0;
function setFrameLoaded()
{
   frame_loaded = 1;
   alert("Iframe is loaded");
}
$('#click').click(function(){
   if(frame_loaded == 1)
    console.log('iframe loaded')
   } else {
    console.log('iframe not loaded')
   }
})
</script>
</head>
<button id='click'>click me</button>

<iframe id='MainPopupIframe' onload='setFrameLoaded();' src='http://...' />...</iframe>

When should I use cross apply over inner join?

cross apply sometimes enables you to do things that you cannot do with inner join.

Example (a syntax error):

select F.* from sys.objects O  
inner join dbo.myTableFun(O.name) F   
on F.schema_id= O.schema_id

This is a syntax error, because, when used with inner join, table functions can only take variables or constants as parameters. (I.e., the table function parameter cannot depend on another table's column.)

However:

select F.* from sys.objects O  
cross apply ( select * from dbo.myTableFun(O.name) ) F  
where F.schema_id= O.schema_id

This is legal.

Edit: Or alternatively, shorter syntax: (by ErikE)

select F.* from sys.objects O  
cross apply dbo.myTableFun(O.name) F
where F.schema_id= O.schema_id

Edit:

Note: Informix 12.10 xC2+ has Lateral Derived Tables and Postgresql (9.3+) has Lateral Subqueries which can be used to a similar effect.

How can I use Html.Action?

You should look at the documentation for the Action method; it's explained well. For your case, this should work:

@Html.Action("GetOptions", new { pk="00", rk="00" });

The controllerName parameter will default to the controller from which Html.Action is being invoked. So if you're trying to invoke an action from another controller, you'll have to specify the controller name like so:

@Html.Action("GetOptions", "ControllerName", new { pk="00", rk="00" });

Passing arguments to C# generic new() of templated type

You need to add where T: new() to let the compiler know that T is guaranteed to provide a default constructor.

public static string GetAllItems<T>(...) where T: new()

UICollectionView Set number of columns

Its all about layout you want to draw. You can create custom class inheriting from UICollectionViewFlowLayout. Currently there is not any direct method to set columns. If you want to achieve this kind of functionality you need to do it manually. You need to handle it in your custom flow layout class.

Now question will arise how you will do it? If you dont want to disturb cell frame you can adjust

 collectionView:layout:minimumInteritemSpacingForSectionAtIndex:
 collectionView:layout:minimumLineSpacingForSectionAtIndex:

Another way is provide you own positions of cells. By overriding below two methods, which will get called during your layout formation.

  - (NSArray*)layoutAttributesForElementsInRect:(CGRect)rect
  - (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)path

UICollectionViewLayoutAttributes is class which will deal with cell position, frame, Zindex etc

Regex match digits, comma and semicolon?

You almost have it, you just left out 0 and forgot the quantifier.

word.matches("^[0-9,;]+$")

How do I include the string header?

You want to include <string> and use std::string:

#include <string>
#include <iostream>

int main()
{
    std::string s = "a string";
    std::cout << s << std::endl;
}

But what you really need to do is get an introductory level book. You aren't going to learn properly any other way, certainly not scrapping for information online.

Java 8: merge lists with stream API

In Java 8 we can use stream List1.stream().collect(Collectors.toList()).addAll(List2); Another option List1.addAll(List2)

DB2 Date format

SELECT VARCHAR_FORMAT(CURRENT TIMESTAMP, 'YYYYMMDD')
FROM SYSIBM.SYSDUMMY1

Should work on both Mainframe and Linux/Unix/Windows DB2. Info Center entry for VARCHAR_FORMAT().

What is the difference between <jsp:include page = ... > and <%@ include file = ... >?

In one reusable piece of code I use the directive <%@include file="reuse.html"%> and in the second I use the standard action <jsp:include page="reuse.html" />.

Let the code in the reusable file be:

<html>
<head>
    <title>reusable</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
    <img src="candle.gif" height="100" width="50"/> <br />
    <p><b>As the candle burns,so do I</b></p>
</body>

After running both the JSP files you see the same output and think if there was any difference between the directive and the action tag. But if you look at the generated servlet of the two JSP files, you will see the difference.

Here is what you will see when you use the directive:

out.write("<html>\r\n");
out.write("    <head>\r\n");
out.write("        <title>reusable</title>\r\n");
out.write("        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
out.write("    </head>\r\n");
out.write("    <body>\r\n");
out.write("        <img src=\"candle.gif\" height=\"100\" width=\"50\"/> <br />\r\n");
out.write("        <p><b>As the candle burns,so do I</b></p>\r\n");
out.write("    </body>\r\n");
out.write("</html>\r\n");
 

And this is what you will see for the used standard action in the second JSP file :

org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "reusable.html", out, false);

So now you know that the include directive inserts the source of reuse.html at translation time, but the action tag inserts the response of reuse.html at runtime.

If you think about it, there is an extra performance hit with every action tag (<jsp:include>). It means you can guarantee you will always have the latest content, but it increases performance cost.

Use LINQ to get items in one List<>, that are not in another List<>

If you override the equality of People then you can also use:

peopleList2.Except(peopleList1)

Except should be significantly faster than the Where(...Any) variant since it can put the second list into a hashtable. Where(...Any) has a runtime of O(peopleList1.Count * peopleList2.Count) whereas variants based on HashSet<T> (almost) have a runtime of O(peopleList1.Count + peopleList2.Count).

Except implicitly removes duplicates. That shouldn't affect your case, but might be an issue for similar cases.

Or if you want fast code but don't want to override the equality:

var excludedIDs = new HashSet<int>(peopleList1.Select(p => p.ID));
var result = peopleList2.Where(p => !excludedIDs.Contains(p.ID));

This variant does not remove duplicates.

Generating a list of pages (not posts) without the index file

I have never used jekyll, but it's main page says that it uses Liquid, and according to their docs, I think the following should work:

<ul> {% for page in site.pages %}     {% if page.title != 'index' %}     <li><div class="drvce"><a href="{{ page.url }}">{{ page.title }}</a></div></li>     {% endif %} {% endfor %} </ul> 

Express.js - app.listen vs server.listen

I came with same question but after google, I found there is no big difference :)

From Github

If you wish to create both an HTTP and HTTPS server you may do so with the "http" and "https" modules as shown here.

/**
 * Listen for connections.
 *
 * A node `http.Server` is returned, with this
 * application (which is a `Function`) as its
 * callback. If you wish to create both an HTTP
 * and HTTPS server you may do so with the "http"
 * and "https" modules as shown here:
 *
 *    var http = require('http')
 *      , https = require('https')
 *      , express = require('express')
 *      , app = express();
 *
 *    http.createServer(app).listen(80);
 *    https.createServer({ ... }, app).listen(443);
 *
 * @return {http.Server}
 * @api public
 */

app.listen = function(){
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

Also if you want to work with socket.io see their example

See this

I prefer app.listen() :)