Programs & Examples On #6502

The 6502, developed by MOS Technology, is an 8-bit microprocessor that was in common use as a microcomputer and video-game CPU from the late 1970s through to the early 1990s, notably powering products from Commodore, Apple, Atari, Acorn and Nintendo.

Failed to install Python Cryptography package with PIP and setup.py

This worked for me in El Capitan

brew install pkg-config libffi openssl
env LDFLAGS="-L$(brew --prefix openssl)/lib" CFLAGS="-I$(brew --prefix openssl)/include" pip install cryptography

You can also check the thread here : https://github.com/pyca/cryptography/issues/2350

ORA-06502: PL/SQL: numeric or value error: character string buffer too small

CHAR is a fixed-length data type that uses as much space as possible. So a:= a||'one '; will require more space than is available. Your problem can be reduced to the following example:

declare
  v_foo char(50);
begin
  v_foo := 'A';
  dbms_output.put_line('length of v_foo(A) = ' || length(v_foo));
  -- next line will raise:
  -- ORA-06502: PL/SQL: numeric or value error: character string buffer too small
  v_foo := v_foo || 'B';
  dbms_output.put_line('length of v_foo(AB) = ' || length(v_foo));  
end;
/

Never use char. For rationale check the following question (read also the links):

How to increase dbms_output buffer?

You can Enable DBMS_OUTPUT and set the buffer size. The buffer size can be between 1 and 1,000,000.

dbms_output.enable(buffer_size IN INTEGER DEFAULT 20000);
exec dbms_output.enable(1000000);

Check this

EDIT

As per the comment posted by Frank and Mat, you can also enable it with Null

exec dbms_output.enable(NULL);

buffer_size : Upper limit, in bytes, the amount of buffered information. Setting buffer_size to NULL specifies that there should be no limit. The maximum size is 1,000,000, and the minimum is 2,000 when the user specifies buffer_size (NOT NULL).

Encapsulation vs Abstraction?

Encapsulation is a strategy used as part of abstraction. Encapsulation refers to the state of objects - objects encapsulate their state and hide it from the outside; outside users of the class interact with it through its methods, but cannot access the classes state directly. So the class abstracts away the implementation details related to its state.

Abstraction is a more generic term, it can also be achieved by (amongst others) subclassing. For example, the interface List in the standard library is an abstraction for a sequence of items, indexed by their position, concrete examples of a List are an ArrayList or a LinkedList. Code that interacts with a List abstracts over the detail of which kind of a list it is using.

Abstraction is often not possible without hiding underlying state by encapsulation - if a class exposes its internal state, it can't change its inner workings, and thus cannot be abstracted.

Oracle 10g: Extract data (select) from XML (CLOB Type)

You can achieve with below queries

  1. select extract(xmltype(xml), '//fax/text()').getStringVal() from mytab;

  2. select extractvalue(xmltype(xml), '//fax') from mytab;

How to change the window title of a MATLAB plotting figure?

If you do not want to include that your code script (as advised by others above), then simply you may do the following after generating the figure window:

  1. Go to "Edit" in the figure window

  2. Go to "Figure Properties"

  3. At the bottom, you can type the name you want in "Figure Name" field. You can uncheck "Show Figure Number".

That's all.

Good luck.

How to query a CLOB column in Oracle

To add to the answer.

declare
v_result clob;
begin
---- some operation on v_result
dbms_lob.substr( v_result, 4000 ,length(v_result) - 3999 );

end;
/

In dbms_lob.substr

first parameter is clob which you want to extract .

Second parameter is how much length of clob you want to extract.

Third parameter is from which word you want to extract .

In above example i know my clob size is more than 50000 , so i want last 4000 character .

Unit Testing C Code

Minunit is an incredibly simple unit testing framework. I'm using it to unit test c microcontroller code for avr.

How to ORDER BY a SUM() in MySQL?

Don'y forget that if you are mixing grouped (ie. SUM) fields and non-grouped fields, you need to GROUP BY one of the non-grouped fields.

Try this:

SELECT SUM(something) AS fieldname
FROM tablename
ORDER BY fieldname

OR this:

SELECT Field1, SUM(something) AS Field2
FROM tablename
GROUP BY Field1
ORDER BY Field2

And you can always do a derived query like this:

SELECT
   f1, f2
FROM
    (
        SELECT SUM(x+y) as f1, foo as F2
        FROM tablename 
        GROUP BY f2
    ) as table1
ORDER BY 
    f1

Many possibilities!

"Full screen" <iframe>

You can use this piece of code:

  <iframe src="http://example.com" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0%;left:0px;right:0px;bottom:0px" height="100%" width="100%"></iframe>

Git: Find the most recent common ancestor of two branches

git diff master...feature

shows all the new commits of your current (possibly multi-commit) feature branch.

man git-diff documents that:

git diff A...B

is the same as:

git diff $(git merge-base A B) B

but the ... is easier to type and remember.

As mentioned by Dave, the special case of HEAD can be omitted. So:

git diff master...HEAD

is the same as:

git diff master...

which is enough if the current branch is feature.

Finally, remember that order matters! Doing git diff feature...master will show changes that are on master not on feature.

I wish more git commands would support that syntax, but I don't think they do. And some even have different semantics for ...: What are the differences between double-dot ".." and triple-dot "..." in Git commit ranges?

Calling a function within a Class method?

  class sampleClass
    { 
        public function f1()
        {
           return "f1 run";
        }

        public function f2()
        {
           echo ("f2 run" );
           $result =  $this->f1();
           echo ($result);
        }   

    f2();  

    }

output :

f2 run f1 run

In angular $http service, How can I catch the "status" of error?

The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. Have a look at the docs https://docs.angularjs.org/api/ng/service/$http

Now the right way to use is:

// Simple GET request example:
$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
});

The response object has these properties:

  • data – {string|Object} – The response body transformed with the transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.
  • statusText – {string} – HTTP status text of the response.

A response status code between 200 and 299 is considered a success status and will result in the success callback being called.

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

Simple method to get the records count:

df.count()[0]

Read Post Data submitted to ASP.Net Form

if (!string.IsNullOrEmpty(Request.Form["username"])) { ... }

username is the name of the input on the submitting page. The password can be obtained the same way. If its not null or empty, it exists, then log in the user (I don't recall the exact steps for ASP.NET Membership, assuming that's what you're using).

jQuery - determine if input element is textbox or select list

If you just want to check the type, you can use jQuery's .is() function,

Like in my case I used below,

if($("#id").is("select")) {
 alert('Select'); 
else if($("#id").is("input")) {
 alert("input");
}

django: TypeError: 'tuple' object is not callable

You're missing comma (,) inbetween:

>>> ((1,2) (2,3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

Put comma:

>>> ((1,2), (2,3))
((1, 2), (2, 3))

Load json from local file with http.get() in angular 2

MY OWN SOLUTION

I created a new component called test in this folder:

enter image description here

I also created a mock called test.json in the assests folder created by angular cli (important):

enter image description here

This mock looks like this:

[
        {
            "id": 1,
            "name": "Item 1"
        },
        {
            "id": 2,
            "name": "Item 2"
        },
        {
            "id": 3,
            "name": "Item 3"
        }
]

In the controller of my component test import follow rxjs like this

import 'rxjs/add/operator/map'

This is important, because you have to map your response from the http get call, so you get a json and can loop it in your ngFor. Here is my code how I load the mock data. I used http get and called my path to the mock with this path this.http.get("/assets/mock/test/test.json"). After this i map the response and subscribe it. Then I assign it to my variable items and loop it with ngFor in my template. I also export the type. Here is my whole controller code:

import { Component, OnInit } from "@angular/core";
import { Http, Response } from "@angular/http";
import 'rxjs/add/operator/map'

export type Item = { id: number, name: string };

@Component({
  selector: "test",
  templateUrl: "./test.component.html",
  styleUrls: ["./test.component.scss"]
})
export class TestComponent implements OnInit {
  items: Array<Item>;

  constructor(private http: Http) {}

  ngOnInit() {
    this.http
      .get("/assets/mock/test/test.json")
      .map(data => data.json() as Array<Item>)
      .subscribe(data => {
        this.items = data;
        console.log(data);
      });
  }
}

And my loop in it's template:

<div *ngFor="let item of items">
  {{item.name}}
</div>

It works as expected! I can now add more mock files in the assests folder and just change the path to get it as json. Notice that you have also to import the HTTP and Response in your controller. The same in you app.module.ts (main) like this:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule, JsonpModule } from '@angular/http';


import { AppComponent } from './app.component';
import { TestComponent } from './components/molecules/test/test.component';


@NgModule({
  declarations: [
    AppComponent,
    TestComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    JsonpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

CREATE FILE encountered operating system error 5(failed to retrieve text for this error. Reason: 15105)

if you have mount points add the the SQL server service account to volume security accordingly

height style property doesn't work in div elements

This worked for me:

min-height: 14px;
height: 14px;

How can I show dots ("...") in a span with hidden overflow?

Thanks a lot @sandeep for his answer.

My problem was that I want to show / hide text on span with mouse click. So by default short text with dots is shown and by clicking long text appears. Clicking again hides that long text and shows short one again.

Quite easy thing to do: just add / remove class with text-overflow:ellipsis.

HTML:

<span class="spanShortText cursorPointer"  onclick="fInventoryShippingReceiving.ShowHideTextOnSpan(this);">Some really long description here</span>

CSS (same as @sandeep with .cursorPointer added)

.spanShortText {
  display: inline-block;
  width: 100px;
  white-space: nowrap;
  overflow: hidden !important;
  text-overflow: ellipsis;
}

.cursorPointer {
  cursor: pointer;
}

JQuery part - basically just removes / adds class cSpanShortText.

  function ShowHideTextOnSpan(element) {
    var cSpanShortText = 'spanShortText';
    var $el = $(element);
    if ($el.hasClass(cSpanShortText)) {
      $el.removeClass(cSpanShortText)
    } else {
      $el.addClass(cSpanShortText);
    }
  }

Automatic confirmation of deletion in powershell

The default is: no prompt.

You can enable it with -Confirm or disable it with -Confirm:$false

However, it will still prompt, when the target:

  • is a directory
  • and it is not empty
  • and the -Recurse parameter is not specified.

-Force is required to also remove hidden and read-only items etc.

To sum it up:

Remove-Item -Recurse -Force -Confirm:$false

...should cover all scenarios.

PHP, How to get current date in certain format

I belive the answer is:

echo date('Y-m-d H:i:s');

What does '?' do in C++?

Just a note, if you ever see this:

a = x ? : y;

It's a GNU extension to the standard (see https://gcc.gnu.org/onlinedocs/gcc/Conditionals.html#Conditionals).

It is the same as

a = x ? x : y;

How to put two divs side by side

Based on the layout you gave you can use float left property in css.

HTML

<div id="header"> LOGO</div>
<div id="wrap">
<div id="box1"></div>
<div id="box2"></div>
<div id="clear"></div>
</div>
<div id="footer">Footer</div>

CSS

body{
margin:0px;
height: 100%;
}
#header {

background-color: black;
height: 50px;
color: white;
font-size:25px;

 }

#wrap {

margin-left:200px;
margin-top:300px;


 }
#box1 {
width:200px;
float: left;
height: 300px;
background-color: black;
margin-right: 20px;
}
#box2{
width: 200px;
float: left;
height: 300px;
background-color: blue;
}
#clear {
clear: both;
}
#footer {
width: 100%;
background-color: black;
height: 50px;
margin-top:300px;
color: white;
font-size:25px;
position: absolute;
}

Show or hide element in React

If you would like to see how to TOGGLE the display of a component checkout this fiddle.

http://jsfiddle.net/mnoster/kb3gN/16387/

var Search = React.createClass({
    getInitialState: function() {
        return { 
            shouldHide:false
        };
    },
    onClick: function() {
        console.log("onclick");
        if(!this.state.shouldHide){
            this.setState({
                shouldHide: true 
            })
        }else{
                    this.setState({
                shouldHide: false 
            })
        }
    },
render: function() {
    return (
      <div>
        <button onClick={this.onClick}>click me</button>
        <p className={this.state.shouldHide ? 'hidden' : ''} >yoyoyoyoyo</p>
      </div>
    );
}
});

ReactDOM.render( <Search /> , document.getElementById('container'));

Replace only text inside a div using jquery

Another approach is keep that element, change the text, then append that element back

const star_icon = $(li).find('.stars svg')
$(li).find('.stars').text(repo.stargazers_count).append(star_icon)

How do I check if an object has a key in JavaScript?

Try the JavaScript in operator.

if ('key' in myObj)

And the inverse.

if (!('key' in myObj))

Be careful! The in operator matches all object keys, including those in the object's prototype chain.

Use myObj.hasOwnProperty('key') to check an object's own keys and will only return true if key is available on myObj directly:

myObj.hasOwnProperty('key')

Unless you have a specific reason to use the in operator, using myObj.hasOwnProperty('key') produces the result most code is looking for.

How to use php serialize() and unserialize()

From http://php.net/manual/en/function.serialize.php :

Generates a storable representation of a value. This is useful for storing or passing PHP values around without losing their type and structure.

Essentially, it takes a php array or object and converts it to a string (which you can then transmit or store as you see fit).

Unserialize is used to convert the string back to an object.

How do I convert an interval into a number of hours with postgres?

select floor((date_part('epoch', order_time - '2016-09-05 00:00:00') / 3600)), count(*)
from od_a_week
group by floor((date_part('epoch', order_time - '2016-09-05 00:00:00') / 3600));

The ::int conversion follows the principle of rounding. If you want a different result such as rounding down, you can use the corresponding math function such as floor.

Error :- java runtime environment JRE or java development kit must be available in order to run eclipse

I had this problem before and I solved by :

Right click my computer -> properties -> Advanced system settings.

In both sections :

  • User variables for "YourUser" &
  • System variables

Update the PATH by adding to the end of it a ";" and your java bin folder location , mine was "C:\Program Files\Java\jdk1.7.0_51\bin"

If there is no path then create it using the NEW button, set "Variable Name " to PATH and "Value" to your java bin location.

You can replace your PATH if there is no need for it

NOTE : THE FOLDER BIN SHOULD CONTAIN javaw.exe

Form inside a table

If you want a "editable grid" i.e. a table like structure that allows you to make any of the rows a form, use CSS that mimics the TABLE tag's layout: display:table, display:table-row, and display:table-cell.

There is no need to wrap your whole table in a form and no need to create a separate form and table for each apparent row of your table.

Try this instead:

<style>
DIV.table 
{
    display:table;
}
FORM.tr, DIV.tr
{
    display:table-row;
}
SPAN.td
{
    display:table-cell;
}
</style>
...
<div class="table">
    <form class="tr" method="post" action="blah.html">
        <span class="td"><input type="text"/></span>
        <span class="td"><input type="text"/></span>
    </form>
    <div class="tr">
        <span class="td">(cell data)</span>
        <span class="td">(cell data)</span>
    </div>
    ...
</div>

The problem with wrapping the whole TABLE in a FORM is that any and all form elements will be sent on submit (maybe that is desired but probably not). This method allows you to define a form for each "row" and send only that row of data on submit.

The problem with wrapping a FORM tag around a TR tag (or TR around a FORM) is that it's invalid HTML. The FORM will still allow submit as usual but at this point the DOM is broken. Note: Try getting the child elements of your FORM or TR with JavaScript, it can lead to unexpected results.

Note that IE7 doesn't support these CSS table styles and IE8 will need a doctype declaration to get it into "standards" mode: (try this one or something equivalent)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Any other browser that supports display:table, display:table-row and display:table-cell should display your css data table the same as it would if you were using the TABLE, TR and TD tags. Most of them do.

Note that you can also mimic THEAD, TBODY, TFOOT by wrapping your row groups in another DIV with display: table-header-group, table-row-group and table-footer-group respectively.

NOTE: The only thing you cannot do with this method is colspan.

Check out this illustration: http://jsfiddle.net/ZRQPP/

open new tab(window) by clicking a link in jquery

Try this:

window.open(url, '_blank');

This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)

How do I declare and initialize an array in Java?

In Java 8 you can use something like this.

String[] strs = IntStream.range(0, 15)  // 15 is the size
    .mapToObj(i -> Integer.toString(i))
    .toArray(String[]::new);

How do I change the android actionbar title and icon

I used the following call inside onNavigationItemSelected:

HomeActivity.this.setTitle(item.getTitle());

How do I copy SQL Azure database to my local development server?

Copy Azure database data to local database: Now you can use the SQL Server Management Studio to do this as below:

  • Connect to the SQL Azure database.
  • Right click the database in Object Explorer.
  • Choose the option "Tasks" / "Deploy Database to SQL Azure".
  • In the step named "Deployment Settings", connect local SQL Server and create New database.

enter image description here

"Next" / "Next" / "Finish"

How to listen for changes to a MongoDB collection?

Actually, instead of watching output, why you dont get notice when something new is inserted by using middle-ware that was provided by mongoose schema

You can catch the event of insert a new document and do something after this insertion done

How to fix error Base table or view not found: 1146 Table laravel relationship table?

For solving your Base Table or view not found error you can do As @Alexey Mezenin said that change table name category_post to category_posts,

but if you don't want to change the name like in my case i am using inventory table so i don't want to suffix it by s so i will provide table name in model as protected $table = 'Table_name_as_you_want' and then there is no need to change table name:

Change your Model of the module in which you are getting error for example:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Inventory extends Model
{
    protected $table = 'inventory';

    protected $fillable = [
        'supply', 'order',
    ];
}

you have to provide table name in model then it will not give error.

PHP AES encrypt / decrypt

If you are using MCRYPT_RIJNDAEL_128, try rtrim($output, "\0\3"). If the length of the string is less than 16, the decrypt function will return a string with length of 16 characters, adding 03 at the end.

You can easily check this, e.g. by trying:

$string = "TheString";
$decrypted_string = decrypt_function($stirng, $key);

echo bin2hex($decrypted_string)."=".bin2hex("TheString");

How to check if String value is Boolean type in Java?

Something you should also take into consideration is character casing...

Instead of:

return value.equals("false") || value.equals("true");

Do this:

return value.equalsIgnoreCase("false") || value.equalsIgnoreCase("true");

WAMP shows error 'MSVCR100.dll' is missing when install

Just ran on this issue. Issue was at same OS (Win7 HB x64) as in this answer. I used gaurav's advice and successfully started WAMP.

I wanted to add that you don't need Visual C++ 2010 versions when using 2012 version (at least in this case).

How to get the date from jQuery UI datepicker

NamingException's answer worked for me. Except I used

var date = $("#date").dtpicker({ dateFormat: 'dd,MM,yyyy' }).val()

datepicker didn't work but dtpicker did.

How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

in SQL*Plus you could also use a REFCURSOR variable:

SQL> VARIABLE x REFCURSOR
SQL> DECLARE
  2   V_Sqlstatement Varchar2(2000);
  3  BEGIN
  4   V_Sqlstatement := 'SELECT * FROM DUAL';
  5   OPEN :x for v_Sqlstatement;
  6  End;
  7  /

ProcÚdure PL/SQL terminÚe avec succÞs.

SQL> print x;

D
-
X

Most efficient conversion of ResultSet to JSON?

Two things that will make this faster are:

Move your call to rsmd.getColumnCount() out of the while loop. The column count should not vary across rows.

For each column type, you end up calling something like this:

obj.put(column_name, rs.getInt(column_name));

It will be slightly faster to use the column index to retrieve the column value:

obj.put(column_name, rs.getInt(i));

How to create and handle composite primary key in JPA

Key class:

@Embeddable
@Access (AccessType.FIELD)
public class EntryKey implements Serializable {

    public EntryKey() {
    }

    public EntryKey(final Long id, final Long version) {
        this.id = id;
        this.version = version;
    }

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getVersion() {
        return this.version;
    }

    public void setVersion(Long version) {
        this.version = version;
    }

    public boolean equals(Object other) {
        if (this == other)
            return true;
        if (!(other instanceof EntryKey))
            return false;
        EntryKey castOther = (EntryKey) other;
        return id.equals(castOther.id) && version.equals(castOther.version);
    }

    public int hashCode() {
        final int prime = 31;
        int hash = 17;
        hash = hash * prime + this.id.hashCode();
        hash = hash * prime + this.version.hashCode();
        return hash;
    }

    @Column (name = "ID")
    private Long id;
    @Column (name = "VERSION")
    private Long operatorId;
}

Entity class:

@Entity
@Table (name = "YOUR_TABLE_NAME")
public class Entry implements Serializable {

    @EmbeddedId
    public EntryKey getKey() {
        return this.key;
    }

    public void setKey(EntryKey id) {
        this.id = id;
    }

    ...

    private EntryKey key;
    ...
}

How can I duplicate it with another Version?

You can detach entity which retrieved from provider, change the key of Entry and then persist it as a new entity.

Getting "net::ERR_BLOCKED_BY_CLIENT" error on some AJAX calls

As it has been explained here, beside of multiple extensions that perform ad or script blocking you may aware that this may happen by file names as below:

Particularly in the AdBlock Plus the character string "-300x600" is causing the Failed to Load Resource ERR_BLOCKED_BY_CLIENT problem.

As shown in the picture, some of the images were blocked because of the '-300x600' pattern in their name, that particular text pattern matches an expression list pattern in the AdBlock Plus.

ERR_BLOCKED_BY_CLIENT problem

How to add an UIViewController's view as subview

As of iOS 5, Apple now allows you to make custom containers for the purpose of adding a UIViewController to another UIViewController particularly via methods such as addChildViewController so it is indeed possible to nest UIViewControllers

EDIT: Including in-place summary so as to avoid link breakage

I quote:

iOS provides many standard containers to help you organize your apps. However, sometimes you need to create a custom workflow that doesn’t match that provided by any of the system containers. Perhaps in your vision, your app needs a specific organization of child view controllers with specialized navigation gestures or animation transitions between them. To do that, you implement a custom container - Tell me more...

...and:

When you design a container, you create explicit parent-child relationships between your container, the parent, and other view controllers, its children - Tell me more

Sample (courtesy of Apple docs) Adding another view controller’s view to the container’s view hierarchy

- (void) displayContentController: (UIViewController*) content
{
   [self addChildViewController:content];                 
   content.view.frame = [self frameForContentController]; 
   [self.view addSubview:self.currentClientView];
   [content didMoveToParentViewController:self];          
}

Get operating system info

If you want very few info like a class in your html for common browsers for instance, you could use:

function get_browser()
{
    $browser = '';
    $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
    if (preg_match('~(?:msie ?|trident.+?; ?rv: ?)(\d+)~', $ua, $matches)) $browser = 'ie ie'.$matches[1];
    elseif (preg_match('~(safari|chrome|firefox)~', $ua, $matches)) $browser = $matches[1];

    return $browser;
}

which will return 'safari' or 'firefox' or 'chrome', or 'ie ie8', 'ie ie9', 'ie ie10', 'ie ie11'.

Highcharts - how to have a chart with dynamic height?

I had the same problem and I fixed it with:

<div id="container" style="width: 100%; height: 100%; position:absolute"></div>

The chart fits perfect to the browser even if I resize it. You can change the percentage according to your needs.

VBA, if a string contains a certain letter

Try:

If myString like "*A*" Then

Can't create handler inside thread that has not called Looper.prepare()

 runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(mContext, "Message", Toast.LENGTH_SHORT).show();
            }
        });

In Chart.js set chart title, name of x axis and y axis?

just use this:

<script>
  var ctx = document.getElementById("myChart").getContext('2d');
  var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ["1","2","3","4","5","6","7","8","9","10","11",],
      datasets: [{
        label: 'YOUR LABEL',
        backgroundColor: [
          "#566573",
          "#99a3a4",
          "#dc7633",
          "#f5b041",
          "#f7dc6f",
          "#82e0aa",
          "#73c6b6",
          "#5dade2",
          "#a569bd",
          "#ec7063",
          "#a5754a"
        ],
        data: [12, 19, 3, 17, 28, 24, 7, 2,4,14,6],            
      },]
    },
    //HERE COMES THE AXIS Y LABEL
    options : {
      scales: {
        yAxes: [{
          scaleLabel: {
            display: true,
            labelString: 'probability'
          }
        }]
      }
    }
  });
</script>

How to create cross-domain request?

@RestController
@RequestMapping(value = "/profile")
@CrossOrigin(origins="*")
public class UserProfileController {

SpringREST provides @CrossOrigin annotations where (origins="*") allow access to REST APIS from any source.

We can add it to respective API or entire RestController.

Add default value of datetime field in SQL Server to a timestamp

In SQLPlus while creating a table it is be like as

SQL> create table Test

 ( Test_ID number not null,
   Test_Date date default sysdate not null );

SQL> insert into Test(id) values (1);

 Test_ID Test_Date
       1 08-MAR-19

How to split the filename from a full path in batch?

@echo off
Set filename=C:\Documents and Settings\All Users\Desktop\Dostips.cmd
For %%A in ("%filename%") do (
    Set Folder=%%~dpA
    Set Name=%%~nxA
)
echo.Folder is: %Folder%
echo.Name is: %Name%

But I can't take credit for this; Google found this at http://www.dostips.com/forum/viewtopic.php?f=3&t=409

How to select all checkboxes with jQuery?

This code works fine with me

<script type="text/javascript">
$(document).ready(function(){ 
$("#select_all").change(function(){
  $(".checkbox_class").prop("checked", $(this).prop("checked"));
  });
});
</script>

you only need to add class checkbox_class to all checkbox

Easy and simple :D

Print array to a file

file_put_contents($file, print_r($array, true), FILE_APPEND)

What is the opposite of :hover (on mouse leave)?

Just use CSS transitions instead of animations.

A {
    color: #999;
    transition: color 1s ease-in-out;
}

A:hover {
    color: #000;
}

Live demo

Array initialization syntax when not in a declaration

I'll try to answer the why question: The Java array is very simple and rudimentary compared to classes like ArrayList, that are more dynamic. Java wants to know at declaration time how much memory should be allocated for the array. An ArrayList is much more dynamic and the size of it can vary over time.

If you initialize your array with the length of two, and later on it turns out you need a length of three, you have to throw away what you've got, and create a whole new array. Therefore the 'new' keyword.

In your first two examples, you tell at declaration time how much memory to allocate. In your third example, the array name becomes a pointer to nothing at all, and therefore, when it's initialized, you have to explicitly create a new array to allocate the right amount of memory.

I would say that (and if someone knows better, please correct me) the first example

AClass[] array = {object1, object2}

actually means

AClass[] array = new AClass[]{object1, object2};

but what the Java designers did, was to make quicker way to write it if you create the array at declaration time.

The suggested workarounds are good. If the time or memory usage is critical at runtime, use arrays. If it's not critical, and you want code that is easier to understand and to work with, use ArrayList.

Create a file if one doesn't exist - C

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

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

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

A complete example

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

Posting form to different MVC post action depending on the clicked submit button

you can use ajax calls to call different methods without a postback

$.ajax({
    type: "POST",
     url: "@(Url.Action("Action", "Controller"))",
     data: {id: 'id', id1: 'id1' },
     contentType: "application/json; charset=utf-8",
     cache: false,
     async: true,
     success: function (result) {
        //do something
     }
});

VBA Subscript out of range - error 9

Suggest the following simplification: capture return value from Workbooks.Add instead of subscripting Windows() afterward, as follows:

Set wkb = Workbooks.Add
wkb.SaveAs ...

wkb.Activate ' instead of Windows(expression).Activate


General Philosophy Advice:

Avoid use Excel's built-ins: ActiveWorkbook, ActiveSheet, and Selection: capture return values, and, favor qualified expressions instead.

Use the built-ins only once and only in outermost macros(subs) and capture at macro start, e.g.

Set wkb = ActiveWorkbook
Set wks = ActiveSheet
Set sel = Selection

During and within macros do not rely on these built-in names, instead capture return values, e.g.

Set wkb = Workbooks.Add 'instead of Workbooks.Add without return value capture
wkb.Activate 'instead of Activeworkbook.Activate

Also, try to use qualified expressions, e.g.

wkb.Sheets("Sheet3").Name = "foo" ' instead of Sheets("Sheet3").Name = "foo"

or

Set newWks = wkb.Sheets.Add
newWks.Name = "bar" 'instead of ActiveSheet.Name = "bar"

Use qualified expressions, e.g.

newWks.Name = "bar" 'instead of `xyz.Select` followed by Selection.Name = "bar" 

These methods will work better in general, give less confusing results, will be more robust when refactoring (e.g. moving lines of code around within and between methods) and, will work better across versions of Excel. Selection, for example, changes differently during macro execution from one version of Excel to another.

Also please note that you'll likely find that you don't need to .Activate nearly as much when using more qualified expressions. (This can mean the for the user the screen will flicker less.) Thus the whole line Windows(expression).Activate could simply be eliminated instead of even being replaced by wkb.Activate.

(Also note: I think the .Select statements you show are not contributing and can be omitted.)

(I think that Excel's macro recorder is responsible for promoting this more fragile style of programming using ActiveSheet, ActiveWorkbook, Selection, and Select so much; this style leaves a lot of room for improvement.)

How to set entire application in portrait mode only?

You can set this in your manifest file..

android:name=".your launching activity name"
android:screenOrientation="portrait"

and you can also achive the same by writing the code in your class file like:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

Adding images to an HTML document with javascript

or you can just

<script> 
document.write('<img src="/*picture_location_(you can just copy the picture and paste   it into the script)*\"')
document.getElementById('pic')
</script>
<div id="pic">
</div>

SASS and @font-face

For those looking for an SCSS mixin instead, including woff2:

@mixin fface($path, $family, $type: '', $weight: 400, $svg: '', $style: normal) {
  @font-face {
    font-family: $family;
    @if $svg == '' {
      // with OTF without SVG and EOT
      src: url('#{$path}#{$type}.otf') format('opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype');
    } @else {
      // traditional src inclusions
      src: url('#{$path}#{$type}.eot');
      src: url('#{$path}#{$type}.eot?#iefix') format('embedded-opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype'), url('#{$path}#{$type}.svg##{$svg}') format('svg');
    }
    font-weight: $weight;
    font-style: $style;
  }
}
// ========================================================importing
$dir: '/assets/fonts/';
$famatic: 'AmaticSC';
@include fface('#{$dir}amatic-sc-v11-latin-regular', $famatic, '', 400, $famatic);

$finter: 'Inter';
// adding specific types of font-weights
@include fface('#{$dir}#{$finter}', $finter, '-Thin-BETA', 100);
@include fface('#{$dir}#{$finter}', $finter, '-Regular', 400);
@include fface('#{$dir}#{$finter}', $finter, '-Medium', 500);
@include fface('#{$dir}#{$finter}', $finter, '-Bold', 700);
// ========================================================usage
.title {
  font-family: Inter;
  font-weight: 700; // Inter-Bold font is loaded
}
.special-title {
  font-family: AmaticSC;
  font-weight: 700; // default font is loaded
}

The $type parameter is useful for stacking related families with different weights.

The @if is due to the need of supporting the Inter font (similar to Roboto), which has OTF but doesn't have SVG and EOT types at this time.

If you get a can't resolve error, remember to double check your fonts directory ($dir).

How to cast or convert an unsigned int to int in C?

Unsigned int can be converted to signed (or vice-versa) by simple expression as shown below :

unsigned int z;
int y=5;
z= (unsigned int)y;   

Though not targeted to the question, you would like to read following links :

Can an html element have multiple ids?

No, you should use nested DIVs if you want to head down that path. Besides, even if you could, imagine the confusion it would cause when you run document.getElementByID(). What ID is it going to grab if there are multiple ones?

On a slightly related topic, you can add multiple classes to a DIV. See Eric Myers discussion at,

http://meyerweb.com/eric/articles/webrev/199802a.html

Convert a bitmap into a byte array

Use a MemoryStream instead of a FileStream, like this:

MemoryStream ms = new MemoryStream();
bmp.Save (ms, ImageFormat.Jpeg);
byte[] bmpBytes = ms.ToArray();

How to generate and manually insert a uniqueidentifier in sql server?

Kindly check Column ApplicationId datatype in Table aspnet_Users , ApplicationId column datatype should be uniqueidentifier .

*Your parameter order is passed wrongly , Parameter @id should be passed as first argument, but in your script it is placed in second argument..*

So error is raised..

Please refere sample script:

DECLARE @id uniqueidentifier
SET @id = NEWID()
Create Table #temp1(AppId uniqueidentifier)

insert into #temp1 values(@id)

Select * from #temp1

Drop Table #temp1

How to include JavaScript file or library in Chrome console?

In the modern browsers you can use the fetch to download resource (Mozilla docs) and then eval to execute it.

For example to download Angular1 you need to type:

fetch('https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js')
    .then(response => response.text())
    .then(text => eval(text))
    .then(() => { /* now you can use your library */ })

Check file size before upload

I created a jQuery version of PhpMyCoder's answer:

$('form').submit(function( e ) {    
    if(!($('#file')[0].files[0].size < 10485760 && get_extension($('#file').val()) == 'jpg')) { // 10 MB (this size is in bytes)
        //Prevent default and display error
        alert("File is wrong type or over 10Mb in size!");
        e.preventDefault();
    }
});

function get_extension(filename) {
    return filename.split('.').pop().toLowerCase();
}

How can I do width = 100% - 100px in CSS?

Could you nest a div with margin-left: 50px; and margin-right: 50px; inside a <div> with width: 100%;?

how to run two commands in sudo?

The -s option didn't work for me, -i did.

Here is an example of how I could update the log size from my bash:

sudo -u [user] -i -- sh -c 'db2 connect to [database name];db2 update db cfg for [database name] using logsecond 20;db2 update db cfg for [database name] using logprimary 20;'

javascript - match string against the array of regular expressions

Consider breaking this problem up into two pieces:

  1. filter out the items that match the given regular expression
  2. determine if that filtered list has 0 matches in it
const sampleStringData = ["frog", "pig", "tiger"];

const matches = sampleStringData.filter((animal) => /any.regex.here/.test(animal));

if (matches.length === 0) {
  console.log("No matches");
}

How do I download a file from the internet to my linux server with Bash

You can use the command wget to download from command line. Specifically, you could use

wget http://download.oracle.com/otn-pub/java/jdk/7u10-b18/jdk-7u10-linux-x64.tar.gz

However because Oracle requires you to accept a license agreement this may not work (and I am currently unable to test it).

How to create a inner border for a box in html?

  1. Use dashed border style for outline.
  2. Draw background-color with :before or :after pseudo element.

Note: This method will allow you to have maximum browser support.

Output Image:

Output Image

_x000D_
_x000D_
* {box-sizing: border-box;}_x000D_
_x000D_
.box {_x000D_
  border: 1px dashed #fff;_x000D_
  position: relative;_x000D_
  height: 160px;_x000D_
  width: 350px;_x000D_
  margin: 20px;_x000D_
}_x000D_
_x000D_
.box:before {_x000D_
  position: absolute;_x000D_
  background: black;_x000D_
  content: '';_x000D_
  bottom: -10px;_x000D_
  right: -10px;_x000D_
  left: -10px;_x000D_
  top: -10px;_x000D_
  z-index: -1;_x000D_
}
_x000D_
<div class="box">_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to make a radio button unchecked by clicking it?

Most of the modern day browsers consider checked="anything" as checked="true".

You might have to remove the checked attribute if that makes sense in your case, one of which might be related to when you load the page.

$(this).removeAttr('checked')

This might help you in cases when you want your radio button to be checked adhering to some condition. You can simply remove the attribute to achieve that.

PS: Not helpful in all the cases.

How to remove .html from URL?

To remove the .html extension from your URLs, you can use the following code in root/htaccess :

#mode_rerwrite start here

RewriteEngine On

# does not apply to existing directores, meaning that if the folder exists on server then don't change anything and don't run the rule.

RewriteCond %{REQUEST_FILENAME} !-d

#Check for file in directory with .html extension 

RewriteCond %{REQUEST_FILENAME}\.html !-f

#Here we actually show the page that has .html extension

RewriteRule ^(.*)$ $1.html [NC,L]

Thanks

Take a full page screenshot with Firefox on the command-line

Firefox Screenshots is a new tool that ships with Firefox. It is not a developer tool, it is aimed at end-users of the browser.

To take a screenshot, click on the page actions menu in the address bar, and click "take a screenshot". If you then click "Save full page", it will save the full page, scrolling for you.


(source: mozilla.net)

How do you import an Eclipse project into Android Studio now?

The best way to bring in an Eclipse/ADT project is to import it directly into Android Studio. At first GO to Eclipse project & delete the project.properties file.

After that, open the Android studio Tool & import Eclipse project(Eclipse ADT, Gradle etc).

How to fix missing dependency warning when using useEffect React Hook?

Actually the warnings are very useful when you develop with hooks. but in some cases, it can needle you. especially when you do not need to listen for dependencies change.

If you don't want to put fetchBusinesses inside the hook's dependencies, you can simply pass it as an argument to the hook's callback and set the main fetchBusinesses as the default value for it like this

useEffect((fetchBusinesses = fetchBusinesses) => {
   fetchBusinesses();
}, []);

It's not best practice but it could be useful in some cases.

Also as Shubnam wrote, you can add below code to tell ESLint to ignore the checking for your hook.

// eslint-disable-next-line react-hooks/exhaustive-deps

Get current time in hours and minutes

I have another solution for your question .

In the first when use date the output is like this :

Thu 28 Jan 2021 22:29:40 IST

Then if you want only to show current time in hours and minutes you can use this command :

date | cut -d " " -f5 | cut -d ":" -f1-2 

Then the output :

22:29

Getters \ setters for dummies

I think the first article you link to states it pretty clearly:

The obvious advantage to writing JavaScript in this manner is that you can use it obscure values that you don't want the user to directly access.

The goal here is to encapsulate and abstract away the fields by only allowing access to them thru a get() or set() method. This way, you can store the field/data internally in whichever way you want, but outside components are only away of your published interface. This allows you to make internal changes without changing external interfaces, to do some validation or error-checking within the set() method, etc.

How do I call a JavaScript function on page load?

If you want the onload method to take parameters, you can do something similar to this:

window.onload = function() {
  yourFunction(param1, param2);
};

This binds onload to an anonymous function, that when invoked, will run your desired function, with whatever parameters you give it. And, of course, you can run more than one function from inside the anonymous function.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

you need to add jar file in your build path..

commons-dbcp-1.1-RC2.jar

or any version of that..!!!!

ADDED : also make sure you have commons-pool-1.1.jar too in your build path.

ADDED: sorry saw complete list of jar late... may be version clashes might be there.. better check out..!!! just an assumption.

Slick Carousel Uncaught TypeError: $(...).slick is not a function

In Laravel i solve with:

app.sccs

// slick
@import "~slick-carousel/slick/slick";
@import "~slick-carousel/slick/slick-theme";

bootstrap.js

try {
   window.Popper = require('popper.js').default;
   window.$ = window.jQuery = require('jquery');
   require('bootstrap');
   require('slick')
   require('slick-carousel')
} 

package.json

"jquery": "^3.2",
"slick": "^1.12.2",
"slick-carousel": "^1.6.0"

example.js

$('.testimonial-active').slick({
    dots: false,
    arrows: true,
    prevArrow: '<span class="prev"><i class="mdi mdi-arrow-left"></i></span>',
    nextArrow: '<span class="next"><i class="mdi mdi-arrow-right"></i></span>',
    infinite: true,
    autoplay: true,
    autoplaySpeed: 5000,
    speed: 800,
    slidesToShow: 1,
});

Add User to Role ASP.NET Identity

This one works for me. You can see this code on AccountController -> Register

var user = new JobUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
    //add this to add role to user
     await UserManager.AddToRoleAsync(user.Id, "Name of your role");
}

but the role name must exist in your AspNetRoles table.

How to redirect to a 404 in Rails?

The selected answer doesn't work in Rails 3.1+ as the error handler was moved to a middleware (see github issue).

Here's the solution I found which I'm pretty happy with.

In ApplicationController:

  unless Rails.application.config.consider_all_requests_local
    rescue_from Exception, with: :handle_exception
  end

  def not_found
    raise ActionController::RoutingError.new('Not Found')
  end

  def handle_exception(exception=nil)
    if exception
      logger = Logger.new(STDOUT)
      logger.debug "Exception Message: #{exception.message} \n"
      logger.debug "Exception Class: #{exception.class} \n"
      logger.debug "Exception Backtrace: \n"
      logger.debug exception.backtrace.join("\n")
      if [ActionController::RoutingError, ActionController::UnknownController, ActionController::UnknownAction].include?(exception.class)
        return render_404
      else
        return render_500
      end
    end
  end

  def render_404
    respond_to do |format|
      format.html { render template: 'errors/not_found', layout: 'layouts/application', status: 404 }
      format.all { render nothing: true, status: 404 }
    end
  end

  def render_500
    respond_to do |format|
      format.html { render template: 'errors/internal_server_error', layout: 'layouts/application', status: 500 }
      format.all { render nothing: true, status: 500}
    end
  end

and in application.rb:

config.after_initialize do |app|
  app.routes.append{ match '*a', :to => 'application#not_found' } unless config.consider_all_requests_local
end

And in my resources (show, edit, update, delete):

@resource = Resource.find(params[:id]) or not_found

This could certainly be improved, but at least, I have different views for not_found and internal_error without overriding core Rails functions.

React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

I confirm some methods proposed here that also worked for me : you have to put your local .json file in your public directory where fetch() is looking for (looking in http://localhost:3000/) for example : I use this fetch() in my src/App.js file:

componentDidMount(){
  fetch('./data/json-data.json')
  .then ( resp1 => resp1.json() )
  .then ( users1 => this.setState( {cards : users1} ) )
}

so I created public/data/json-data.json

and everything was fine then :)

Selecting one row from MySQL using mysql_* API

$result = mysql_query("SELECT option_value FROM wp_10_options WHERE option_name='homepage'");
$row = mysql_fetch_assoc($result);
echo $row['option_value'];

WPF User Control Parent

The Window.GetWindow(userControl) will return the actual window only after the window was initialized (InitializeComponent() method finished).

This means, that if your user control is initialized together with its window (for instance you put your user control into the window's xaml file), then on the user control's OnInitialized event you will not get the window (it will be null), cause in that case the user control's OnInitialized event fires before the window is initialized.

This also means that if your user control is initialized after its window, then you can get the window already in the user control's constructor.

How to convert an xml string to a dictionary?

xmltodict (full disclosure: I wrote it) does exactly that:

xmltodict.parse("""
<?xml version="1.0" ?>
<person>
  <name>john</name>
  <age>20</age>
</person>""")
# {u'person': {u'age': u'20', u'name': u'john'}}

How do I zip two arrays in JavaScript?

Use the map method:

_x000D_
_x000D_
var a = [1, 2, 3]_x000D_
var b = ['a', 'b', 'c']_x000D_
_x000D_
var c = a.map(function(e, i) {_x000D_
  return [e, b[i]];_x000D_
});_x000D_
_x000D_
console.log(c)
_x000D_
_x000D_
_x000D_

DEMO

Add params to given URL in Python

Based on this answer, one-liner for simple cases (Python 3 code):

from urllib.parse import urlparse, urlencode


url = "https://stackoverflow.com/search?q=question"
params = {'lang':'en','tag':'python'}

url += ('&' if urlparse(url).query else '?') + urlencode(params)

or:

url += ('&', '?')[urlparse(url).query == ''] + urlencode(params)

Sqlite: CURRENT_TIMESTAMP is in GMT, not the timezone of the machine

In the (admitted rare) case that a local datatime is wanted (I, for example, store local time in one of my database since all I care is what time in the day is was and I don't keep track of where I was in term of time zones...), you can define the column as

"timestamp" TEXT DEFAULT (strftime('%Y-%m-%dT%H:%M','now', 'localtime'))

The %Y-%m-%dT%H:%M part is of course optional; it is just how I like my time to be stored. [Also, if my impression is correct, there is no "DATETIME" datatype in sqlite, so it does not really matter whether TEXT or DATETIME is used as data type in column declaration.]

Why is textarea filled with mysterious white spaces?

I got the same problem, and the solution is very simple: don't start a new line! Although some of the previous answers can solve the problem, the idea is not stated clearly. The important understanding is, to get rid of the unintended spaces, never start a new line just after your start tag.

The following way is WRONG and will leave a lot of unwanted spaces before your text content:

 <textarea>
    text content // start with a new line will leave a lot of unwanted spaces
 </textarea>

The RIGHT WAY to do it is:

 <textarea>text content //put text content right after your start tag, no new line
 </textarea>

Is a Python list guaranteed to have its elements stay in the order they are inserted in?

You are confusing 'sets' and 'lists'. A set does not guarantee order, but lists do.

Sets are declared using curly brackets: {}. In contrast, lists are declared using square brackets: [].

mySet = {a, b, c, c}

Does not guarantee order, but list does:

myList = [a, b, c]

"An access token is required to request this resource" while accessing an album / photo with Facebook php sdk

Well, you are having a valid access token to access your information and not others( this is because you got logged in and you have given permission to access your information). But the picture owner has not done the same (logged in + permission ) and so you are getting a violation error.

To obtain permission see this link and decide what kind of informations you want from any user and decide the permissions. Later on embed this in your code. (In the login function call)

Thanks

Simple linked list in C++

Below is a sample linkedlist

    #include <string>
    #include <iostream>

    using namespace std;


    template<class T>
    class Node
    {
    public:
        Node();
        Node(const T& item, Node<T>* ptrnext = NULL);
        T value;
        Node<T> * next;
    };

    template<class T>
    Node<T>::Node()
    {
        value = NULL;
        next = NULL;
    }
    template<class T>
    Node<T>::Node(const T& item, Node<T>* ptrnext = NULL)
    {
        this->value = item;
        this->next = ptrnext;
    }

    template<class T>
    class LinkedListClass
    {
    private:
        Node<T> * Front;
        Node<T> * Rear;
        int Count;
    public:
        LinkedListClass();
        ~LinkedListClass();
        void InsertFront(const T Item);
        void InsertRear(const T Item);
        void PrintList();
    };
    template<class T>
    LinkedListClass<T>::LinkedListClass()
    {
        Front = NULL;
        Rear = NULL;
    }

    template<class T>
    void LinkedListClass<T>::InsertFront(const T  Item)
    {
        if (Front == NULL)
        {
            Front = new Node<T>();
            Front->value = Item;
            Front->next = NULL;
            Rear = new Node<T>();
            Rear = Front;
        }
        else
        {
            Node<T> * newNode = new Node<T>();
            newNode->value = Item;
            newNode->next = Front;
            Front = newNode;
        }
    }

    template<class T>
    void LinkedListClass<T>::InsertRear(const T  Item)
    {
        if (Rear == NULL)
        {
            Rear = new Node<T>();
            Rear->value = Item;
            Rear->next = NULL;
            Front = new Node<T>();
            Front = Rear;
        }
        else
        {
            Node<T> * newNode = new Node<T>();
            newNode->value = Item;
            Rear->next = newNode;
            Rear = newNode;
        }
    }
    template<class T>
    void LinkedListClass<T>::PrintList()
    {
        Node<T> *  temp = Front;
        while (temp->next != NULL)
        {
            cout << " " << temp->value << "";
            if (temp != NULL)
            {
                temp = (temp->next);
            }
            else
            {
                break;
            }
        }
    }

    int main()
    {
        LinkedListClass<int> * LList = new LinkedListClass<int>();
        LList->InsertFront(40);
        LList->InsertFront(30);
        LList->InsertFront(20);
        LList->InsertFront(10);
        LList->InsertRear(50);
        LList->InsertRear(60);
        LList->InsertRear(70);
        LList->PrintList();
    }

Getting time difference between two times in PHP

You can also use DateTime class:

$time1 = new DateTime('09:00:59');
$time2 = new DateTime('09:01:00');
$interval = $time1->diff($time2);
echo $interval->format('%s second(s)');

Result:

1 second(s)

ssh: Could not resolve hostname github.com: Name or service not known; fatal: The remote end hung up unexpectedly

Recently, I have seen this problem too. Below, you have my solution:

  1. ping github.com, if ping failed. it is DNS error.
  2. sudo vim /etc/resolv.conf, the add: nameserver 8.8.8.8 nameserver 8.8.4.4

Or it can be a genuine network issue. Restart your network-manager using sudo service network-manager restart or fix it up


I have just received this error after switching from HTTPS to SSH (for my origin remote). To fix, I simply ran the following command (for each repo):

ssh -T [email protected]

Upon receiving a successful response, I could fetch/push to the repo with ssh.

I took that command from Git's Testing your SSH connection guide, which is part of the greater Connecting to GitHub with with SSH guide.

Call a React component method from outside

With React hook - useRef



const MyComponent = ({myRef}) => {
  const handleClick = () => alert('hello world')
  myRef.current.handleClick = handleClick
  return (<button onClick={handleClick}>Original Button</button>)
}

MyComponent.defaultProps = {
  myRef: {current: {}}
}

const MyParentComponent = () => {
  const myRef = React.useRef({})
  return (
    <>
      <MyComponent 
        myRef={myRef}
      />
      <button onClick={myRef.current.handleClick}>
        Additional Button
      </button>
    </>
  )
}

Good Luck...

Android: keeping a background service alive (preventing process death)

http://developer.android.com/reference/android/content/Context.html#BIND_ABOVE_CLIENT

public static final int BIND_ABOVE_CLIENT -- Added in API level 14

Flag for bindService(Intent, ServiceConnection, int): indicates that the client application binding to this service considers the service to be more important than the app itself. When set, the platform will try to have the out of memory killer kill the app before it kills the service it is bound to, though this is not guaranteed to be the case.

Other flags of the same group are: BIND_ADJUST_WITH_ACTIVITY, BIND_AUTO_CREATE, BIND_IMPORTANT, BIND_NOT_FOREGROUND, BIND_WAIVE_PRIORITY.

Note that the meaning of BIND_AUTO_CREATE has changed in ICS, and old applications that don't specify BIND_AUTO_CREATE will automatically have the flags BIND_WAIVE_PRIORITY and BIND_ADJUST_WITH_ACTIVITY set for them.

SQL Server Escape an Underscore

None of these worked for me in SSIS v18.0, so I would up doing something like this:

WHERE CHARINDEX('_', thingyoursearching) < 1

..where I am trying to ignore strings with an underscore in them. If you want to find things that have an underscore, just flip it around:

WHERE CHARINDEX('_', thingyoursearching) > 0

Most Useful Attributes

[DeploymentItem("myFile1.txt")] MSDN Doc on DeploymentItem

This is really useful if you are testing against a file or using the file as input to your test.

How do I install PHP cURL on Linux Debian?

I wrote an article on topis how to [manually install curl on debian linu][1]x.

[1]: http://www.jasom.net/how-to-install-curl-command-manually-on-debian-linux. This is its shortcut:

  1. cd /usr/local/src
  2. wget http://curl.haxx.se/download/curl-7.36.0.tar.gz
  3. tar -xvzf curl-7.36.0.tar.gz
  4. rm *.gz
  5. cd curl-7.6.0
  6. ./configure
  7. make
  8. make install

And restart Apache. If you will have an error during point 6, try to run apt-get install build-essential.

Can I assume (bool)true == (int)1 for any C++ compiler?

I've found different compilers return different results on true. I've also found that one is almost always better off comparing a bool to a bool instead of an int. Those ints tend to change value over time as your program evolves and if you assume true as 1, you can get bitten by an unrelated change elsewhere in your code.

JSON Naming Convention (snake_case, camelCase or PascalCase)

Notably for me on NodeJS, if I'm working with databases and my field names are underscore separated, I also use them in the struct keys.

This is because db fields have a lot of acronyms/abbreviations so something like appSNSInterfaceRRTest looks a bit messy but app_sns_interface_rr_test is nicer.

In Javascript variables are all camelCase and class names (constructors) are ProperCase, so you'd see something like

var devTask = {
        task_id: 120,
        store_id: 2118,
        task_name: 'generalLedger'
    };

or

generalLedgerTask = new GeneralLedgerTask( devTask );

And of course in JSON keys/strings are wrapped in double quotes, but then you just use the JSON.stringify and pass in JS objects, so don't need to worry about that.

I struggled with this a bit until I found this happy medium between JSON and JS naming conventions.

grep for special characters in Unix

Try vi with the -b option, this will show special end of line characters (I typically use it to see windows line endings in a txt file on a unix OS)

But if you want a scripted solution obviously vi wont work so you can try the -f or -e options with grep and pipe the result into sed or awk. From grep man page:

Matcher Selection -E, --extended-regexp Interpret PATTERN as an extended regular expression (ERE, see below). (-E is specified by POSIX.)

   -F, --fixed-strings
          Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched.  (-F is specified
          by POSIX.)

Java JSON serialization - best practice

Well, when writing it out to file, you do know what class T is, so you can store that in dump. Then, when reading it back in, you can dynamically call it using reflection.

public JSONObject dump() throws JSONException {
    JSONObject result = new JSONObject();
    JSONArray a = new JSONArray();
    for(T i : items){
        a.put(i.dump());
        // inside this i.dump(), store "class-name"
    }
    result.put("items", a);
    return result;
}

public void load(JSONObject obj) throws JSONException {
    JSONArray arrayItems = obj.getJSONArray("items");
    for (int i = 0; i < arrayItems.length(); i++) {
        JSONObject item = arrayItems.getJSONObject(i);
        String className = item.getString("class-name");
        try {
            Class<?> clazzy = Class.forName(className);
            T newItem = (T) clazzy.newInstance();
            newItem.load(obj);
            items.add(newItem);
        } catch (InstantiationException e) {
            // whatever
        } catch (IllegalAccessException e) {
            // whatever
        } catch (ClassNotFoundException e) {
            // whatever
        }
    }

Simple PowerShell LastWriteTime compare

Slightly easier - use the new-timespan cmdlet, which creates a time interval from the current time.

ls | where-object {(new-timespan $_.LastWriteTime).days -ge 1}

shows all files not written to today.

java.net.URLEncoder.encode(String) is deprecated, what should I use instead?

Use the other encode method in URLEncoder:

URLEncoder.encode(String, String)

The first parameter is the text to encode; the second is the name of the character encoding to use (e.g., UTF-8). For example:

System.out.println(
  URLEncoder.encode(
    "urlParameterString",
    java.nio.charset.StandardCharsets.UTF_8.toString()
  )
);

How can I access the MySQL command line with XAMPP for Windows?

For windows

cd\xampp\mysql\bin
mysql -u root -p

Just a simple commands for linux to open mysql :

sudo /opt/lampp/bin/mysql

How to write to a file, using the logging Python module?

An example of using logging.basicConfig rather than logging.fileHandler()

logging.basicConfig(filename=logname,
                            filemode='a',
                            format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
                            datefmt='%H:%M:%S',
                            level=logging.DEBUG)

logging.info("Running Urban Planning")

self.logger = logging.getLogger('urbanGUI')

In order, the five parts do the following:

  1. set the output file (filename=logname)
  2. set it to append rather than overwrite (filemode='a')
  3. determine the format of the output message (format=...)
  4. determine the format of the output time (datefmt='%H:%M:%S')
  5. and determine the minimum message level it will accept (level=logging.DEBUG).

What does the "~" (tilde/squiggle/twiddle) CSS selector mean?

It is General sibling combinator and is explained in @Salaman's answer very well.

What I did miss is Adjacent sibling combinator which is + and is closely related to ~.

example would be

.a + .b {
  background-color: #ff0000;
}

<ul>
  <li class="a">1st</li>
  <li class="b">2nd</li>
  <li>3rd</li>
  <li class="b">4th</li>
  <li class="a">5th</li>
</ul>
  • Matches elements that are .b
  • Are adjacent to .a
  • After .a in HTML

In example above it will mark 2nd li but not 4th.

_x000D_
_x000D_
   .a + .b {_x000D_
     background-color: #ff0000;_x000D_
   }
_x000D_
<ul>_x000D_
  <li class="a">1st</li>_x000D_
  <li class="b">2nd</li>_x000D_
  <li>3rd</li>_x000D_
  <li class="b">4th</li>_x000D_
  <li class="a">5th</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

JSFiddle

How can I find the length of a number?

Yes you need to convert to string in order to find the length.For example

var x=100;// type of x is number
var x=100+"";// now the type of x is string
document.write(x.length);//which would output 3.

Fit image to table cell [Pure HTML]

Inline content leaves space at the bottom for characters that descend (j, y, q):

https://developer.mozilla.org/en-US/docs/Images,_Tables,_and_Mysterious_Gaps

There are a couple fixes:

Use display: block;

<img style="display:block;" width="100%" height="100%" src="http://dummyimage.com/68x68/000/fff" />

or use vertical-align: bottom;

<img style="vertical-align: bottom;" width="100%" height="100%" src="http://dummyimage.com/68x68/000/fff" />

Save ArrayList to SharedPreferences

Why don't you stick your arraylist on an Application class? It only get's destroyed when the app is really killed, so, it will stick around for as long as the app is available.

Can I have multiple background images using CSS?

You could have a div for the top with one background and another for the main page, and seperate the page content between them or put the content in a floating div on another z-level. The way you are doing it may work but I doubt it will work across every browser you encounter.

How to sum digits of an integer in java?

In Java 8, this is possible in a single line of code as follows:

int sum = Pattern.compile("")
        .splitAsStream(factorialNumber.toString())
        .mapToInt(Integer::valueOf)
        .sum();

How to remove all of the data in a table using Django

Use this syntax to delete the rows also to redirect to the homepage (To avoid page load errors) :

def delete_all(self):
  Reporter.objects.all().delete()
  return HttpResponseRedirect('/')

Error in file(file, "rt") : cannot open the connection

close your R studio and run it again as an administrator. That did the magic for me. Hope it works for you and anyone going through this too.

z-index not working with fixed positioning

the behaviour of fixed elements (and absolute elements) as defined in CSS Spec:

They behave as they are detached from document, and placed in the nearest fixed/absolute positioned parent. (not a word by word quote)

This makes zindex calculation a bit complicated, I solved my problem (the same situation) by dynamically creating a container in body element and moving all such elements (which are class-ed as "my-fixed-ones" inside that body-level element)

How do I include negative decimal numbers in this regular expression?

^(-?\d+\.)?-?\d+$

allow:

23425.23425
10.10
100
0
0.00
-100
-10.10
10.-10
-10.-10
-23425.23425
-23425.-23425
0.234

Android - implementing startForeground for a service?

Solution for Oreo 8.1

I've encountered some problems such as RemoteServiceException because of invalid channel id with most recent versions of Android. This is how i solved it:

Activity:

override fun onCreate(savedInstanceState: Bundle?) {
    val intent = Intent(this, BackgroundService::class.java)

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        startForegroundService(intent)
    } else {
        startService(intent)
    }
}

BackgroundService:

override fun onCreate() {
    super.onCreate()
    startForeground()
}

private fun startForeground() {

    val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    val channelId =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                createNotificationChannel()
            } else {
                // If earlier version channel ID is not used
                // https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#NotificationCompat.Builder(android.content.Context)
                ""
            }

    val notificationBuilder = NotificationCompat.Builder(this, channelId )
    val notification = notificationBuilder.setOngoing(true)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setPriority(PRIORITY_MIN)
            .setCategory(Notification.CATEGORY_SERVICE)
            .build()
    startForeground(101, notification)
}


@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(): String{
    val channelId = "my_service"
    val channelName = "My Background Service"
    val chan = NotificationChannel(channelId,
            channelName, NotificationManager.IMPORTANCE_HIGH)
    chan.lightColor = Color.BLUE
    chan.importance = NotificationManager.IMPORTANCE_NONE
    chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
    val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    service.createNotificationChannel(chan)
    return channelId
}

JAVA EQUIVALENT

public class YourService extends Service {

    // Constants
    private static final int ID_SERVICE = 101;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        // do stuff like register for BroadcastReceiver, etc.

        // Create the Foreground Service
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? createNotificationChannel(notificationManager) : "";
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);
        Notification notification = notificationBuilder.setOngoing(true)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setPriority(PRIORITY_MIN)
                .setCategory(NotificationCompat.CATEGORY_SERVICE)
                .build();

        startForeground(ID_SERVICE, notification);
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private String createNotificationChannel(NotificationManager notificationManager){
        String channelId = "my_service_channelid";
        String channelName = "My Foreground Service";
        NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
        // omitted the LED color
        channel.setImportance(NotificationManager.IMPORTANCE_NONE);
        channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        notificationManager.createNotificationChannel(channel);
        return channelId;
    }
}

Eclipse error "Could not find or load main class"

I had the same problem. Spent few hours and finally changed my workspace back to local folder and everything works now. Maybe saves some time for others. Jon

jQuery.css() - marginLeft vs. margin-left?

when is marginLeft being used:

$("div").css({
    marginLeft:'12px',
    backgroundPosition:'10px -10px',
    minHeight: '40px'
});

As you can see, attributes that has a hyphen on it are converted to camelcased format. Using the margin-left from the previous code block above would make JavaScript bonkers because it will treat the hyphen as an operation for subtraction.

when is margin-left used:

$("div").css("margin-left","12px").css("background-position","10px -10px").css("min-height","40px");

Theoretically, both code blocks will do the same thing. We can allow hyphens on the second block because it is a string value while compared to the first block, it is somewhat an object.
Now that should make sense.

JPA CascadeType.ALL does not delete orphans

If you are using it with Hibernate, you'll have to explicitly define the annotation CascadeType.DELETE_ORPHAN, which can be used in conjunction with JPA CascadeType.ALL.

If you don't plan to use Hibernate, you'll have to explicitly first delete the child elements and then delete the main record to avoid any orphan records.

execution sequence

  1. fetch main row to be deleted
  2. fetch child elements
  3. delete all child elements
  4. delete main row
  5. close session

With JPA 2.0, you can now use the option orphanRemoval = true

@OneToMany(mappedBy="foo", orphanRemoval=true)

Convert JSON array to Python list

import json

array = '{"fruits": ["apple", "banana", "orange"]}'
data  = json.loads(array)
print data['fruits']
# the print displays:
# [u'apple', u'banana', u'orange']

You had everything you needed. data will be a dict, and data['fruits'] will be a list

How to copy files from host to Docker container?

The simpliest way to achieve this is,

  1. Find the container id
  2. docker cp <filename> <container-id>:<path>

How to resolve this System.IO.FileNotFoundException

I hate to point out the obvious, but System.IO.FileNotFoundException means the program did not find the file you specified. So what you need to do is check what file your code is looking for in production.

To see what file your program is looking for in production (look at the FileName property of the exception), try these techniques:

Then look at the file system on the machine and see if the file exists. Most likely the case is that it doesn't exist.

Targeting .NET Framework 4.5 via Visual Studio 2010

I have been struggling with VS2010/DNFW 4.5 integration and have finally got this working. Starting in VS 2008, a cache of assemblies was introduced that is used by Visual Studio called the "Referenced Assemblies". This file cache for VS 2010 is located at \Reference Assemblies\Microsoft\Framework.NetFramework\v4.0. Visual Studio loads framework assemblies from this location instead of from the framework installation directory. When Microsoft says that VS 2010 does not support DNFW 4.5 what they mean is that this directory does not get updated when DNFW 4.5 is installed. Once you have replace the files in this location with the updated DNFW 4.5 files, you will find that VS 2010 will happily function with DNFW 4.5.

jQuery set checkbox checked

I know this asks for a Jquery solution, but I just thought I'd point out that it is very easy to toggle this in plain javascript.

var element = document.getElementById("estado_cat");
element.checked = 1;

It will work in all current and future versions.

Exporting functions from a DLL with dllexport

If you want plain C exports, use a C project not C++. C++ DLLs rely on name-mangling for all the C++isms (namespaces etc...). You can compile your code as C by going into your project settings under C/C++->Advanced, there is an option "Compile As" which corresponds to the compiler switches /TP and /TC.

If you still want to use C++ to write the internals of your lib but export some functions unmangled for use outside C++, see the second section below.

Exporting/Importing DLL Libs in VC++

What you really want to do is define a conditional macro in a header that will be included in all of the source files in your DLL project:

#ifdef LIBRARY_EXPORTS
#    define LIBRARY_API __declspec(dllexport)
#else
#    define LIBRARY_API __declspec(dllimport)
#endif

Then on a function that you want to be exported you use LIBRARY_API:

LIBRARY_API int GetCoolInteger();

In your library build project create a define LIBRARY_EXPORTS this will cause your functions to be exported for your DLL build.

Since LIBRARY_EXPORTS will not be defined in a project consuming the DLL, when that project includes the header file of your library all of the functions will be imported instead.

If your library is to be cross-platform you can define LIBRARY_API as nothing when not on Windows:

#ifdef _WIN32
#    ifdef LIBRARY_EXPORTS
#        define LIBRARY_API __declspec(dllexport)
#    else
#        define LIBRARY_API __declspec(dllimport)
#    endif
#elif
#    define LIBRARY_API
#endif

When using dllexport/dllimport you do not need to use DEF files, if you use DEF files you do not need to use dllexport/dllimport. The two methods accomplish the same task different ways, I believe that dllexport/dllimport is the recommended method out of the two.

Exporting unmangled functions from a C++ DLL for LoadLibrary/PInvoke

If you need this to use LoadLibrary and GetProcAddress, or maybe importing from another language (i.e PInvoke from .NET, or FFI in Python/R etc) you can use extern "C" inline with your dllexport to tell the C++ compiler not to mangle the names. And since we are using GetProcAddress instead of dllimport we don't need to do the ifdef dance from above, just a simple dllexport:

The Code:

#define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)

EXTERN_DLL_EXPORT int getEngineVersion() {
  return 1;
}

EXTERN_DLL_EXPORT void registerPlugin(Kernel &K) {
  K.getGraphicsServer().addGraphicsDriver(
    auto_ptr<GraphicsServer::GraphicsDriver>(new OpenGLGraphicsDriver())
  );
}

And here's what the exports look like with Dumpbin /exports:

  Dump of file opengl_plugin.dll

  File Type: DLL

  Section contains the following exports for opengl_plugin.dll

    00000000 characteristics
    49866068 time date stamp Sun Feb 01 19:54:32 2009
        0.00 version
           1 ordinal base
           2 number of functions
           2 number of names

    ordinal hint RVA      name

          1    0 0001110E getEngineVersion = @ILT+265(_getEngineVersion)
          2    1 00011028 registerPlugin = @ILT+35(_registerPlugin)

So this code works fine:

m_hDLL = ::LoadLibrary(T"opengl_plugin.dll");

m_pfnGetEngineVersion = reinterpret_cast<fnGetEngineVersion *>(
  ::GetProcAddress(m_hDLL, "getEngineVersion")
);
m_pfnRegisterPlugin = reinterpret_cast<fnRegisterPlugin *>(
  ::GetProcAddress(m_hDLL, "registerPlugin")
);

Select value from list of tuples where condition

Yes, you can use filter if you know at which position in the tuple the desired column resides. If the case is that the id is the first element of the tuple then you can filter the list like so:

filter(lambda t: t[0]==10, mylist)

This will return the list of corresponding tuples. If you want the age, just pick the element you want. Instead of filter you could also use list comprehension and pick the element in the first go. You could even unpack it right away (if there is only one result):

[age] = [t[1] for t in mylist if t[0]==10]

But I would strongly recommend to use dictionaries or named tuples for this purpose.

Extracting columns from text file with different delimiters in Linux

You can use cut with a delimiter like this:

with space delim:

cut -d " " -f1-100,1000-1005 infile.csv > outfile.csv

with tab delim:

cut -d$'\t' -f1-100,1000-1005 infile.csv > outfile.csv

I gave you the version of cut in which you can extract a list of intervals...

Hope it helps!

Install opencv for Python 3.3

I can't comment on midopa's excellent answer due to lack of reputation.

On a Mac I (finally) successfully installed opencv from source using the following commands:

cmake -D CMAKE_BUILD_TYPE=RELEASE 
-D CMAKE_INSTALL_PREFIX=/usr/local 
-D PYTHON_EXECUTABLE=/Library/Frameworks/Python.framework/Versions/3.4/bin/python3 
-D PYTHON_LIBRARY=/Library/Frameworks/Python.framework//Versions/3.4/lib/libpython3.4m.dylib 
-D PYTHON_INCLUDE_DIR=/Library/Frameworks/Python.framework/Versions/3.4/include/python3.4m 
-D PYTHON_NUMPY_INCLUDE_DIRS=/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/numpy/core/include/numpy 
-D PYTHON_PACKAGES_PATH=/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages 
/relative/path/to/source/directory/

Then,

make -j8

change 8 for the number of threads your machine can handle, to speed things up

sudo make install

I added a PYTHONPATH environment variable to my ~/.bash_profile file so that Python could find cv2.so:

PYTHONPATH="${PYTHONPATH}:/usr/local/lib/python3.4/site-packages”
export PYTHONPATH

[For those using PyCharm, I had to go to Preferences > Project Structure > Add Content Root, and added the path to cv2.so's parent directory: /usr/local/lib/python3.4/site-packages]

This command got me past errors such as:

Could NOT find PythonLibs, by explicitly declaring the python library path

ld: can't link with a main executable for architecture x86_64
collect2: error: ld returned 1 exit status
make[2]: *** [lib/cv2.so] Error 1
make[1]: *** [modules/python2/CMakeFiles/opencv_python2.dir/all] Error 2
make: *** [all] Error 2

by explicitly pointing to the libpython3.4m.dylib

In terminal, check that it worked with:

$python3
>>> import cv2

It's all good if you don't get ImportError: No module named 'cv2'

This worked on a Macbook Pro Retina 15" 2013, Mavericks 10.9.4, Python 3.4.1 (previously installed from official download), opencv3 from source. Hope that this helps someone.

Can I add extension methods to an existing static class?

No. Extension methods require an instance variable (value) for an object. You can however, write a static wrapper around the ConfigurationManager interface. If you implement the wrapper, you don't need an extension method since you can just add the method directly.

 public static class ConfigurationManagerWrapper
 {
      public static ConfigurationSection GetSection( string name )
      {
         return ConfigurationManager.GetSection( name );
      }

      .....

      public static ConfigurationSection GetWidgetSection()
      {
          return GetSection( "widgets" );
      }
 }

Calculating the area under a curve given a set of coordinates, without knowing the function

If you have sklearn isntalled, a simple alternative is to use sklearn.metrics.auc

This computes the area under the curve using the trapezoidal rule given arbitrary x, and y array

import numpy as np
from sklearn.metrics import auc

dx = 5
xx = np.arange(1,100,dx)
yy = np.arange(1,100,dx)

print('computed AUC using sklearn.metrics.auc: {}'.format(auc(xx,yy)))
print('computed AUC using np.trapz: {}'.format(np.trapz(yy, dx = dx)))

both output the same area: 4607.5

the advantage of sklearn.metrics.auc is that it can accept arbitrarily-spaced 'x' array, just make sure it is ascending otherwise the results will be incorrect

In Perl, how can I read an entire file into a string?

This is more of a suggestion on how NOT to do it. I've just had a bad time finding a bug in a rather big Perl application. Most of the modules had its own configuration files. To read the configuration files as-a-whole, I found this single line of Perl somewhere on the Internet:

# Bad! Don't do that!
my $content = do{local(@ARGV,$/)=$filename;<>};

It reassigns the line separator as explained before. But it also reassigns the STDIN.

This had at least one side effect that cost me hours to find: It does not close the implicit file handle properly (since it does not call closeat all).

For example, doing that:

use strict;
use warnings;

my $filename = 'some-file.txt';

my $content = do{local(@ARGV,$/)=$filename;<>};
my $content2 = do{local(@ARGV,$/)=$filename;<>};
my $content3 = do{local(@ARGV,$/)=$filename;<>};

print "After reading a file 3 times redirecting to STDIN: $.\n";

open (FILE, "<", $filename) or die $!;

print "After opening a file using dedicated file handle: $.\n";

while (<FILE>) {
    print "read line: $.\n";
}

print "before close: $.\n";
close FILE;
print "after close: $.\n";

results in:

After reading a file 3 times redirecting to STDIN: 3
After opening a file using dedicated file handle: 3
read line: 1
read line: 2
(...)
read line: 46
before close: 46
after close: 0

The strange thing is, that the line counter $. is increased for every file by one. It's not reset, and it does not contain the number of lines. And it is not reset to zero when opening another file until at least one line is read. In my case, I was doing something like this:

while($. < $skipLines) {<FILE>};

Because of this problem, the condition was false because the line counter was not reset properly. I don't know if this is a bug or simply wrong code... Also calling close; oder close STDIN; does not help.

I replaced this unreadable code by using open, string concatenation and close. However, the solution posted by Brad Gilbert also works since it uses an explicit file handle instead.

The three lines at the beginning can be replaced by:

my $content = do{local $/; open(my $f1, '<', $filename) or die $!; my $tmp1 = <$f1>; close $f1 or die $!; $tmp1};
my $content2 = do{local $/; open(my $f2, '<', $filename) or die $!; my $tmp2 = <$f2>; close $f2 or die $!; $tmp2};
my $content3 = do{local $/; open(my $f3, '<', $filename) or die $!; my $tmp3 = <$f3>; close $f3 or die $!; $tmp3};

which properly closes the file handle.

Quadratic and cubic regression in Excel

The LINEST function described in a previous answer is the way to go, but an easier way to show the 3 coefficients of the output is to additionally use the INDEX function. In one cell, type: =INDEX(LINEST(B2:B21,A2:A21^{1,2},TRUE,FALSE),1) (by the way, the B2:B21 and A2:A21 I used are just the same values the first poster who answered this used... of course you'd change these ranges appropriately to match your data). This gives the X^2 coefficient. In an adjacent cell, type the same formula again but change the final 1 to a 2... this gives the X^1 coefficient. Lastly, in the next cell over, again type the same formula but change the last number to a 3... this gives the constant. I did notice that the three coefficients are very close but not quite identical to those derived by using the graphical trendline feature under the charts tab. Also, I discovered that LINEST only seems to work if the X and Y data are in columns (not rows), with no empty cells within the range, so be aware of that if you get a #VALUE error.

How to get values from selected row in DataGrid for Windows Form Application?

You could just use

DataGridView1.CurrentRow.Cells["ColumnName"].Value

ImportError: No module named pythoncom

$ pip3 install pypiwin32

Sometimes using pip3 also works if just pip by itself is not working.

How to set DialogFragment's width and height?

@Override
public void onStart() {
    super.onStart();
    Dialog dialog = getDialog();
    if (dialog != null)
    {
        dialog.getWindow().setLayout(-1, -2);
        dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        params.dimAmount = 1.0f;
        window.setAttributes(params);
        window.setBackgroundDrawableResource(android.R.color.transparent);
    }
}

Replace contents of factor column in R dataframe

I bet the problem is when you are trying to replace values with a new one, one that is not currently part of the existing factor's levels:

levels(iris$Species)
# [1] "setosa"     "versicolor" "virginica" 

Your example was bad, this works:

iris$Species[iris$Species == 'virginica'] <- 'setosa'

This is what more likely creates the problem you were seeing with your own data:

iris$Species[iris$Species == 'virginica'] <- 'new.species'
# Warning message:
# In `[<-.factor`(`*tmp*`, iris$Species == "virginica", value = c(1L,  :
#   invalid factor level, NAs generated

It will work if you first increase your factor levels:

levels(iris$Species) <- c(levels(iris$Species), "new.species")
iris$Species[iris$Species == 'virginica'] <- 'new.species'

If you want to replace "species A" with "species B" you'd be better off with

levels(iris$Species)[match("oldspecies",levels(iris$Species))] <- "newspecies"

C/C++ check if one bit is set in, i.e. int variable

the fastest way seems to be a lookup table for masks

writing integer values to a file using out.write()

i = Your_int_value

Write bytes value like this for example:

the_file.write(i.to_bytes(2,"little"))

Depend of you int value size and the bit order your prefer

Extract a substring according to a pattern

Another method to extract a substring

library(stringr)
substring <- str_extract(string, regex("(?<=:).*"))
#[1] "E001" "E002" "E003
  • (?<=:): look behind the colon (:)

The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'

This is how I was able to solve the problem when I faced it

  1. Start SQL Management Studio.
  2. Expand the Server Node (in the 'Object Explorer').
  3. Expand the Databases Node and then expand the specific Database which you are trying to access using the specific user.
  4. Expand the Users node under the Security node for the database.
  5. Right click the specific user and click 'properties'. You will get a dialog box.
  6. Make sure the user is a member of the db_owner group (please read the comments below before you use go this path) and other required changes using the view. (I used this for 2016. Not sure how the specific dialog look like in other version and hence not being specific)

Where to change default pdf page width and font size in jspdf.debug.js?

From the documentation page

To set the page type pass the value in constructor

jsPDF(orientation, unit, format) Creates new jsPDF document object

instance Parameters:

orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")

unit Measurement unit to be used when coordinates are specified. One of "pt" (points), "mm" (Default), "cm", "in"

format One of 'a3', 'a4' (Default),'a5' ,'letter' ,'legal'

To set font size

setFontSize(size)

Sets font size for upcoming text elements.

Parameters:

{Number} size Font size in points.

Best way to import Observable from rxjs

One thing I've learnt the hard way is being consistent

Watch out for mixing:

 import { BehaviorSubject } from "rxjs";

with

 import { BehaviorSubject } from "rxjs/BehaviorSubject";

This will probably work just fine UNTIL you try to pass the object to another class (where you did it the other way) and then this can fail

 (myBehaviorSubject instanceof Observable)

It fails because the prototype chain will be different and it will be false.

I can't pretend to understand exactly what is happening but sometimes I run into this and need to change to the longer format.

Select2() is not a function

Put config.assets.debug = false in config/environments/development.rb.

Need to ZIP an entire directory using Node.js

Adm-zip has problems just compressing an existing archive https://github.com/cthackers/adm-zip/issues/64 as well as corruption with compressing binary files.

I've also ran into compression corruption issues with node-zip https://github.com/daraosn/node-zip/issues/4

node-archiver is the only one that seems to work well to compress but it doesn't have any uncompress functionality.

Get month name from Date

To get Date formatted as "dd-MMM-yyyy" using JavaScript use the below code

_x000D_
_x000D_
const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
    ];

    const d = new Date();
    var dd = String(d.getDate()).padStart(2, '0');
    var mm = String(d.getMonth() + 1).padStart(2, '0');
    var yyyy = d.getFullYear();
    var fullDate = +dd +"-"+ monthNames[d.getMonth()] +"-"+ yyyy;
    document.write("The date is : "+ fullDate);
_x000D_
_x000D_
_x000D_

How to use particular CSS styles based on screen size / device

Why not use @media-queries? These are designed for that exact purpose. You can also do this with jQuery, but that's a last resort in my book.

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

//Check if viewport is smaller than 768 pixels
if(window.innerWidth < 768) {
    s.type = "text/javascript";
    s.src = "http://www.example.com/public/assets/css1";
}else { //Else we have a larger screen
    s.type = "text/javascript";
    s.src = "http://www.example.com/public/assets/css2";
}

$(function(){
    $("head").append(s); //Inject stylesheet
})

How to Validate Google reCaptcha on Form Submit

From a UX perspective, it can help to visibly let the user know when they can proceed to submit the form - either by enabling a disabled button, or simply making the button visible.

Here's a simple example...

<form>
    <div class="g-recaptcha" data-sitekey="YOUR_PRIVATE_KEY" data-callback="recaptchaCallback"></div>
    <button type="submit" class="btn btn-default hidden" id="btnSubmit">Submit</button>
</form>

<script>
    function recaptchaCallback() {
        var btnSubmit = document.getElementById("btnSubmit");

        if ( btnSubmit.classList.contains("hidden") ) {
            btnSubmit.classList.remove("hidden");
            btnSubmitclassList.add("show");
        }
    }
</script>

Examples for string find in Python

From the documentation:

str.find(sub[, start[, end]])

Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

So, some examples:

>>> my_str = 'abcdefioshgoihgs sijsiojs '
>>> my_str.find('a')
0
>>> my_str.find('g')
10
>>> my_str.find('s', 11)
15
>>> my_str.find('s', 15)
15
>>> my_str.find('s', 16)
17
>>> my_str.find('s', 11, 14)
-1

What is mapDispatchToProps?

mapStateToProps receives the state and props and allows you to extract props from the state to pass to the component.

mapDispatchToProps receives dispatch and props and is meant for you to bind action creators to dispatch so when you execute the resulting function the action gets dispatched.

I find this only saves you from having to do dispatch(actionCreator()) within your component thus making it a bit easier to read.

https://github.com/reactjs/react-redux/blob/master/docs/api.md#arguments

Install MySQL on Ubuntu without a password prompt

Another way to make it work:

echo "mysql-server-5.5 mysql-server/root_password password root" | debconf-set-selections
echo "mysql-server-5.5 mysql-server/root_password_again password root" | debconf-set-selections
apt-get -y install mysql-server-5.5

Note that this simply sets the password to "root". I could not get it to set a blank password using simple quotes '', but this solution was sufficient for me.

Based on a solution here.

Which characters need to be escaped when using Bash?

I presume that you're talking about bash strings. There are different types of strings which have a different set of requirements for escaping. eg. Single quotes strings are different from double quoted strings.

The best reference is the Quoting section of the bash manual.

It explains which characters needs escaping. Note that some characters may need escaping depending on which options are enabled such as history expansion.

PermissionError: [Errno 13] in python

When doing;

a_file = open('E:\Python Win7-64-AMD 3.3\Test', encoding='utf-8')

...you're trying to open a directory as a file, which may (and on most non UNIX file systems will) fail.

Your other example though;

a_file = open('E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')

should work well if you just have the permission on a.txt. You may want to use a raw (r-prefixed) string though, to make sure your path does not contain any escape characters like \n that will be translated to special characters.

a_file = open(r'E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')

Javascript - get array of dates between 2 dates

I was recently working with moment.js, following did the trick..

function getDateRange(startDate, endDate, dateFormat) {
        var dates = [],
            end = moment(endDate),
            diff = endDate.diff(startDate, 'days');

        if(!startDate.isValid() || !endDate.isValid() || diff <= 0) {
            return;
        }

        for(var i = 0; i < diff; i++) {
            dates.push(end.subtract(1,'d').format(dateFormat));
        }

        return dates;
    };
    console.log(getDateRange(startDate, endDate, dateFormat));

Result would be:

["09/03/2015", "10/03/2015", "11/03/2015", "12/03/2015", "13/03/2015", "14/03/2015", "15/03/2015", "16/03/2015", "17/03/2015", "18/03/2015"]

convert string to specific datetime format?

Use DATE_FORMAT from Date Conversions:

In your initializer:

DateTime::DATE_FORMATS[:my_date_format] = "%a %b %d %H:%M:%S %Z %Y"

In your view:

date = DateTime.parse("2011-05-19 10:30:14")
date.to_formatted_s(:my_date_format)
date.to_s(:my_date_format) 

How to find the difference in days between two dates?

Use the shell functions from http://cfajohnson.com/shell/ssr/ssr-scripts.tar.gz; they work in any standard Unix shell.

date1=2012-09-22
date2=2013-01-31
. date-funcs-sh
_date2julian "$date1"
jd1=$_DATE2JULIAN
_date2julian "$date2"
echo $(( _DATE2JULIAN - jd1 ))

See the documentation at http://cfajohnson.com/shell/ssr/08-The-Dating-Game.shtml

Css Move element from left to right animated

It's because you aren't giving the un-hovered state a right attribute.

right isn't set so it's trying to go from nothing to 0px. Obviously because it has nothing to go to, it just 'warps' over.

If you give the unhovered state a right:90%;, it will transition how you like.

Just as a side note, if you still want it to be on the very left of the page, you can use the calc css function.

Example:

right: calc(100% - 100px)
                     ^ width of div

You don't have to use left then.

Also, you can't transition using left or right auto and will give the same 'warp' effect.

_x000D_
_x000D_
div {_x000D_
    width:100px;_x000D_
    height:100px;_x000D_
    background:red;_x000D_
    transition:2s;_x000D_
    -webkit-transition:2s;_x000D_
    -moz-transition:2s;_x000D_
    position:absolute;_x000D_
    right:calc(100% - 100px);_x000D_
}_x000D_
div:hover {_x000D_
  right:0;_x000D_
}
_x000D_
<p>_x000D_
  <b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions._x000D_
</p>_x000D_
<div></div>_x000D_
<p>Hover over the red square to see the transition effect.</p>
_x000D_
_x000D_
_x000D_

CanIUse says that the calc() function only works on IE10+

Enum "Inheritance"

Enums cannot be derrived from other enums, but only from int, uint, short, ushort, long, ulong, byte and sbyte.

Like Pascal said, you can use other enum's values or constants to initialize an enum value, but that's about it.

MySQL stored procedure vs function, which would I use when?

A stored function can be used within a query. You could then apply it to every row, or within a WHERE clause.

A procedure is executed using the CALL query.

Overflow Scroll css is not working in the div

You didn't gave the div a height. So it will automatically stretch when more content is added. Give it a fix-height and the scroll bars will show up.

jquery fill dropdown with json data

In most of the companies they required a common functionality for multiple dropdownlist for all the pages. Just call the functions or pass your (DropDownID,JsonData,KeyValue,textValue)

    <script>

        $(document).ready(function(){

            GetData('DLState',data,'stateid','statename');
        });

        var data = [{"stateid" : "1","statename" : "Mumbai"},
                    {"stateid" : "2","statename" : "Panjab"},
                    {"stateid" : "3","statename" : "Pune"},
                     {"stateid" : "4","statename" : "Nagpur"},
                     {"stateid" : "5","statename" : "kanpur"}];

        var Did=document.getElementById("DLState");

        function GetData(Did,data,valkey,textkey){
          var str= "";
          for (var i = 0; i <data.length ; i++){

            console.log(data);


            str+= "<option value='" + data[i][valkey] + "'>" + data[i][textkey] + "</option>";

          }
          $("#"+Did).append(str);
        };    </script>

</head>
<body>
  <select id="DLState">
  </select>
</body>
</html>

How to update (append to) an href in jquery?

jQuery 1.4 has a new feature for doing this, and it rules. I've forgotten what it's called, but you use it like this:

$("a.directions-link").attr("href", function(i, href) {
  return href + '?q=testing';
});

That loops over all the elements too, so no need for $.each

Filter Java Stream to 1 and only 1 element

If you don't use Guava or Kotlin, here's a solution based on @skiwi and @Neuron answers.

users.stream().collect(single(user -> user.getId() == 1));

or

users.stream().collect(optional(user -> user.getId() == 1));

where single and optional are statically imported functions returning corresponding collectors.

I reasoned it would look more succinct if the filtering logic had been moved inside the collector. Also nothing would break in the code if you happened to delete the string with .filter.

The gist for the code https://gist.github.com/overpas/ccc39b75f17a1c65682c071045c1a079

Inline IF Statement in C#

You can do inline ifs with

return y == 20 ? 1 : 2;

which will give you 1 if true and 2 if false.

Remove char at specific index - python

as a sidenote, replace doesn't have to move all zeros. If you just want to remove the first specify count to 1:

'asd0asd0'.replace('0','',1)

Out:

'asdasd0'

Reading/parsing Excel (xls) files with Python

If the file is really an old .xls, this works for me on python3 just using base open() and pandas:

df = pandas.read_csv(open(f, encoding = 'UTF-8'), sep='\t')

Note that the file I'm using is tab delimited. less or a text editor should be able to read .xls so that you can sniff out the delimiter.

I did not have a lot of luck with xlrd because of – I think – UTF-8 issues.

PHP Date Format to Month Name and Year

You could use:

echo date('F Y', strtotime('20130814'));

which should do the trick.

Edit: You have a date which is in a string format. To be able to format it nicelt, you first need to change it into a date itself - which is where strtotime comes in. It is a fantastic feature that converts almost any plausible expression of a date into a date itself. Then we can actually use the date() function to format the output into what you want.

How can I view a git log of just one user's commits?

Show n number of logs for x user in colour by adding this little snippet in your .bashrc file.

gitlog() {
    if [ "$1" ] && [ "$2" ]; then
       git log --pretty=format:"%h%x09 %C(cyan)%an%x09 %Creset%ad%x09 %Cgreen%s" --date-order -n "$1" --author="$2"
    elif [ "$1" ]; then
       git log --pretty=format:"%h%x09 %C(cyan)%an%x09 %Creset%ad%x09 %Cgreen%s" --date-order -n "$1"
    else
        git log --pretty=format:"%h%x09 %C(cyan)%an%x09 %Creset%ad%x09 %Cgreen%s" --date-order
    fi
}

alias l=gitlog

To show the last 10 commits by Frank:

l 10 frank

To show the last 20 commits by anyone:

l 20

Open a URL without using a browser from a batch file

Try winhttpjs.bat. It uses a winhttp request object that should be faster than
Msxml2.XMLHTTP as there isn't any DOM parsing of the response. It is capable to do requests with body and all HTTP methods.

call winhttpjs.bat  http://somelink.com/something.html -saveTo c:\something.html

Can't Load URL: The domain of this URL isn't included in the app's domains

Like the other answer says, in the left hand side select Products and add product. Then select Facbook Login.

I then added http://localhost:3000/ to the field 'Valid OAuth redirect URIs', and then everything worked.

Table column sizing

I hacked this out for release Bootstrap 4.1.1 per my needs before I saw @florian_korner's post. Looks very similar.

If you use sass you can paste this snippet at the end of your bootstrap includes. It seems to fix the issue for chrome, IE, and edge. Does not seem to break anything in firefox.

@mixin make-td-col($size, $columns: $grid-columns) {
    width: percentage($size / $columns);
}

@each $breakpoint in map-keys($grid-breakpoints) {
    $infix: breakpoint-infix($breakpoint, $grid-breakpoints);

    @for $i from 1 through $grid-columns {
        td.col#{$infix}-#{$i}, th.col#{$infix}-#{$i} {
            @include make-td-col($i, $grid-columns);
        }
    }
}

or if you just want the compiled css utility:

td.col-1, th.col-1 {
  width: 8.33333%; }

td.col-2, th.col-2 {
  width: 16.66667%; }

td.col-3, th.col-3 {
  width: 25%; }

td.col-4, th.col-4 {
  width: 33.33333%; }

td.col-5, th.col-5 {
  width: 41.66667%; }

td.col-6, th.col-6 {
  width: 50%; }

td.col-7, th.col-7 {
  width: 58.33333%; }

td.col-8, th.col-8 {
  width: 66.66667%; }

td.col-9, th.col-9 {
  width: 75%; }

td.col-10, th.col-10 {
  width: 83.33333%; }

td.col-11, th.col-11 {
  width: 91.66667%; }

td.col-12, th.col-12 {
  width: 100%; }

td.col-sm-1, th.col-sm-1 {
  width: 8.33333%; }

td.col-sm-2, th.col-sm-2 {
  width: 16.66667%; }

td.col-sm-3, th.col-sm-3 {
  width: 25%; }

td.col-sm-4, th.col-sm-4 {
  width: 33.33333%; }

td.col-sm-5, th.col-sm-5 {
  width: 41.66667%; }

td.col-sm-6, th.col-sm-6 {
  width: 50%; }

td.col-sm-7, th.col-sm-7 {
  width: 58.33333%; }

td.col-sm-8, th.col-sm-8 {
  width: 66.66667%; }

td.col-sm-9, th.col-sm-9 {
  width: 75%; }

td.col-sm-10, th.col-sm-10 {
  width: 83.33333%; }

td.col-sm-11, th.col-sm-11 {
  width: 91.66667%; }

td.col-sm-12, th.col-sm-12 {
  width: 100%; }

td.col-md-1, th.col-md-1 {
  width: 8.33333%; }

td.col-md-2, th.col-md-2 {
  width: 16.66667%; }

td.col-md-3, th.col-md-3 {
  width: 25%; }

td.col-md-4, th.col-md-4 {
  width: 33.33333%; }

td.col-md-5, th.col-md-5 {
  width: 41.66667%; }

td.col-md-6, th.col-md-6 {
  width: 50%; }

td.col-md-7, th.col-md-7 {
  width: 58.33333%; }

td.col-md-8, th.col-md-8 {
  width: 66.66667%; }

td.col-md-9, th.col-md-9 {
  width: 75%; }

td.col-md-10, th.col-md-10 {
  width: 83.33333%; }

td.col-md-11, th.col-md-11 {
  width: 91.66667%; }

td.col-md-12, th.col-md-12 {
  width: 100%; }

td.col-lg-1, th.col-lg-1 {
  width: 8.33333%; }

td.col-lg-2, th.col-lg-2 {
  width: 16.66667%; }

td.col-lg-3, th.col-lg-3 {
  width: 25%; }

td.col-lg-4, th.col-lg-4 {
  width: 33.33333%; }

td.col-lg-5, th.col-lg-5 {
  width: 41.66667%; }

td.col-lg-6, th.col-lg-6 {
  width: 50%; }

td.col-lg-7, th.col-lg-7 {
  width: 58.33333%; }

td.col-lg-8, th.col-lg-8 {
  width: 66.66667%; }

td.col-lg-9, th.col-lg-9 {
  width: 75%; }

td.col-lg-10, th.col-lg-10 {
  width: 83.33333%; }

td.col-lg-11, th.col-lg-11 {
  width: 91.66667%; }

td.col-lg-12, th.col-lg-12 {
  width: 100%; }

td.col-xl-1, th.col-xl-1 {
  width: 8.33333%; }

td.col-xl-2, th.col-xl-2 {
  width: 16.66667%; }

td.col-xl-3, th.col-xl-3 {
  width: 25%; }

td.col-xl-4, th.col-xl-4 {
  width: 33.33333%; }

td.col-xl-5, th.col-xl-5 {
  width: 41.66667%; }

td.col-xl-6, th.col-xl-6 {
  width: 50%; }

td.col-xl-7, th.col-xl-7 {
  width: 58.33333%; }

td.col-xl-8, th.col-xl-8 {
  width: 66.66667%; }

td.col-xl-9, th.col-xl-9 {
  width: 75%; }

td.col-xl-10, th.col-xl-10 {
  width: 83.33333%; }

td.col-xl-11, th.col-xl-11 {
  width: 91.66667%; }

td.col-xl-12, th.col-xl-12 {
  width: 100%; }

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.

How do I append a node to an existing XML file in java

To append a new data element,just do this...

Document doc = docBuilder.parse(is);        
Node root=doc.getFirstChild();
Element newserver=doc.createElement("new_server");
root.appendChild(newserver);

easy.... 'is' is an InputStream object. rest is similar to your code....tried it just now...

Detect enter press in JTextField

For each text field in your frame, invoke the addKeyListener method. Then implement and override the keyPressed method, as others have indicated. Now you can press enter from any field in your frame to activate your action.

@Override
        public void keyPressed(KeyEvent e) {
            if(e.getKeyCode() == KeyEvent.VK_ENTER){
                //perform action
            }
        }

How to properly upgrade node using nvm

This may work:

nvm install NEW_VERSION --reinstall-packages-from=OLD_VERSION

For example:

nvm install 6.7 --reinstall-packages-from=6.4

then, if you want, you can delete your previous version with:

nvm uninstall OLD_VERSION

Where, in your case, NEW_VERSION = 5.4 OLD_VERSION = 5.0

Alternatively, try:

nvm install stable --reinstall-packages-from=current

How to sum up elements of a C++ vector?

#include<boost/range/numeric.hpp>
int sum = boost::accumulate(vector, 0);

How to delete last character from a string using jQuery?

You can do it with plain JavaScript:

alert('123-4-'.substr(0, 4)); // outputs "123-"

This returns the first four characters of your string (adjust 4 to suit your needs).

Android: Test Push Notification online (Google Cloud Messaging)

Found a very easy way to do this.

Open http://phpfiddle.org/

Paste following php script in box. In php script set API_ACCESS_KEY, set device ids separated by coma.

Press F9 or click Run.

Have fun ;)

<?php


// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'YOUR-API-ACCESS-KEY-GOES-HERE' );


$registrationIds = array("YOUR DEVICE IDS WILL GO HERE" );

// prep the bundle
$msg = array
(
    'message'       => 'here is a message. message',
    'title'         => 'This is a title. title',
    'subtitle'      => 'This is a subtitle. subtitle',
    'tickerText'    => 'Ticker text here...Ticker text here...Ticker text here',
    'vibrate'   => 1,
    'sound'     => 1
);

$fields = array
(
    'registration_ids'  => $registrationIds,
    'data'              => $msg
);

$headers = array
(
    'Authorization: key=' . API_ACCESS_KEY,
    'Content-Type: application/json'
);

$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );

echo $result;
?>

For FCM, google url would be: https://fcm.googleapis.com/fcm/send

For FCM v1 google url would be: https://fcm.googleapis.com/v1/projects/YOUR_GOOGLE_CONSOLE_PROJECT_ID/messages:send

Note: While creating API Access Key on google developer console, you have to use 0.0.0.0/0 as ip address. (For testing purpose).

In case of receiving invalid Registration response from GCM server, please cross check the validity of your device token. You may check the validity of your device token using following url:

https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=YOUR_DEVICE_TOKEN

Some response codes:

Following is the description of some response codes you may receive from server.

{ "message_id": "XXXX" } - success
{ "message_id": "XXXX", "registration_id": "XXXX" } - success, device registration id has been changed mainly due to app re-install
{ "error": "Unavailable" } - Server not available, resend the message
{ "error": "InvalidRegistration" } - Invalid device registration Id 
{ "error": "NotRegistered"} - Application was uninstalled from the device

PreparedStatement with Statement.RETURN_GENERATED_KEYS

You can either use the prepareStatement method taking an additional int parameter

PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)

For some JDBC drivers (for example, Oracle) you have to explicitly list the column names or indices of the generated keys:

PreparedStatement ps = con.prepareStatement(sql, new String[]{"USER_ID"})

Query to get only numbers from a string

First create this UDF

CREATE FUNCTION dbo.udf_GetNumeric
(
  @strAlphaNumeric VARCHAR(256)
)
RETURNS VARCHAR(256)
AS
BEGIN
  DECLARE @intAlpha INT
  SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric)
  BEGIN
    WHILE @intAlpha > 0
    BEGIN
      SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' )
      SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric )
    END
  END
  RETURN ISNULL(@strAlphaNumeric,0)
END
GO

Now use the function as

SELECT dbo.udf_GetNumeric(column_name) 
from table_name

SQL FIDDLE

I hope this solved your problem.

Reference

java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

I had the same problem. Go to Project Properties -> Deployment Assemplbly and add jstl jar

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

jGuru:

The <%@include file="abc.jsp"%> directive acts like C "#include", pulling in the text of the included file and compiling it as if it were part of the including file. The included file can be any type (including HTML or text).

The <jsp:include page="abc.jsp"> tag compiles the file as a separate JSP file, and embeds a call to it in the compiled JSP.

Some JSP engines support the non-standard tags <!--#include file="data.inc"--> (NCSA-, or .shtml-style) and <%@ vinclude="data.inc" %> (JRun-style), but these are not defined in the JSP spec and thus cannot be relied on.

See also this question in the JSP FAQ.

Escaping a forward slash in a regular expression

For java, you don't need to.

eg: "^(.*)/\\*LOG:(\\d+)\\*/(.*)$" ==> ^(.*)/\*LOG:(\d+)\*/(.*)$

If you put \ in front of /. IDE will tell you "Redundant Character Escape "\/" in ReGex"

How to set environment variable for everyone under my linux system?

Some interesting excerpts from the bash manpage:

When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.
...
When an interactive shell that is not a login shell is started, bash reads and executes commands from /etc/bash.bashrc and ~/.bashrc, if these files exist. This may be inhibited by using the --norc option. The --rcfile file option will force bash to read and execute commands from file instead of /etc/bash.bashrc and ~/.bashrc.

So have a look at /etc/profile or /etc/bash.bashrc, these files are the right places for global settings. Put something like this in them to set up an environement variable:

export MY_VAR=xxx

HTTP status code for update and delete?

In addition to 200 and 204, 205 (Reset Content) could be a valid response.

The server has fulfilled the request and the user agent SHOULD reset the document view which caused the request to be sent ... [e.g.] clearing of the form in which the input is given.

OpenSSL and error in reading openssl.conf file

The problem here is that there ISN'T an openssl.cnf file given with the GnuWin32 openssl stuff. You have to create it. You can find out HOW to create an openssl.cnf file by going here:

http://www.flatmtn.com/article/setting-ssl-certificates-apache

Where it lays it all out for you on how to do it.

PLEASE NOTE: The openssl command given with the backslash at the end is for UNIX. For Windows : 1)Remove the backslash, and 2)Move the second line up so it is at the end of the first line. (So you get just one command.)

ALSO: It is VERY important to read through the comments. There are some changes you might want to make based upon them.

Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception

If you are using eclipse, you should modify the context.xml, from the server project created in your eclipse package explorer. When using tomcat in eclipse it is the only one valid, the others are ignored or overwriten

How to find path of active app.config file?

Make sure you click the properties on the file and set it to "copy always" or it will not be in the Debug\ folder with your happy lil dll's to configure where it needs to be and add more cowbell

Converting string to number in javascript/jQuery

You can adding a + before the string without using parseInt and parseFloat and radix, Simply

sample:

var votevalue = +$('button').data('votevalue');

alert(typeof(votevalue));

Reading Datetime value From Excel sheet

i had a similar situation and i used the below code for getting this worked..

Aspose.Cells.LoadOptions loadOptions = new Aspose.Cells.LoadOptions(Aspose.Cells.LoadFormat.CSV);

Workbook workbook = new Workbook(fstream, loadOptions);

Worksheet worksheet = workbook.Worksheets[0];

dt = worksheet.Cells.ExportDataTable(0, 0, worksheet.Cells.MaxDisplayRange.RowCount, worksheet.Cells.MaxDisplayRange.ColumnCount, true);

DataTable dtCloned = dt.Clone();
ArrayList myAL = new ArrayList();

foreach (DataColumn column in dtCloned.Columns)
{
    if (column.DataType == Type.GetType("System.DateTime"))
    {
        column.DataType = typeof(String);
        myAL.Add(column.ColumnName);
    }
}


foreach (DataRow row in dt.Rows)
{
    dtCloned.ImportRow(row);
}



foreach (string colName in myAL)
{
    dtCloned.Columns[colName].Convert(val => DateTime.Parse(Convert.ToString(val)).ToString("MMMM dd, yyyy"));
}


/*******************************/

public static class MyExtension
{
    public static void Convert<T>(this DataColumn column, Func<object, T> conversion)
    {
        foreach (DataRow row in column.Table.Rows)
        {
            row[column] = conversion(row[column]);
        }
    }
}

Hope this helps some1 thx_joxin

Spark - Error "A master URL must be set in your configuration" when submitting an app

var appName:String ="test"
val conf = new SparkConf().setAppName(appName).setMaster("local[*]").set("spark.executor.memory","1g");
val sc =  SparkContext.getOrCreate(conf)
sc.setLogLevel("WARN")

How to extract duration time from ffmpeg output?

I recommend using json format, it's easier for parsing

ffprobe -i your-input-file.mp4 -v quiet -print_format json -show_format -show_streams -hide_banner

{
    "streams": [
        {
            "index": 0,
            "codec_name": "aac",
            "codec_long_name": "AAC (Advanced Audio Coding)",
            "profile": "HE-AACv2",
            "codec_type": "audio",
            "codec_time_base": "1/44100",
            "codec_tag_string": "[0][0][0][0]",
            "codec_tag": "0x0000",
            "sample_fmt": "fltp",
            "sample_rate": "44100",
            "channels": 2,
            "channel_layout": "stereo",
            "bits_per_sample": 0,
            "r_frame_rate": "0/0",
            "avg_frame_rate": "0/0",
            "time_base": "1/28224000",
            "duration_ts": 305349201,
            "duration": "10.818778",
            "bit_rate": "27734",
            "disposition": {
                "default": 0,
                "dub": 0,
                "original": 0,
                "comment": 0,
                "lyrics": 0,
                "karaoke": 0,
                "forced": 0,
                "hearing_impaired": 0,
                "visual_impaired": 0,
                "clean_effects": 0,
                "attached_pic": 0
            }
        }
    ],
    "format": {
        "filename": "your-input-file.mp4",
        "nb_streams": 1,
        "nb_programs": 0,
        "format_name": "aac",
        "format_long_name": "raw ADTS AAC (Advanced Audio Coding)",
        "duration": "10.818778",
        "size": "37506",
        "bit_rate": "27734",
        "probe_score": 51
    }
}

you can find the duration information in format section, works both for video and audio

How to create a user in Django?

The correct way to create a user in Django is to use the create_user function. This will handle the hashing of the password, etc..

from django.contrib.auth.models import User
user = User.objects.create_user(username='john',
                                 email='[email protected]',
                                 password='glass onion')

Anyway to prevent the Blue highlighting of elements in Chrome when clicking quickly?

I had similar issue with <input type="range" /> and I solved it with

-webkit-tap-highlight-color: transparent;

_x000D_
_x000D_
input[type="range"]{
  -webkit-tap-highlight-color: transparent;
}
_x000D_
 <input type="range" id="volume" name="demo"
         min="0" max="11">
  <label for="volume">Demo</label>
_x000D_
_x000D_
_x000D_