@martinho as a newbie using Flask and Python myself, I think the previous answers here took for granted that you had a good understanding of the fundamentals. In case you or other viewers don't know the fundamentals, I'll give more context to understand the answer...
... the request.args
is bringing a "dictionary" object for you. The "dictionary" object is similar to other collection-type of objects in Python, in that it can store many elements in one single object. Therefore the answer to your question
And how many parameters
request.args.get()
takes.
It will take only one object, a "dictionary" type of object (as stated in the previous answers). This "dictionary" object, however, can have as many elements as needed... (dictionaries have paired elements called Key, Value).
Other collection-type of objects besides "dictionaries", would be "tuple", and "list"... you can run a google search on those and "data structures" in order to learn other Python fundamentals. This answer is based Python; I don't have an idea if the same applies to other programming languages.
Let me show approch without JQuery. Simple JS function:
function isVisible(elem) {
var coords = elem.getBoundingClientRect();
var topVisible = coords.top > 0 && coords.top < 0;
var bottomVisible = coords.bottom < shift && coords.bottom > 0;
return topVisible || bottomVisible;
}
Short example how to use it:
var img = document.getElementById("pic1");
if (isVisible(img)) { img.style.opacity = "1.00"; }
In order to do this in SQL Server, you must order the query by a column, so you can specify the rows you want.
Example:
select * from table order by [some_column]
offset 10 rows
FETCH NEXT 10 rows only
And you can't use the "TOP" keyword when doing this.
You can learn more here: https://technet.microsoft.com/pt-br/library/gg699618%28v=sql.110%29.aspx
As someone who has written several libraries for consuming REST services, let me give you the client perspective on why I think wrapping the result in metadata is the way to go:
And a suggestion: Like the Twitter API, you should replace the page_number with a straight index/cursor. The reason is, the API allows the client to set the page size per-request. Is the returned page_number the number of pages the client has requested so far, or the number of the page given the last used page_size (almost certainly the later, but why not avoid such ambiguity altogether)?
You should include "bPaginate": false,
into the configuration object you pass to your constructor parameters. As seen here: http://datatables.net/release-datatables/examples/basic_init/filter_only.html
You can either use skip() and limit(), but it's very inefficient. A better solution would be a sort on indexed field plus limit(). We at Wunderflats have published a small lib here: https://github.com/wunderflats/goosepage It uses the first way.
You should \usepackage{longtable}
.
beside the answer of @MantasD I would like to offer comprehensive customized Laravel pagination. Assuming using Laravel 5.2 and the following included view:
@include('pagination.default', ['pager' => $users])
Features
default.blade.php
@if($pager->lastPage() != 1)
<ul class="pagination">
@unless($pager->currentPage() < 3)
<li class="paginate_button previous">
<a href="{{ $pager->url(1) }}" title="First Page"><i class="fa fa-angle-double-left"></i></a>
</li>
@endunless
<li class="paginate_button previous @unless($pager->previousPageUrl())disabled @endunless">
<a href="{{ $pager->previousPageUrl() }}"><i class="fa fa-angle-left"></i></a>
</li>
@while($pager->paging++ < $pager->lastPage())
@if (abs($pager->paging - $pager->currentPage()) >= 2)
{{-- Generate relative links (eg. +10,etc) --}}
@if(in_array(abs($pager->paging - $pager->currentPage()), array(10, 50, 100, 500, 1000))
and $pager->paging != 1 and $pager->paging != $pager->lastPage())
<li class="paginate_button @unless($pager->currentPage() != $pager->paging)active @endunless">
<a title="Results from {{ PaginationStartEnd($pager->paging, $pager->perPage(), $pager->total())['start'] }} to {{ PaginationStartEnd($pager->paging, $pager->perPage(), $pager->total())['end'] }} of {{ $pager->total() }}" href="{{ $pager->url($pager->paging) }}">
<!-- + {{ $pager->paging - $pager->currentPage() }} -->{{ $pager->paging }}
</a>
</li>
@endif
@else
<li class="paginate_button @unless($pager->currentPage() != $pager->paging)active @endunless">
<a title="Results from {{ PaginationStartEnd($pager->paging, $pager->perPage(), $pager->total())['start'] }} to {{ PaginationStartEnd($pager->paging, $pager->perPage(), $pager->total())['end'] }} of {{ $pager->total() }}" href="{{ $pager->url($pager->paging) }}">
{{ $pager->paging }}
</a>
</li>
@endif
@endwhile
<li class="paginate_button next @unless($pager->nextPageUrl())disabled @endunless">
<a href="{{ $pager->nextPageUrl() }}"><i class="fa fa-angle-right"></i></a>
</li>
@unless($pager->lastPage() - $pager->currentPage() < 2)
<li class="paginate_button next">
<a href="{{ $pager->url($pager->lastPage()) }}" title="Last Page"><i class="fa fa-angle-double-right"></i></a>
</li>
@endunless
</ul>
@endif
PaginationStartEnd function
if (!function_exists('PaginationStartEnd')) {
function PaginationStartEnd($currentPage, $perPage, $total)
{
$pageStart = number_format( $perPage * ($currentPage - 1));
$pageEnd = $pageStart + $perPage;
if ($pageEnd > $total)
$pageEnd = $total;
$pageStart++;
return array('start' => number_format($pageStart), 'end' => number_format($pageEnd));
}
}
You can use and customize this more as you wish.
Note: $pager->paging is variable set to 0 declared in the controller action
IF you have a version greater than 1.8, you can use this to hit the page change events:
$('#myTable').on('page', function () {...} );
Hope this helps!
UPDATE:
Some comments have pointed out that using .live() instead of .on() worked for them. Be aware of that you should try both and see which one works best in your particular circumstance! (I believe this may have to do with your version on jQuery, but please comment if you find another reason!)
Another way to link Angular Paginator with the data table using Slice Pipe.Here data is fetched only once from server.
View:
<div class="col-md-3" *ngFor="let productObj of productListData |
slice: lowValue : highValue">
//actual data dispaly
</div>
<mat-paginator [length]="productListData.length" [pageSize]="pageSize"
(page)="pageEvent = getPaginatorData($event)">
</mat-paginator>
Component
pageIndex:number = 0;
pageSize:number = 50;
lowValue:number = 0;
highValue:number = 50;
getPaginatorData(event){
console.log(event);
if(event.pageIndex === this.pageIndex + 1){
this.lowValue = this.lowValue + this.pageSize;
this.highValue = this.highValue + this.pageSize;
}
else if(event.pageIndex === this.pageIndex - 1){
this.lowValue = this.lowValue - this.pageSize;
this.highValue = this.highValue - this.pageSize;
}
this.pageIndex = event.pageIndex;
}
select top {LIMIT HERE} * from (
select *, ROW_NUMBER() over (order by {ORDER FIELD}) as r_n_n
from {YOUR TABLES} where {OTHER OPTIONAL FILTERS}
) xx where r_n_n >={OFFSET HERE}
A note:
This solution will only work in SQL Server 2005 or above, since this was when ROW_NUMBER()
was implemented.
You can do that by adding a check on where you're at in the cellForRowAtIndexPath:
method. This method is easy to understand and to implement :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Classic start method
static NSString *cellIdentifier = @"MyCell";
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell)
{
cell = [[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MainMenuCellIdentifier];
}
MyData *data = [self.dataArray objectAtIndex:indexPath.row];
// Do your cell customisation
// cell.titleLabel.text = data.title;
BOOL lastItemReached = [data isEqual:[[self.dataArray] lastObject]];
if (!lastItemReached && indexPath.row == [self.dataArray count] - 1)
{
[self launchReload];
}
}
EDIT : added a check on last item to prevent recursion calls. You'll have to implement the method defining whether the last item has been reached or not.
EDIT2 : explained lastItemReached
There may be two approaches depending on your server side logic.
Approach 1: When server is not smart enough to handle object states.
You could send all cached record unique id’s to server, for example ["id1","id2","id3","id4","id5","id6","id7","id8","id9","id10"] and a boolean parameter to know whether you are requesting new records(pull to refresh) or old records(load more).
Your sever should responsible to return new records(load more records or new records via pull to refresh) as well as id’s of deleted records from ["id1","id2","id3","id4","id5","id6","id7","id8","id9","id10"].
Example:- If you are requesting load more then your request should look something like this:-
{
"isRefresh" : false,
"cached" : ["id1","id2","id3","id4","id5","id6","id7","id8","id9","id10"]
}
Now suppose you are requesting old records(load more) and suppose "id2" record is updated by someone and "id5" and "id8" records is deleted from server then your server response should look something like this:-
{
"records" : [
{"id" :"id2","more_key":"updated_value"},
{"id" :"id11","more_key":"more_value"},
{"id" :"id12","more_key":"more_value"},
{"id" :"id13","more_key":"more_value"},
{"id" :"id14","more_key":"more_value"},
{"id" :"id15","more_key":"more_value"},
{"id" :"id16","more_key":"more_value"},
{"id" :"id17","more_key":"more_value"},
{"id" :"id18","more_key":"more_value"},
{"id" :"id19","more_key":"more_value"},
{"id" :"id20","more_key":"more_value"}],
"deleted" : ["id5","id8"]
}
But in this case if you’ve a lot of local cached records suppose 500, then your request string will be too long like this:-
{
"isRefresh" : false,
"cached" : ["id1","id2","id3","id4","id5","id6","id7","id8","id9","id10",………,"id500"]//Too long request
}
Approach 2: When server is smart enough to handle object states according to date.
You could send the id of first record and the last record and previous request epoch time. In this way your request is always small even if you’ve a big amount of cached records
Example:- If you are requesting load more then your request should look something like this:-
{
"isRefresh" : false,
"firstId" : "id1",
"lastId" : "id10",
"last_request_time" : 1421748005
}
Your server is responsible to return the id’s of deleted records which is deleted after the last_request_time as well as return the updated record after last_request_time between "id1" and "id10" .
{
"records" : [
{"id" :"id2","more_key":"updated_value"},
{"id" :"id11","more_key":"more_value"},
{"id" :"id12","more_key":"more_value"},
{"id" :"id13","more_key":"more_value"},
{"id" :"id14","more_key":"more_value"},
{"id" :"id15","more_key":"more_value"},
{"id" :"id16","more_key":"more_value"},
{"id" :"id17","more_key":"more_value"},
{"id" :"id18","more_key":"more_value"},
{"id" :"id19","more_key":"more_value"},
{"id" :"id20","more_key":"more_value"}],
"deleted" : ["id5","id8"]
}
Pull To Refresh:-
Load More
A simple client-side pagination example where data is fetched only once at page loading.
// dummy data_x000D_
const myarr = [{ "req_no": 1, "title": "test1" },_x000D_
{ "req_no": 2, "title": "test2" },_x000D_
{ "req_no": 3, "title": "test3" },_x000D_
{ "req_no": 4, "title": "test4" },_x000D_
{ "req_no": 5, "title": "test5" },_x000D_
{ "req_no": 6, "title": "test6" },_x000D_
{ "req_no": 7, "title": "test7" },_x000D_
{ "req_no": 8, "title": "test8" },_x000D_
{ "req_no": 9, "title": "test9" },_x000D_
{ "req_no": 10, "title": "test10" },_x000D_
{ "req_no": 11, "title": "test11" },_x000D_
{ "req_no": 12, "title": "test12" },_x000D_
{ "req_no": 13, "title": "test13" },_x000D_
{ "req_no": 14, "title": "test14" },_x000D_
{ "req_no": 15, "title": "test15" },_x000D_
{ "req_no": 16, "title": "test16" },_x000D_
{ "req_no": 17, "title": "test17" },_x000D_
{ "req_no": 18, "title": "test18" },_x000D_
{ "req_no": 19, "title": "test19" },_x000D_
{ "req_no": 20, "title": "test20" },_x000D_
{ "req_no": 21, "title": "test21" },_x000D_
{ "req_no": 22, "title": "test22" },_x000D_
{ "req_no": 23, "title": "test23" },_x000D_
{ "req_no": 24, "title": "test24" },_x000D_
{ "req_no": 25, "title": "test25" },_x000D_
{ "req_no": 26, "title": "test26" }];_x000D_
_x000D_
// on page load collect data to load pagination as well as table_x000D_
const data = { "req_per_page": document.getElementById("req_per_page").value, "page_no": 1 };_x000D_
_x000D_
// At a time maximum allowed pages to be shown in pagination div_x000D_
const pagination_visible_pages = 4;_x000D_
_x000D_
_x000D_
// hide pages from pagination from beginning if more than pagination_visible_pages_x000D_
function hide_from_beginning(element) {_x000D_
if (element.style.display === "" || element.style.display === "block") {_x000D_
element.style.display = "none";_x000D_
} else {_x000D_
hide_from_beginning(element.nextSibling);_x000D_
}_x000D_
}_x000D_
_x000D_
// hide pages from pagination ending if more than pagination_visible_pages_x000D_
function hide_from_end(element) {_x000D_
if (element.style.display === "" || element.style.display === "block") {_x000D_
element.style.display = "none";_x000D_
} else {_x000D_
hide_from_beginning(element.previousSibling);_x000D_
}_x000D_
}_x000D_
_x000D_
// load data and style for active page_x000D_
function active_page(element, rows, req_per_page) {_x000D_
var current_page = document.getElementsByClassName('active');_x000D_
var next_link = document.getElementById('next_link');_x000D_
var prev_link = document.getElementById('prev_link');_x000D_
var next_tab = current_page[0].nextSibling; _x000D_
var prev_tab = current_page[0].previousSibling;_x000D_
current_page[0].className = current_page[0].className.replace("active", "");_x000D_
if (element === "next") {_x000D_
if (parseInt(next_tab.text).toString() === 'NaN') {_x000D_
next_tab.previousSibling.className += " active";_x000D_
next_tab.setAttribute("onclick", "return false");_x000D_
} else {_x000D_
next_tab.className += " active"_x000D_
render_table_rows(rows, parseInt(req_per_page), parseInt(next_tab.text));_x000D_
if (prev_link.getAttribute("onclick") === "return false") {_x000D_
prev_link.setAttribute("onclick", `active_page('prev',\"${rows}\",${req_per_page})`);_x000D_
}_x000D_
if (next_tab.style.display === "none") {_x000D_
next_tab.style.display = "block";_x000D_
hide_from_beginning(prev_link.nextSibling)_x000D_
}_x000D_
}_x000D_
} else if (element === "prev") {_x000D_
if (parseInt(prev_tab.text).toString() === 'NaN') {_x000D_
prev_tab.nextSibling.className += " active";_x000D_
prev_tab.setAttribute("onclick", "return false");_x000D_
} else {_x000D_
prev_tab.className += " active";_x000D_
render_table_rows(rows, parseInt(req_per_page), parseInt(prev_tab.text));_x000D_
if (next_link.getAttribute("onclick") === "return false") {_x000D_
next_link.setAttribute("onclick", `active_page('next',\"${rows}\",${req_per_page})`);_x000D_
}_x000D_
if (prev_tab.style.display === "none") {_x000D_
prev_tab.style.display = "block";_x000D_
hide_from_end(next_link.previousSibling)_x000D_
}_x000D_
}_x000D_
} else {_x000D_
element.className += "active";_x000D_
render_table_rows(rows, parseInt(req_per_page), parseInt(element.text));_x000D_
if (prev_link.getAttribute("onclick") === "return false") {_x000D_
prev_link.setAttribute("onclick", `active_page('prev',\"${rows}\",${req_per_page})`);_x000D_
}_x000D_
if (next_link.getAttribute("onclick") === "return false") {_x000D_
next_link.setAttribute("onclick", `active_page('next',\"${rows}\",${req_per_page})`);_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
// Render the table's row in table request-table_x000D_
function render_table_rows(rows, req_per_page, page_no) {_x000D_
const response = JSON.parse(window.atob(rows));_x000D_
const resp = response.slice(req_per_page * (page_no - 1), req_per_page * page_no)_x000D_
$('#request-table').empty()_x000D_
$('#request-table').append('<tr><th>Index</th><th>Request No</th><th>Title</th></tr>');_x000D_
resp.forEach(function (element, index) {_x000D_
if (Object.keys(element).length > 0) {_x000D_
const { req_no, title } = element;_x000D_
const td = `<tr><td>${++index}</td><td>${req_no}</td><td>${title}</td></tr>`;_x000D_
$('#request-table').append(td)_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
// Pagination logic implementation_x000D_
function pagination(data, myarr) {_x000D_
const all_data = window.btoa(JSON.stringify(myarr));_x000D_
$(".pagination").empty();_x000D_
if (data.req_per_page !== 'ALL') {_x000D_
let pager = `<a href="#" id="prev_link" onclick=active_page('prev',\"${all_data}\",${data.req_per_page})>«</a>` +_x000D_
`<a href="#" class="active" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>1</a>`;_x000D_
const total_page = Math.ceil(parseInt(myarr.length) / parseInt(data.req_per_page));_x000D_
if (total_page < pagination_visible_pages) {_x000D_
render_table_rows(all_data, data.req_per_page, data.page_no);_x000D_
for (let num = 2; num <= total_page; num++) {_x000D_
pager += `<a href="#" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>${num}</a>`;_x000D_
}_x000D_
} else {_x000D_
render_table_rows(all_data, data.req_per_page, data.page_no);_x000D_
for (let num = 2; num <= pagination_visible_pages; num++) {_x000D_
pager += `<a href="#" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>${num}</a>`;_x000D_
}_x000D_
for (let num = pagination_visible_pages + 1; num <= total_page; num++) {_x000D_
pager += `<a href="#" style="display:none;" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>${num}</a>`;_x000D_
}_x000D_
}_x000D_
pager += `<a href="#" id="next_link" onclick=active_page('next',\"${all_data}\",${data.req_per_page})>»</a>`;_x000D_
$(".pagination").append(pager);_x000D_
} else {_x000D_
render_table_rows(all_data, myarr.length, 1);_x000D_
}_x000D_
}_x000D_
_x000D_
//calling pagination function_x000D_
pagination(data, myarr);_x000D_
_x000D_
_x000D_
// trigger when requests per page dropdown changes_x000D_
function filter_requests() {_x000D_
const data = { "req_per_page": document.getElementById("req_per_page").value, "page_no": 1 };_x000D_
pagination(data, myarr);_x000D_
}
_x000D_
.box {_x000D_
float: left;_x000D_
padding: 50px 0px;_x000D_
}_x000D_
_x000D_
.clearfix::after {_x000D_
clear: both;_x000D_
display: table;_x000D_
}_x000D_
_x000D_
.options {_x000D_
margin: 5px 0px 0px 0px;_x000D_
float: left;_x000D_
}_x000D_
_x000D_
.pagination {_x000D_
float: right;_x000D_
}_x000D_
_x000D_
.pagination a {_x000D_
color: black;_x000D_
float: left;_x000D_
padding: 8px 16px;_x000D_
text-decoration: none;_x000D_
transition: background-color .3s;_x000D_
border: 1px solid #ddd;_x000D_
margin: 0 4px;_x000D_
}_x000D_
_x000D_
.pagination a.active {_x000D_
background-color: #4CAF50;_x000D_
color: white;_x000D_
border: 1px solid #4CAF50;_x000D_
}_x000D_
_x000D_
.pagination a:hover:not(.active) {_x000D_
background-color: #ddd;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div>_x000D_
<table id="request-table">_x000D_
</table>_x000D_
</div>_x000D_
_x000D_
<div class="clearfix">_x000D_
<div class="box options">_x000D_
<label>Requests Per Page: </label>_x000D_
<select id="req_per_page" onchange="filter_requests()">_x000D_
<option>5</option>_x000D_
<option>10</option>_x000D_
<option>ALL</option>_x000D_
</select>_x000D_
</div>_x000D_
<div class="box pagination">_x000D_
</div>_x000D_
</div>
_x000D_
As far as I can see it on the website of that paginations plugin, the plugin itself doesn't do the actual pagination. The only thing it does is display a row of numbers, and display the correct buttons depending on the page you're on.
However, to actually paginate, you have to write the appropriate Javascript yourself. This should be placed in stead of this Javascript:
function test(pageNumber)
{
var page="#page-id-"+pageNumber;
$('.select').hide()
$(page).show()
}
Which is code I'm guessing you've copy-pasted from somewhere but at the moment doesn't really do anything. If you don't know Javascript, going with another library that actually does pagination of a table is something you probably want to do.
You can implement paging in this simple way by passing PageIndex
Declare @PageIndex INT = 1
Declare @PageSize INT = 20
Select ROW_NUMBER() OVER ( ORDER BY Products.Name ASC ) AS RowNumber,
Products.ID,
Products.Name
into #Result
From Products
SELECT @RecordCount = COUNT(*) FROM #Results
SELECT *
FROM #Results
WHERE RowNumber
BETWEEN
(@PageIndex -1) * @PageSize + 1
AND
(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1
LARAVEL 5
The view must contain something like:
{!! $myItems->appends(Input::except('page'))->render() !!}
I recently created this Pagination component that implements paging logic like Google's search results:
import React, { PropTypes } from 'react';
const propTypes = {
items: PropTypes.array.isRequired,
onChangePage: PropTypes.func.isRequired,
initialPage: PropTypes.number
}
const defaultProps = {
initialPage: 1
}
class Pagination extends React.Component {
constructor(props) {
super(props);
this.state = { pager: {} };
}
componentWillMount() {
this.setPage(this.props.initialPage);
}
setPage(page) {
var items = this.props.items;
var pager = this.state.pager;
if (page < 1 || page > pager.totalPages) {
return;
}
// get new pager object for specified page
pager = this.getPager(items.length, page);
// get new page of items from items array
var pageOfItems = items.slice(pager.startIndex, pager.endIndex + 1);
// update state
this.setState({ pager: pager });
// call change page function in parent component
this.props.onChangePage(pageOfItems);
}
getPager(totalItems, currentPage, pageSize) {
// default to first page
currentPage = currentPage || 1;
// default page size is 10
pageSize = pageSize || 10;
// calculate total pages
var totalPages = Math.ceil(totalItems / pageSize);
var startPage, endPage;
if (totalPages <= 10) {
// less than 10 total pages so show all
startPage = 1;
endPage = totalPages;
} else {
// more than 10 total pages so calculate start and end pages
if (currentPage <= 6) {
startPage = 1;
endPage = 10;
} else if (currentPage + 4 >= totalPages) {
startPage = totalPages - 9;
endPage = totalPages;
} else {
startPage = currentPage - 5;
endPage = currentPage + 4;
}
}
// calculate start and end item indexes
var startIndex = (currentPage - 1) * pageSize;
var endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);
// create an array of pages to ng-repeat in the pager control
var pages = _.range(startPage, endPage + 1);
// return object with all pager properties required by the view
return {
totalItems: totalItems,
currentPage: currentPage,
pageSize: pageSize,
totalPages: totalPages,
startPage: startPage,
endPage: endPage,
startIndex: startIndex,
endIndex: endIndex,
pages: pages
};
}
render() {
var pager = this.state.pager;
return (
<ul className="pagination">
<li className={pager.currentPage === 1 ? 'disabled' : ''}>
<a onClick={() => this.setPage(1)}>First</a>
</li>
<li className={pager.currentPage === 1 ? 'disabled' : ''}>
<a onClick={() => this.setPage(pager.currentPage - 1)}>Previous</a>
</li>
{pager.pages.map((page, index) =>
<li key={index} className={pager.currentPage === page ? 'active' : ''}>
<a onClick={() => this.setPage(page)}>{page}</a>
</li>
)}
<li className={pager.currentPage === pager.totalPages ? 'disabled' : ''}>
<a onClick={() => this.setPage(pager.currentPage + 1)}>Next</a>
</li>
<li className={pager.currentPage === pager.totalPages ? 'disabled' : ''}>
<a onClick={() => this.setPage(pager.totalPages)}>Last</a>
</li>
</ul>
);
}
}
Pagination.propTypes = propTypes;
Pagination.defaultProps
export default Pagination;
And here's an example App component that uses the Pagination component to paginate a list of 150 example items:
import React from 'react';
import Pagination from './Pagination';
class App extends React.Component {
constructor() {
super();
// an example array of items to be paged
var exampleItems = _.range(1, 151).map(i => { return { id: i, name: 'Item ' + i }; });
this.state = {
exampleItems: exampleItems,
pageOfItems: []
};
// bind function in constructor instead of render (https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md)
this.onChangePage = this.onChangePage.bind(this);
}
onChangePage(pageOfItems) {
// update state with new page of items
this.setState({ pageOfItems: pageOfItems });
}
render() {
return (
<div>
<div className="container">
<div className="text-center">
<h1>React - Pagination Example with logic like Google</h1>
{this.state.pageOfItems.map(item =>
<div key={item.id}>{item.name}</div>
)}
<Pagination items={this.state.exampleItems} onChangePage={this.onChangePage} />
</div>
</div>
<hr />
<div className="credits text-center">
<p>
<a href="http://jasonwatmore.com" target="_top">JasonWatmore.com</a>
</p>
</div>
</div>
);
}
}
export default App;
For more details and a live demo you can check out this post
You can use a subquery for this like
select *
from
( select *
from emp
order by sal desc )
where ROWNUM <= 5;
Have also a look at the topic On ROWNUM and limiting results at Oracle/AskTom for more information.
Update: To limit the result with both lower and upper bounds things get a bit more bloated with
select * from
( select a.*, ROWNUM rnum from
( <your_query_goes_here, with order by> ) a
where ROWNUM <= :MAX_ROW_TO_FETCH )
where rnum >= :MIN_ROW_TO_FETCH;
(Copied from specified AskTom-article)
Update 2: Starting with Oracle 12c (12.1) there is a syntax available to limit rows or start at offsets.
SELECT *
FROM sometable
ORDER BY name
OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;
See this answer for more examples. Thanks to Krumia for the hint.
<?php
// Custom PHP MySQL Pagination Tutorial and Script
// You have to put your mysql connection data and alter the SQL queries(both queries)
mysql_connect("DATABASE_Host_Here","DATABASE_Username_Here","DATABASE_Password_Here") or die (mysql_error());
mysql_select_db("DATABASE_Name_Here") or die (mysql_error());
////////////// QUERY THE MEMBER DATA INITIALLY LIKE YOU NORMALLY WOULD
$sql = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC");
//////////////////////////////////// Pagination Logic ////////////////////////////////////////////////////////////////////////
$nr = mysql_num_rows($sql); // Get total of Num rows from the database query
if (isset($_GET['pn'])) { // Get pn from URL vars if it is present
$pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); // filter everything but numbers for security(new)
//$pn = ereg_replace("[^0-9]", "", $_GET['pn']); // filter everything but numbers for security(deprecated)
} else { // If the pn URL variable is not present force it to be value of page number 1
$pn = 1;
}
//This is where we set how many database items to show on each page
$itemsPerPage = 10;
// Get the value of the last page in the pagination result set
$lastPage = ceil($nr / $itemsPerPage);
// Be sure URL variable $pn(page number) is no lower than page 1 and no higher than $lastpage
if ($pn < 1) { // If it is less than 1
$pn = 1; // force if to be 1
} else if ($pn > $lastPage) { // if it is greater than $lastpage
$pn = $lastPage; // force it to be $lastpage's value
}
// This creates the numbers to click in between the next and back buttons
// This section is explained well in the video that accompanies this script
$centerPages = "";
$sub1 = $pn - 1;
$sub2 = $pn - 2;
$add1 = $pn + 1;
$add2 = $pn + 2;
if ($pn == 1) {
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> ';
} else if ($pn == $lastPage) {
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
} else if ($pn > 2 && $pn < ($lastPage - 1)) {
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a> ';
} else if ($pn > 1 && $pn < $lastPage) {
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> ';
}
// This line sets the "LIMIT" range... the 2 values we place to choose a range of rows from database in our query
$limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage;
// Now we are going to run the same query as above but this time add $limit onto the end of the SQL syntax
// $sql2 is what we will use to fuel our while loop statement below
$sql2 = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC $limit");
//////////////////////////////// END Pagination Logic ////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Pagination Display Setup /////////////////////////////////////////////////////////////////////
$paginationDisplay = ""; // Initialize the pagination output variable
// This code runs only if the last page variable is ot equal to 1, if it is only 1 page we require no paginated links to display
if ($lastPage != "1"){
// This shows the user what page they are on, and the total number of pages
$paginationDisplay .= 'Page <strong>' . $pn . '</strong> of ' . $lastPage. ' ';
// If we are not on page 1 we can place the Back button
if ($pn != 1) {
$previous = $pn - 1;
$paginationDisplay .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $previous . '"> Back</a> ';
}
// Lay in the clickable numbers display here between the Back and Next links
$paginationDisplay .= '<span class="paginationNumbers">' . $centerPages . '</span>';
// If we are not on the very last page we can place the Next button
if ($pn != $lastPage) {
$nextPage = $pn + 1;
$paginationDisplay .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $nextPage . '"> Next</a> ';
}
}
///////////////////////////////////// END Pagination Display Setup ///////////////////////////////////////////////////////////////////////////
// Build the Output Section Here
$outputList = '';
while($row = mysql_fetch_array($sql2)){
$id = $row["id"];
$firstname = $row["firstname"];
$country = $row["country"];
$outputList .= '<h1>' . $firstname . '</h1><h2>' . $country . ' </h2><hr />';
} // close while loop
?>
<html>
<head>
<title>Simple Pagination</title>
</head>
<body>
<div style="margin-left:64px; margin-right:64px;">
<h2>Total Items: <?php echo $nr; ?></h2>
</div>
<div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
<div style="margin-left:64px; margin-right:64px;"><?php print "$outputList"; ?></div>
<div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
</body>
</html>
ng-repeat pagination
<div ng-app="myApp" ng-controller="MyCtrl">
<input ng-model="q" id="search" class="form-control" placeholder="Filter text">
<select ng-model="pageSize" id="pageSize" class="form-control">
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
</select>
<ul>
<li ng-repeat="item in data | filter:q | startFrom:currentPage*pageSize | limitTo:pageSize">
{{item}}
</li>
</ul>
<button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">
Previous
</button>
{{currentPage+1}}/{{numberOfPages()}}
<button ng-disabled="currentPage >= getData().length/pageSize - 1" ng- click="currentPage=currentPage+1">
Next
</button>
</div>
<script>
var app=angular.module('myApp', []);
app.controller('MyCtrl', ['$scope', '$filter', function ($scope, $filter) {
$scope.currentPage = 0;
$scope.pageSize = 10;
$scope.data = [];
$scope.q = '';
$scope.getData = function () {
return $filter('filter')($scope.data, $scope.q)
}
$scope.numberOfPages=function(){
return Math.ceil($scope.getData().length/$scope.pageSize);
}
for (var i=0; i<65; i++) {
$scope.data.push("Item "+i);
}
}]);
app.filter('startFrom', function() {
return function(input, start) {
start = +start; //parse to int
return input.slice(start);
}
});
</script>
CREATE view vw_sppb_part_listsource as
select row_number() over (partition by sppb_part.init_id order by sppb_part.sppb_part_id asc ) as idx, * from (
select
part.SPPB_PART_ID
, 0 as is_rev
, part.part_number
, part.init_id
from t_sppb_init_part part
left join t_sppb_init_partrev prev on ( part.SPPB_PART_ID = prev.SPPB_PART_ID )
where prev.SPPB_PART_ID is null
union
select
part.SPPB_PART_ID
, 1 as is_rev
, prev.part_number
, part.init_id
from t_sppb_init_part part
inner join t_sppb_init_partrev prev on ( part.SPPB_PART_ID = prev.SPPB_PART_ID )
) sppb_part
will restart idx when it comes to different init_id
Use all SQL server: ;with tbl as (SELECT ROW_NUMBER() over(order by(select 1)) as RowIndex,* from table) select top 10 * from tbl where RowIndex>=10
Java inbuilt libraries support only AIFC, AIFF, AU, SND and WAVE formats. Here I only discussed playing an audio file using Clip only and see the various methods of a clip.
PlayAudio.java
.Audio.java
.PlayAudio.java
import java.io.IOException;
import java.util.Scanner;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class PlayAudio {
public static void main(String[] args) throws
UnsupportedAudioFileException, IOException,
LineUnavailableException {
PlayMp3 playMp3;
playMp3=new PlayMp3();
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter Choice :-");
System.out.println("1. Play");
System.out.println("2. pause");
System.out.println("3. resume");
System.out.println("4. restart");
System.out.println("5. stop");
System.out.println(PlayMp3.status);
System.out.println(":::- ");
int c = sc.nextInt();
if (c ==5){
playMp3.stop();
break;
}
switch (c) {
case 1:
playMp3.play();
break;
case 2:
playMp3.pause();
break;
case 3:
playMp3.resume();
break;
case 4:
playMp3.restart();
break;
case 5:
playMp3.stop();
default:
System.out.println("Please Enter Valid Option :-");
}
}
sc.close();
}
}
Audio.java
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
public class Audio {
private String filePath="mp.snd";
public static String status="paused";
private Long currentFrame=0L;
private Clip clip;
private AudioInputStream audioInputStream;
public Audio() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
audioInputStream = AudioSystem.getAudioInputStream(new File(filePath));
clip = AudioSystem.getClip();
clip.open(audioInputStream);
}
public void play(){
clip.start();
status = "playing";
}
public void pause(){
if (status.equals("paused")) {
System.out.println("audio is already paused");
return;
}
currentFrame = clip.getMicrosecondPosition();
clip.stop();
status = "paused";
}
public void resume() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
if (status.equals("play"))
{
System.out.println("Audio is already being playing");
return;
}
clip.close();
//starts again and goes to currentFrame
resetAudioStream();
clip.setMicrosecondPosition(currentFrame);
play();
status="playing";
}
public void restart() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
clip.stop();
clip.close();
resetAudioStream();
currentFrame = 0L;
clip.setMicrosecondPosition(0);
play();
status="Playing from start";
}
public void stop(){
currentFrame = 0L;
clip.stop();
clip.close();
status="stopped";
}
private void resetAudioStream() throws IOException, UnsupportedAudioFileException, LineUnavailableException {
audioInputStream = AudioSystem.getAudioInputStream(new File(filePath).getAbsoluteFile());
clip.open(audioInputStream);
}
}
The accepted answer does not remove text that could be before Here
or after String
. This will:
sed -e 's/.*Here\(.*\)String.*/\1/'
The main difference is the addition of .*
immediately before Here
and after String
.
Use:
function form_to_json (selector) {
var ary = $(selector).serializeArray();
var obj = {};
for (var a = 0; a < ary.length; a++) obj[ary[a].name] = ary[a].value;
return obj;
}
Output:
{"myfield": "myfield value", "passwordfield": "mypasswordvalue"}
Here is my code for that:
$('#date-daily').datepicker().on('changeDate', function(e) {
//$('#other-input').val(e.format(0,"dd/mm/yyyy"));
//alert(e.date);
//alert(e.format(0,"dd/mm/yyyy"));
//console.log(e.date);
});
Just uncomment the one you prefer. The first option changes the value of other input element. The second one alerts the date with datepicker default format. The third one alerts the date with your own custom format. The last option outputs to log (default format date).
It's your choice to use the e.date , e.dates (for múltiple date input) or e.format(...).
here some more info
I can recommend jOOQ. It provides a lot of great features, also a intuitive DSL for SQL and a extremly customable reverse-engineering approach.
jOOQ effectively combines complex SQL, typesafety, source code generation, active records, stored procedures, advanced data types, and Java in a fluent, intuitive DSL.
As for me I've solved this problem by next way - as developer.android.com says, after adding google-play-services_lib you should add <meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
in your manifest, but on the new SDK you'll always get an error:
Error: No resource found that matches the given name (at 'value' with value '@integer/ google_play_services_version').
To solve that error many people advise to use a raw value, 4030500, instead of @integer/google_play_services_version
, but it is correct ONLY for Google services revision 13.
If you use any older version or version for Froyo (like me) you should put another value in it. To know what value you should put just open a Google Play services manifest and copy-paste a version_code value. For Froyo services, it is 3265130. After adding this I've stopped getting this error, and I've began to receive coordinates in my application at last.
To install the GPL version of PyQt5, run (see PyQt5 Project):
pip3 install pyqt5
This will install the Python wheel for your platform and your version of Python (assuming both are supported).
(The wheel will be automatically downloaded from the Python Package Index.)
The PyQt5 wheel includes the necessary parts of the LGPL version of Qt. There is no need to install Qt yourself.
(The required sip
is packaged as a separate wheel and will be downloaded and installed automatically.)
Note:
If you get an error message saying something as
No downloads could be found that satisfy the requirement
then you are probably using an unsupported version of Python.
you may include bootstrap to your html file and you put it under the style file so if you do that bootstrap file will override the style file briefly like this
// style file
<link rel="stylesheet" href="css/style.css" />
// bootstrap file
<link rel="stylesheet" href="css/bootstrap.min.css" />
the right way is this
// bootstrap file
<link rel="stylesheet" href="css/bootstrap.min.css" />
// style file
<link rel="stylesheet" href="css/style.css" />
Look here for the answer by TheMattster. I implemented it and it worked like a charm. In a nutshell, his solution suggests to add the COM dll as a resource to the project (so now it compiles into the project's dll), and upon the first run write it to a file (i.e. the dll file I wanted there in the first place).
The following is taken from his answer.
Step 1) Add the DLL as a resource (below as "Resources.DllFile"). To do this open project properties, select the resources tab, select "add existing file" and add the DLL as a resource.
Step 2) Add the name of the DLL as a string resource (below as "Resources.DllName").
Step 3) Add this code to your main form-load:
if (!File.Exists(Properties.Resources.DllName))
{
var outStream = new StreamWriter(Properties.Resources.DllName, false);
var binStream = new BinaryWriter(outStream.BaseStream);
binStream.Write(Properties.Resources.DllFile);
binStream.Close();
}
My problem was that not only I had to use the COM dll in my project, I also had to deploy it with my app using ClickOnce, and without being able to add reference to it in my project the above solution is practically the only one that worked.
You could call std::terminate()
from any thread and the thread you're referring to will forcefully end.
You could arrange for ~thread()
to be executed on the object of the target thread, without a intervening join()
nor detach()
on that object. This will have the same effect as option 1.
You could design an exception which has a destructor which throws an exception. And then arrange for the target thread to throw this exception when it is to be forcefully terminated. The tricky part on this one is getting the target thread to throw this exception.
Options 1 and 2 don't leak intra-process resources, but they terminate every thread.
Option 3 will probably leak resources, but is partially cooperative in that the target thread has to agree to throw the exception.
There is no portable way in C++11 (that I'm aware of) to non-cooperatively kill a single thread in a multi-thread program (i.e. without killing all threads). There was no motivation to design such a feature.
A std::thread
may have this member function:
native_handle_type native_handle();
You might be able to use this to call an OS-dependent function to do what you want. For example on Apple's OS's, this function exists and native_handle_type
is a pthread_t
. If you are successful, you are likely to leak resources.
To retain "pretty-print" use
from IPython.display import HTML
HTML(df.to_html(index=False))
Iterator is super class of ListIterator.
Here are the differences between them:
iterator
you can move only forward, but with ListIterator
you can move backword also while reading the elements.ListIterator
you can obtain the index at any point while traversing, which is not possible with iterator
s.iterator
you can check only for next element available or not, but in listiterator
you can check previous and next elements.listiterator
you can add new element at any point of time, while traversing. Not possible with iterator
.listiterator
you can modify an element while traversing, which is not possible with iterator
.Iterator look and feel:
public interface Iterator<E> {
boolean hasNext();
E next();
void remove(); //optional-->use only once with next(),
dont use it when u use for:each
}
ListIterator look and feel:
public interface ListIterator<E> extends Iterator<E> {
boolean hasNext();
E next();
boolean hasPrevious();
E previous();
int nextIndex();
int previousIndex();
void remove(); //optional
void set(E e); //optional
void add(E e); //optional
}
I recommend web storage. Example:
// Storing the data:
localStorage.setItem("variableName","Text");
// Receiving the data:
localStorage.getItem("variableName");
Just replace variable
with your variable name and text
with what you want to store. According to W3Schools, it's better than cookies.
I think this is what you're looking for. NEW_BAL
is the sum of QTY
s subtracted from the balance:
SELECT master_table.ORDERNO,
master_table.ITEM,
SUM(master_table.QTY),
stock_bal.BAL_QTY,
(stock_bal.BAL_QTY - SUM(master_table.QTY)) AS NEW_BAL
FROM master_table INNER JOIN
stock_bal ON master_bal.ITEM = stock_bal.ITEM
GROUP BY master_table.ORDERNO,
master_table.ITEM
If you want to update the item balance with the new balance, use the following:
UPDATE stock_bal
SET BAL_QTY = BAL_QTY - (SELECT SUM(QTY)
FROM master_table
GROUP BY master_table.ORDERNO,
master_table.ITEM)
This assumes you posted the subtraction backward; it subtracts the quantities in the order from the balance, which makes the most sense without knowing more about your tables. Just swap those two to change it if I was wrong:
(SUM(master_table.QTY) - stock_bal.BAL_QTY) AS NEW_BAL
I get this error all the time and consider it normal.
It happens when one side tries to read when the other side has already hung up. Thus depending on the protocol this may or may not designate a problem. If my client code specifically indicates to the server that it is going to hang up, then both client and server can hang up at the same time and this message would not happen.
The way I implement my code is for the client to just hang up without saying goodbye. The server can then catch the error and ignore it. In the context of HTTP, I believe one level of the protocol allows more then one request per connection while the other doesn't.
Thus you can see how potentially one side could keep hanging up on the other. I doubt the error you are receiving is of any piratical concern and you could simply catch it to keep it from filling up your log files.
This can be done by the below code.
CREATE TABLE TestTable
(FirstCol INT NOT NULL)
GO
------------------------------
-- Option 1
------------------------------
-- Adding New Column
ALTER TABLE TestTable
ADD SecondCol INT
GO
-- Updating it with Default
UPDATE TestTable
SET SecondCol = 0
GO
-- Alter
ALTER TABLE TestTable
ALTER COLUMN SecondCol INT NOT NULL
GO
Till yesterday I was able to connect to phpMyAdmin, but today I started getting this error:
2002-no-connection-could-be-made-because-the-target-machine-actively-refused
None of the answers here really helped me fix the problem, what helped me is shared below:
I looked at the mysql logs.[C:\wamp\logs\mysql.log]
It said
2015-09-18 01:16:30 5920 [Note] Plugin 'FEDERATED' is disabled.
2015-09-18 01:16:30 5920 [Note] InnoDB: Using atomics to ref count buffer pool pages
2015-09-18 01:16:30 5920 [Note] InnoDB: The InnoDB memory heap is disabled
2015-09-18 01:16:30 5920 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2015-09-18 01:16:30 5920 [Note] InnoDB: Compressed tables use zlib 1.2.3
2015-09-18 01:16:30 5920 [Note] InnoDB: Not using CPU crc32 instructions
2015-09-18 01:16:30 5920 [Note] InnoDB: Initializing buffer pool, size = 128.0M
2015-09-18 01:16:30 5920 [Note] InnoDB: Completed initialization of buffer pool
2015-09-18 01:16:30 5920 [Note] InnoDB: Highest supported file format is Barracuda.
2015-09-18 01:16:30 5920 [Note] InnoDB: The log sequence numbers 1765410 and 1765410 in ibdata files do not match the log sequence number 2058233 in the ib_logfiles!
2015-09-18 01:16:30 5920 [Note] InnoDB: Database was not shutdown normally!
2015-09-18 01:16:30 5920 [Note] InnoDB: Starting crash recovery.
2015-09-18 01:16:30 5920 [Note] InnoDB: Reading tablespace information from the .ibd files...
2015-09-18 01:16:30 5920 [ERROR] InnoDB: Attempted to open a previously opened tablespace. Previous tablespace harley/login_confirm uses space ID: 6 at filepath: .\harley\login_confirm.ibd. Cannot open tablespace testdb/testtable which uses space ID: 6 at filepath: .\testdb\testtable.ibd
InnoDB: Error: could not open single-table tablespace file .\testdb\testtable.ibd
InnoDB: We do not continue the crash recovery, because the table may become
InnoDB: corrupt if we cannot apply the log records in the InnoDB log to it.
InnoDB: To fix the problem and start mysqld:
InnoDB: 1) If there is a permission problem in the file and mysqld cannot
InnoDB: open the file, you should modify the permissions.
InnoDB: 2) If the table is not needed, or you can restore it from a backup,
InnoDB: then you can remove the .ibd file, and InnoDB will do a normal
InnoDB: crash recovery and ignore that table.
InnoDB: 3) If the file system or the disk is broken, and you cannot remove
InnoDB: the .ibd file, you can set innodb_force_recovery > 0 in my.cnf
InnoDB: and force InnoDB to continue crash recovery here.
I got the clue that this guy is creating a problem - InnoDB: Error: could not open single-table tablespace file .\testdb\testtable.ibd
and this line 2015-09-18 01:16:30 5920 [Note] InnoDB: Database was not shutdown normally!
hmmm, For me the testdb was just a test-db! hence I decided to delete this file inside C:\wamp\bin\mysql\mysql5.6.17\data\testdb
and restarted all services, and went to phpMyAdmin, and this time no issues, phpMyAdmin opened :)
Gson is also good for it: http://code.google.com/p/google-gson/
" Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. "
Check the API examples: https://sites.google.com/site/gson/gson-user-guide#TOC-Overview More examples: http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
For those having the same glitch with <LinearLayout...>
as I did:
It is important to specify android:layout_width="fill_parent"
, it will not work with wrap_content
.
OTOH, you may omit android:layout_weight = "0"
, it is not required.
My code is basically the same as the code in https://stackoverflow.com/a/25781167/755804 (by Vivek Pandey)
I had this issue recently. In my case, I had my IDE set to choose which compiler (C or C++) to use on each file according to its extension, and I was trying to call a C function (i.e. from a .c
file) from C++ code.
The .h
file for the C function wasn't wrapped in this sort of guard:
#ifdef __cplusplus
extern "C" {
#endif
// all of your legacy C code here
#ifdef __cplusplus
}
#endif
I could've added that, but I didn't want to modify it, so I just included it in my C++ file like so:
extern "C" {
#include "legacy_C_header.h"
}
(Hat tip to UncaAlby for his clear explanation of the effect of extern "C".)
Theres a setting max_input_time
(on Apache) for many webservers that defines how long they will wait for post data, regardless of the size. If this time runs out the connection is closed without even touching the php.
So your problem is not necessarily solvable with php only but you will need to change the server settings too.
Just in case... Apache Tomcat 8.5.X is not compatible with Apache Tomcat 8.0 server selection in eclipse. And it gives this error.
You are using the wrong iteration counter, replace inp.charAt(i)
with inp.charAt(j)
.
When plotting a plot using matplotlib:
How to remove the box of the legend?
plt.legend(frameon=False)
How to change the color of the border of the legend box?
leg = plt.legend()
leg.get_frame().set_edgecolor('b')
How to remove only the border of the box of the legend?
leg = plt.legend()
leg.get_frame().set_linewidth(0.0)
random_matrix = [[random.random for j in range(collumns)] for i in range(rows)
for i in range(rows):
print random_matrix[i]
Because my edits to the above were rejected (did any of you actually try?), here's what you really need to make this work:
Windows (And Mac Office 2011+):
(Excel Timestamp - 25569) * 86400
(Unix Timestamp / 86400) + 25569
MAC OS X (pre Office 2011):
(Excel Timestamp - 24107) * 86400
(Unix Timestamp / 86400) + 24107
pmg is spot on about encapsulation; beyond hiding the function from other translation units (or rather, because of it), making functions static
can also confer performance benefits in the presence of compiler optimizations.
Because a static
function cannot be called from anywhere outside of the current translation unit (unless the code takes a pointer to its address), the compiler controls all the call points into it.
This means that it is free to use a non-standard ABI, inline it entirely, or perform any number of other optimizations that might not be possible for a function with external linkage.
Here is a way to do it without involving Console
:
var endlessTask = new TaskCompletionSource<bool>().Task;
endlessTask.Wait();
I was looking at this post to find the answer but... I think everyone on this post was facing the same scenario as me: scrollToPosition()
was fully ignored, for an evident reason.
What I was using?
recyclerView.scrollToPosition(items.size());
... what WORKED?
recyclerView.scrollToPosition(items.size() - 1);
This could be as simple as:
@Column(name = "Some_Column", nullable = false)
but while persisting, the value of "Some_Column"is null, even if "Some_Column" may not be any primary or foreign key.
you can use "__range" for example :
from datetime import datetime
start_date=datetime(2009, 12, 30)
end_end=datetime(2020,12,30)
Sample.objects.filter(date__range=[start_date,end_date])
You're looking for Select
which can be used to transform\project the input sequence:
IEnumerable<string> strings = integers.Select(i => i.ToString());
Remove stop words from the text file using Python
print('====THIS IS HOW TO REMOVE STOP WORS====')
with open('one.txt','r')as myFile:
str1=myFile.read()
stop_words ="not", "is", "it", "By","between","This","By","A","when","And","up","Then","was","by","It","If","can","an","he","This","or","And","a","i","it","am","at","on","in","of","to","is","so","too","my","the","and","but","are","very","here","even","from","them","then","than","this","that","though","be","But","these"
myList=[]
myList.extend(str1.split(" "))
for i in myList:
if i not in stop_words:
print ("____________")
print(i,end='\n')
In a crontab
file, the fields are:
So:
10 * * * * blah
means execute blah
at 10 minutes past every hour.
If you want every five minutes, use either:
*/5 * * * * blah
meaning every minute but only every fifth one, or:
0,5,10,15,20,25,30,35,40,45,50,55 * * * * blah
for older cron
executables that don't understand the */x
notation.
If it still seems to be not working after that, change the command to something like:
date >>/tmp/debug_cron_pax.txt
and monitor that file to ensure something's being written every five minutes. If so, there's something wrong with your PHP scripts. If not, there's something wrong with your cron
daemon.
The Content-Type
header is just used as info for your application. The browser doesn't care what it is. The browser just returns you the data from the AJAX call. If you want to parse it as JSON, you need to do that on your own.
The header is there so your app can detect what data was returned and how it should handle it. You need to look at the header, and if it's application/json
then parse it as JSON.
This is actually how jQuery works. If you don't tell it what to do with the result, it uses the Content-Type
to detect what to do with it.
The correct way to do this is:
String[] stockArr = stock_list.toArray(new String[stock_list.size()]);
I'd like to add to the other great answers here and explain how you could have used the Javadocs to answer your question.
The Javadoc for toArray()
(no arguments) is here. As you can see, this method returns an Object[]
and not String[]
which is an array of the runtime type of your list:
public Object[] toArray()
Returns an array containing all of the elements in this collection. If the collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order. The returned array will be "safe" in that no references to it are maintained by the collection. (In other words, this method must allocate a new array even if the collection is backed by an Array). The caller is thus free to modify the returned array.
Right below that method, though, is the Javadoc for toArray(T[] a)
. As you can see, this method returns a T[]
where T
is the type of the array you pass in. At first this seems like what you're looking for, but it's unclear exactly why you're passing in an array (are you adding to it, using it for just the type, etc). The documentation makes it clear that the purpose of the passed array is essentially to define the type of array to return (which is exactly your use case):
public <T> T[] toArray(T[] a)
Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection. If the collection fits in the specified array with room to spare (i.e., the array has more elements than the collection), the element in the array immediately following the end of the collection is set to null. This is useful in determining the length of the collection only if the caller knows that the collection does not contain any null elements.)
If this collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.
This implementation checks if the array is large enough to contain the collection; if not, it allocates a new array of the correct size and type (using reflection). Then, it iterates over the collection, storing each object reference in the next consecutive element of the array, starting with element 0. If the array is larger than the collection, a null is stored in the first location after the end of the collection.
Of course, an understanding of generics (as described in the other answers) is required to really understand the difference between these two methods. Nevertheless, if you first go to the Javadocs, you will usually find your answer and then see for yourself what else you need to learn (if you really do).
Also note that reading the Javadocs here helps you to understand what the structure of the array you pass in should be. Though it may not really practically matter, you should not pass in an empty array like this:
String [] stockArr = stockList.toArray(new String[0]);
Because, from the doc, this implementation checks if the array is large enough to contain the collection; if not, it allocates a new array of the correct size and type (using reflection). There's no need for the extra overhead in creating a new array when you could easily pass in the size.
As is usually the case, the Javadocs provide you with a wealth of information and direction.
Hey wait a minute, what's reflection?
Inserting 'test' to name will lead to inserting NULL
values to other columns of the base table which wont be correct as Id is a PRIMARY KEY
and it cannot have NULL
value.
Here is another good alternative:
Array.from({ length: 3}).map(...);
Preferably, as @Dave Morse pointed out in the comments, you can also get rid of the map
call, by using the second parameter of the Array.from
function like so:
Array.from({ length: 3 }, () => (...))
i got same problem and i solved
gem update --system 3.0.6
The easiest way to stream video via IP Camera !
I just edit your example. You must replace your IP and add /video
on your link. And go ahead with your project
import cv2
cap = cv2.VideoCapture('http://192.168.18.37:8090/video')
while(True):
ret, frame = cap.read()
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
One of the ways that you can run your spring-boot application from command line is as follows :
1) First go to your project directory in command line [where is your project located ?]
2) Then in the next step you have to create jar file for that, this can be done as
mvnw package
[for WINDOWS OS ] or ./mvnw package
[for MAC OS] , this will
create jar file for our application.
3) jar file is created in the target sub-directory
4)Now go to target sub directory as jar was created inside of it , i.e cd target
5) Now run the jar file in there.
Use command java -jar name.jar
[ name is the name of your created jar file.]
and there you go , you are done . Now you can run project in browser,
http://localhost:port_number
Other way to solve the problem of space reclaiming is, Create multiple partitions within table - Range based, Value based partitions and just drop/truncate the partition to reclaim the space, which will release the space used by whole data stored in the particular partition.
There will be some changes needed in table schema when you introduce the partitioning for your table like - Unique Keys, Indexes to include partition column etc.
If you're just trying to find out where npm is installing your global module (the title of this thread), look at the output when running npm install -g sample_module
$ npm install -g sample_module C:\Users\user\AppData\Roaming\npm\sample_module -> C:\Users\user\AppData\Roaming\npm\node_modules\sample_module\bin\sample_module.js + [email protected] updated 1 package in 2.821s
Add { } while importing and exporting:
export { ... };
|
import { ... } from './Template';
export → import { ... } from './Template'
export default → import ... from './Template'
Here is a working example:
// ExportExample.js
import React from "react";
function DefaultExport() {
return "This is the default export";
}
function Export1() {
return "Export without default 1";
}
function Export2() {
return "Export without default 2";
}
export default DefaultExport;
export { Export1, Export2 };
// App.js
import React from "react";
import DefaultExport, { Export1, Export2 } from "./ExportExample";
export default function App() {
return (
<>
<strong>
<DefaultExport />
</strong>
<br />
<Export1 />
<br />
<Export2 />
</>
);
}
??Working sandbox to play around: https://codesandbox.io/s/export-import-example-react-jl839?fontsize=14&hidenavigation=1&theme=dark
SOLVED: I faced this error and i cant understand, it took 5 hours.
Solution: project properties/Project faced/Dynamic web-module version set to 3.0
after one week ,I got same error
FIXED2 gwt-project-external-mode-main-main-nocache-js-not-found
Update: Please read blmstr's answer below before pulling a whole feature detection library into your project. Detecting actual touch support is more complex, and Modernizr only covers a basic use case.
Modernizr is a great, lightweight way to do all kinds of feature detection on any site.
It simply adds classes to the html element for each feature.
You can then target those features easily in CSS and JS. For example:
html.touch div {
width: 480px;
}
html.no-touch div {
width: auto;
}
And Javascript (jQuery example):
$('html.touch #popup').hide();
I know its already answered, but theres a better solution here use this code :
for ( Field f : context.getFields() ) {
if ( f.getType() == String.class ) || ( f.getType() == String.class ) ) {
//DO String To JSON
}
/// And so on...
}
This way you can access variables from class without manually typing them..
Faster and better .. Hope this helps.
Cheers. :D
std::string trimmed(std::string str ) {
if(str.length() == 0 ) { return "" ; }
else if ( str == std::string(" ") ) { return "" ; }
else {
while(str.at(0) == ' ') { str.erase(0, 1);}
while(str.at(str.length()-1) == ' ') { str.pop_back() ; }
return str ;
}
}
difference is that int the inner(equi/default)join and natural join that in the natuarl join common column win will be display in single time but inner/equi/default/simple join the common column will be display double time.
To fix this, you need to supply an extra parameter to openssl
when you're creating the cert, basically
-sha256 -extfile v3.ext
where v3.ext
is a file like so, with %%DOMAIN%%
replaced with the same name you use as your Common Name
. More info here and over here. Note that typically you'd set the Common Name
and %%DOMAIN%%
to the domain you're trying to generate a cert for. So if it was www.mysupersite.com
, then you'd use that for both.
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = %%DOMAIN%%
Another note: If all you're trying to do is stop chrome from throwing errors when viewing a self signed certificate, you can can tell Chrome to ignore all SSL errors for ALL sites by starting it with a special command line option, as detailed here on SuperUser
Actully what work for me is:
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
and to undo it:
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
Since you already have <Tags>
component calling a function on its parent, you do not need additional state: simply pass the filter to the <Tags>
component as a prop, and use this in rendering your buttons. Like so:
Change your render function inside your <Tags>
component to:
render: function() {
return <div className = "tags">
<button className = {this._checkActiveBtn('')} onClick = {this.setFilter.bind(this, '')}>All</button>
<button className = {this._checkActiveBtn('male')} onClick = {this.setFilter.bind(this, 'male')}>male</button>
<button className = {this._checkActiveBtn('female')} onClick = {this.setFilter.bind(this, 'female')}>female</button>
<button className = {this._checkActiveBtn('blonde')} onClick = {this.setFilter.bind(this, 'blonde')}>blonde</button>
</div>
},
And add a function inside <Tags>
:
_checkActiveBtn: function(filterName) {
return (filterName == this.props.activeFilter) ? "btn active" : "btn";
}
And inside your <List>
component, pass the filter state to the <tags>
component as a prop:
return <div>
<h2>Kids Finder</h2>
<Tags filter = {this.state.filter} onChangeFilter = {this.changeFilter} />
{list}
</div>
Then it should work as intended. Codepen here (hope the link works)
None of the above worked for me. Here's my vanilla.js solution:
(function() {
function handleSubmit(event) {
var form = event.target;
var nodes = form.querySelectorAll("input[disabled]");
for (var node of nodes) {
node.disabled = false;
}
}
function init() {
var submit_form_tag = document.getElementById('new_whatever');
submit_form_tag.addEventListener('submit', handleSubmit, true);
}
window.onload = init_beworst;
})();
Be sure to provide an appropriate replacement for the form id.
My application has a bit of context, where some boxes are pre-checked, and others you have a limit of how many of the other boxes you can check. When you hit that limit, all the non-pre-checked boxes are disabled, and if you uncheck one all the non-pre-checked boxes are enabled again. When the user presses submit all the checked boxes are submitted to the user, regardless of whether they're pre-checked or not.
Here is the example to understand the difference
int i=10;
printf("%d %d",i++,++i);
output: 10 12/11 11
(depending on the order of evaluation of arguments to the printf
function, which varies across compilers and architectures)
Explanation:
i++
->i
is printed, and then increments. (Prints 10, but i
will become 11)
++i
->i
value increments and prints the value. (Prints 12, and the value of i
also 12)
In your case, it's the best to use rotate option from transform property as mentioned before. There is also writing-mode
property and it works like rotate(90deg) so in your case, it should be rotated after it's applied. Even it's not the right solution in this case but you should be aware of this property.
Example:
writing-mode:vertical-rl;
More about transform: https://kolosek.com/css-transform/
More about writing-mode: https://css-tricks.com/almanac/properties/w/writing-mode/
If you set up your file system differently or looking for a different way of setting up a file system and then checking if a file exists in the documents folder heres an another example. also show dynamic checking
for (int i = 0; i < numberHere; ++i){
NSFileManager* fileMgr = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString* imageName = [NSString stringWithFormat:@"image-%@.png", i];
NSString* currentFile = [documentsDirectory stringByAppendingPathComponent:imageName];
BOOL fileExists = [fileMgr fileExistsAtPath:currentFile];
if (fileExists == NO){
cout << "DOESNT Exist!" << endl;
} else {
cout << "DOES Exist!" << endl;
}
}
My problem was that the Id of the table is not AUTO_INCREMENT and I was trying to add range.
If you look at the examples on the api page there is this: Example: Creates a different alias instead of jQuery to use in the rest of the script.
var j = jQuery.noConflict();
// Do something with jQuery
j("div p").hide();
// Do something with another library's $()
$("content").style.display = 'none';
Put the var j = jQuery.noConflict()
after you bring in jquery and then bring in the conflicting scripts. You can then use the j
in place of $
for all your jquery needs and use the $
for the other script.
You need to create another migration file - and place it in there:
Run
Laravel 4: php artisan migrate:make rename_stnk_column
Laravel 5: php artisan make:migration rename_stnk_column
Then inside the new migration file place:
class RenameStnkColumn extends Migration
{
public function up()
{
Schema::table('stnk', function(Blueprint $table) {
$table->renameColumn('id', 'id_stnk');
});
}
public function down()
{
Schema::table('stnk', function(Blueprint $table) {
$table->renameColumn('id_stnk', 'id');
});
}
}
Instead of recommending the usual "turn off the JSHint globals", I recommend using the module pattern to fix this problem. It keeps your code "contained" and gives a performance boost (based on Paul Irish's "10 things I learned about Jquery").
I tend to write my module patterns like this:
(function (window) {
// Handle dependencies
var angular = window.angular,
$ = window.$,
document = window.document;
// Your application's code
}(window))
You can get these other performance benefits (explained more here):
window
object declaration gets minified as well. e.g. window.alert()
become m.alert()
.window
object.window
property or method, preventing expensive traversal of the scope chain e.g. window.alert()
(faster) versus alert()
(slower) performance.Sometimes you have a custom background, in that cases a better solution is use android:foreground="?selectableItemBackground"
If you want ripple effect with rounded corners and custom background you can use this:
background_ripple.xml
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="@color/ripple_color">
<item android:id="@android:id/mask">
<shape android:shape="rectangle">
<solid android:color="@android:color/white" />
<corners android:radius="5dp" />
</shape>
</item>
<item android:id="@android:id/background">
<shape android:shape="rectangle">
<solid android:color="@android:color/white" />
<corners android:radius="5dp" />
</shape>
</item>
layout.xml
<Button
android:id="@+id/btn_play"
android:background="@drawable/background_ripple"
app:backgroundTint="@color/colorPrimary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/play_now" />
I used this on API >= 21
String
and then try
ing Integer.parseInt()
and if you don't catch
an exception then it's a number, if you do, read a new one, maybe by setting num2 to Integer.MIN_VALUE and using the same type of logic in your example.Don't set the style object itself, set the background color property of the style object that is a property of the element.
And yes, even though you said no, jquery and tablesorter with its zebra stripe plugin can do this all for you in 3 lines of code.
And just setting the class attribute would be better since then you have non-hard-coded control over the styling which is more organized
Inspired by Martijn Pieters' response.
In case you only need to delete the header from the csv
file, you can work more efficiently if you write using the standard Python file I/O library, avoiding writing with the CSV Python library:
with open("tmob_notcleaned.csv", "rb") as infile, open("tmob_cleaned.csv", "wb") as outfile:
next(infile) # skip the headers
outfile.write(infile.read())
int max = 50;
int min = 1;
double random = Math.random() * 49 + 1;
or
int random = (int )(Math.random() * 50 + 1);
This will give you value from 1 to 50 in case of int or 1.0 (inclusive) to 50.0 (exclusive) in case of double
Why?
random() method returns a random number between 0.0 and 0.9..., you multiply it by 50, so upper limit becomes 0.0 to 49.999... when you add 1, it becomes 1.0 to 50.999..., now when you truncate to int, you get 1 to 50. (thanks to @rup in comments). leepoint's awesome write-up on both the approaches.
Random rand = new Random();
int value = rand.nextInt(50);
This will give value from 0 to 49.
For 1 to 50: rand.nextInt((max - min) + 1) + min;
Source of some Java Random awesomeness.
In JavaScript this
always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. When we define our faithful function doSomething() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript.
The fundamental misunderstanding here is in thinking that range
is a generator. It's not. In fact, it's not any kind of iterator.
You can tell this pretty easily:
>>> a = range(5)
>>> print(list(a))
[0, 1, 2, 3, 4]
>>> print(list(a))
[0, 1, 2, 3, 4]
If it were a generator, iterating it once would exhaust it:
>>> b = my_crappy_range(5)
>>> print(list(b))
[0, 1, 2, 3, 4]
>>> print(list(b))
[]
What range
actually is, is a sequence, just like a list. You can even test this:
>>> import collections.abc
>>> isinstance(a, collections.abc.Sequence)
True
This means it has to follow all the rules of being a sequence:
>>> a[3] # indexable
3
>>> len(a) # sized
5
>>> 3 in a # membership
True
>>> reversed(a) # reversible
<range_iterator at 0x101cd2360>
>>> a.index(3) # implements 'index'
3
>>> a.count(3) # implements 'count'
1
The difference between a range
and a list
is that a range
is a lazy or dynamic sequence; it doesn't remember all of its values, it just remembers its start
, stop
, and step
, and creates the values on demand on __getitem__
.
(As a side note, if you print(iter(a))
, you'll notice that range
uses the same listiterator
type as list
. How does that work? A listiterator
doesn't use anything special about list
except for the fact that it provides a C implementation of __getitem__
, so it works fine for range
too.)
Now, there's nothing that says that Sequence.__contains__
has to be constant time—in fact, for obvious examples of sequences like list
, it isn't. But there's nothing that says it can't be. And it's easier to implement range.__contains__
to just check it mathematically ((val - start) % step
, but with some extra complexity to deal with negative steps) than to actually generate and test all the values, so why shouldn't it do it the better way?
But there doesn't seem to be anything in the language that guarantees this will happen. As Ashwini Chaudhari points out, if you give it a non-integral value, instead of converting to integer and doing the mathematical test, it will fall back to iterating all the values and comparing them one by one. And just because CPython 3.2+ and PyPy 3.x versions happen to contain this optimization, and it's an obvious good idea and easy to do, there's no reason that IronPython or NewKickAssPython 3.x couldn't leave it out. (And in fact CPython 3.0-3.1 didn't include it.)
If range
actually were a generator, like my_crappy_range
, then it wouldn't make sense to test __contains__
this way, or at least the way it makes sense wouldn't be obvious. If you'd already iterated the first 3 values, is 1
still in
the generator? Should testing for 1
cause it to iterate and consume all the values up to 1
(or up to the first value >= 1
)?
I assume $arr is an array then this is what you are looking for
if ( sizeof($arr) > 1) ...
Defining a constructor with public or internal storage class in an inheritable concrete class Thing
effectively defines two methods:
A method (which I'll call InitializeThing
) which acts upon this
, has no return value, and can only be called from Thing
's CreateThing
and InitializeThing
methods, and subclasses' InitializeXXX
methods.
A method (which I'll call CreateThing
) which returns an object of the constructor's designated type, and essentially behaves as:
Thing CreateThing(int whatever)
{
Thing result = AllocateObject<Thing>();
Thing.initializeThing(whatever);
}
Abstract classes effectively create methods of only the first form. Conceptually, there's no reason why the two "methods" described above should need to have the same access specifiers; in practice, however, there's no way to specify their accessibility differently. Note that in terms of actual implementation, at least in .NET, CreateThing
isn't really implemented as a callable method, but instead represents a code sequence which gets inserted at a newThing = new Thing(23);
statement.
Would this relationship not be better expressed as a one-to-many foreign key relationship to a Friends
table? I understand that myFriends
are just strings but I would think that a better design would be to create a Friend
model and have MyClass
contain a foreign key realtionship to the resulting table.
Same issue I'm getting in my MYSQL while running sql script Please look into below image.. Error code 1206: The number of locks exceeds the lock table size Picture
This is Mysql configuration issue so I made some changes in my.ini
and It's working on my system & issue resolved.
We need to make some changes in my.ini
which is available on following Path:- C:\ProgramData\MySQL\MySQL Server 5.7\my.ini
and please update following changes in my.ini
config file fields:-
key_buffer_size=64M
read_buffer_size=64M
read_rnd_buffer_size=128M
innodb_log_buffer_size=10M
innodb_buffer_pool_size=256M
query_cache_type=2
max_allowed_packet=16M
After all above changes please restart the MYSQL Service. Please refer the image:- Microsoft MYSQL Service Picture
Your error is caused by these:
Dim oTable As Table, oRow As Row,
These types, Table
and Row
are not variable types native to Excel. You can resolve this in one of two ways:
Dim oTable as Word.Table, oRow as Word.Row
. This is called early-binding. Object
type: Dim oTable as Object, oRow as Object
. With this method, you do not need to add the reference to Word, but you also lose the intellisense assistance in the VBE.I have not tested your code but I suspect ActiveDocument
won't work in Excel with method #2, unless you properly scope it to an instance of a Word.Application object. I don't see that anywhere in the code you have provided. An example would be like:
Sub DeleteEmptyRows()
Dim wdApp as Object
Dim oTable As Object, As Object, _
TextInRow As Boolean, i As Long
Set wdApp = GetObject(,"Word.Application")
Application.ScreenUpdating = False
For Each oTable In wdApp.ActiveDocument.Tables
You can try with this code (Same case)
chaine1 + chaine2;
I suggest you also (I prefer this) the string.concat method
In the solution below I used python3.4
as binary, but it's safe to use with any version or binary of python. it works fine on windows too (except the downloading pip with wget
obviously but just save the file locally and run it with python).
This is great if you have multiple versions of python installed, so you can manage external libraries per python version.
So first, I'd recommend get-pip.py
, it's great to install pip :
wget https://bootstrap.pypa.io/get-pip.py
Then you need to install pip for your version of python, I have python3.4
so for me this is the command :
python3.4 get-pip.py
Now pip is installed for python3.4
and in order to get libraries for python3.4
one need to call it within this version, like this :
python3.4 -m pip
So if you want to install numpy you would use :
python3.4 -m pip install numpy
Note that numpy
is quite the heavy library. I thought my system was hanging and failing.
But using the verbose option, you can see that the system is fine :
python3.4 -m pip install numpy -v
This may tell you that you lack python.h but you can easily get it :
On RHEL (Red hat, CentOS, Fedora) it would be something like this :
yum install python34-devel
On debian-like (Debian, Ubuntu, Kali, ...) :
apt-get install python34-dev
Then rerun this :
python3.4 -m pip install numpy -v
There are two main ways that you can do this. One of them is the standard CakePHP way, and the other is using a custom join.
It's worth pointing out that this advice is for CakePHP 2.x, not 3.x.
You would create a relationship with your User model and Messages Model, and use the containable behavior:
class User extends AppModel {
public $actsAs = array('Containable');
public $hasMany = array('Message');
}
class Message extends AppModel {
public $actsAs = array('Containable');
public $belongsTo = array('User');
}
You need to change the messages.from
column to be messages.user_id
so that cake can automagically associate the records for you.
Then you can do this from the messages controller:
$this->Message->find('all', array(
'contain' => array('User')
'conditions' => array(
'Message.to' => 4
),
'order' => 'Message.datetime DESC'
));
I recommend using the first method, because it will save you a lot of time and work. The first method also does the groundwork of setting up a relationship which can be used for any number of other find calls and conditions besides the one you need now. However, cakePHP does support a syntax for defining your own joins. It would be done like this, from the MessagesController
:
$this->Message->find('all', array(
'joins' => array(
array(
'table' => 'users',
'alias' => 'UserJoin',
'type' => 'INNER',
'conditions' => array(
'UserJoin.id = Message.from'
)
)
),
'conditions' => array(
'Message.to' => 4
),
'fields' => array('UserJoin.*', 'Message.*'),
'order' => 'Message.datetime DESC'
));
Note, I've left the field name messages.from
the same as your current table in this example.
Here is how you can do the first example using two relationships to the same model:
class User extends AppModel {
public $actsAs = array('Containable');
public $hasMany = array(
'MessagesSent' => array(
'className' => 'Message',
'foreignKey' => 'from'
)
);
public $belongsTo = array(
'MessagesReceived' => array(
'className' => 'Message',
'foreignKey' => 'to'
)
);
}
class Message extends AppModel {
public $actsAs = array('Containable');
public $belongsTo = array(
'UserFrom' => array(
'className' => 'User',
'foreignKey' => 'from'
)
);
public $hasMany = array(
'UserTo' => array(
'className' => 'User',
'foreignKey' => 'to'
)
);
}
Now you can do your find call like this:
$this->Message->find('all', array(
'contain' => array('UserFrom')
'conditions' => array(
'Message.to' => 4
),
'order' => 'Message.datetime DESC'
));
Based on Thilak's answer I was able to come up with this solution...
Since my form fields only show validation messages if a field is invalid, and has been touched by the user I was able to use this code triggered by a button to show my invalid fields:
// Show/trigger any validation errors for this step_x000D_
angular.forEach(vm.rfiForm.stepTwo.$error, function(error) {_x000D_
angular.forEach(error, function(field) {_x000D_
field.$setTouched();_x000D_
});_x000D_
});_x000D_
// Prevent user from going to next step if current step is invalid_x000D_
if (!vm.rfiForm.stepTwo.$valid) {_x000D_
isValid = false;_x000D_
}
_x000D_
<!-- form field -->_x000D_
<div class="form-group" ng-class="{ 'has-error': rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched && rfi.rfiForm.stepTwo.Parent_Suffix__c.$invalid }">_x000D_
_x000D_
<!-- field label -->_x000D_
<label class="control-label">Suffix</label>_x000D_
<!-- end field label -->_x000D_
<!-- field input -->_x000D_
<select name="Parent_Suffix__c" class="form-control"_x000D_
ng-options="item.value as item.label for item in rfi.contact.Parent_Suffixes"_x000D_
ng-model="rfi.contact.Parent_Suffix__c" />_x000D_
<!-- end field input -->_x000D_
<!-- field help -->_x000D_
<span class="help-block" ng-messages="rfi.rfiForm.stepTwo.Parent_Suffix__c.$error" ng-show="rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched">_x000D_
<span ng-message="required">this field is required</span>_x000D_
</span> _x000D_
<!-- end field help -->_x000D_
</div>_x000D_
<!-- end form field -->
_x000D_
Giving my response just in case if anybody struggling with this issue.
You might need to verify that the server.root configuration in "/etc/ngnx/sites-available/domain" matching with your sites.to config in "Homestead.yaml".
If its not matching then change it and restart the webserver with "sudo service nginx restart"
And still things are not working then allow write permission for the "YOURSITE/app/storage" folder as "chmod -R 777 app/storage"
fill
all items with undefined
before using map
:?? Array.fill
has no IE support
// run 5 times:
Array(5).fill().map((item, i)=>{
console.log(i) // print index
})
_x000D_
There is nice "trick" using destructuring Array, replacing fill
with:
Array(5).fill()
? [...Array(5)]
which does the same, filling the array with undefined
.
If you want to make the above more "declarative", my currently opinion-based solution would be:
const iterate = times => callback => [...Array(times)].map((n,i) => callback(i))
iterate(3)(console.log)
_x000D_
// run 5 times:
for( let i=5; i--; )
console.log(i)
_x000D_
Or as a declarative "while":
const times = count => callback => { while(count--) callback(count) }
times(3)(console.log)
_x000D_
For checking a variable content and have a default text, you can use:
<span>{{myVar || 'Text'}}</span>
Try to use org.apache.commons.io.FileUtils (General file manipulation utilities). Facilities are provided in the following methods:
(1) FileUtils.moveDirectory(File srcDir, File destDir) => Moves a directory.
(2) FileUtils.moveDirectoryToDirectory(File src, File destDir, boolean createDestDir) => Moves a directory to another directory.
(3) FileUtils.moveFile(File srcFile, File destFile) => Moves a file.
(4) FileUtils.moveFileToDirectory(File srcFile, File destDir, boolean createDestDir) => Moves a file to a directory.
(5) FileUtils.moveToDirectory(File src, File destDir, boolean createDestDir) => Moves a file or directory to the destination directory.
It's simple, easy and fast.
If I understand you correctly, you need to use -SearchBase:
Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *
Note that Get-ADUser defaults to using
-SearchScope Subtree
so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).
In the Repository Browser of TortoiseSVN, find the branch that you want to create the new branch from. Right-click, Copy To.... and enter the new branch path. Now you can "switch" your local WC to that branch.
If you'd like your script to install missing packages and continue, you could do something like this (on example of 'krbV' module in 'python-krbV' package):
import pip
import sys
for m, pkg in [('krbV', 'python-krbV')]:
try:
setattr(sys.modules[__name__], m, __import__(m))
except ImportError:
pip.main(['install', pkg])
setattr(sys.modules[__name__], m, __import__(m))
<?php
$dbName = $_SERVER["DOCUMENT_ROOT"] . "products\products.mdb";
if (!file_exists($dbName)) {
die("Could not find database file.");
}
$db = new PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=$dbName; Uid=; Pwd=;");
A successful connection will allow SQL commands to be executed from PHP to read or write the database. If, however, you get the error message “PDOException Could not find driver” then it’s likely that the PDO ODBC driver is not installed. Use the phpinfo() function to check your installation for references to PDO.
If an entry for PDO ODBC is not present, you will need to ensure your installation includes the PDO extension and ODBC drivers. To do so on Windows, uncomment the line extension=php_pdo_odbc.dll in php.ini, restart Apache, and then try to connect to the database again.
With the driver installed, the output from phpinfo() should include information like this:https://www.diigo.com/item/image/5kc39/hdse
Data Source=HARIHARAN-PC\SQLEXPRESS; Initial Catalog=Your_DataBase_name; Integrated Security=true/false; User ID=your_Username;Password=your_Password;
set DSKTOPDIR="D:\test"
set IPADDRESS="23.23.3.23"
>%DSKTOPDIR%\script.ftp ECHO cd %PAY_REP%
>>%DSKTOPDIR%\script.ftp ECHO mget *.report
>>%DSKTOPDIR%\script.ftp ECHO bye
:: run PSFTP Commands
psftp <domain>@%IPADDRESS% -b %DSKTOPDIR%\script.ftp
Set values using set commands before above lines.
I believe this helps you.
Referre psfpt setup for below link https://www.ssh.com/ssh/putty/putty-manuals/0.68/Chapter6.html
Try
request.getSession().setAttribute("SUBFAMILY", subFam);
request.getSession().getAttribute("SUBFAMILY");
You can also do this without using groupby or loc. By simply including the condition in code. Let the name of dataframe be df. Then you can try :
df[df['a']==1]['b'].sum()
or you can also try :
sum(df[df['a']==1]['b'])
Another way could be to use the numpy library of python :
import numpy as np
print(np.where(df['a']==1, df['b'],0).sum())
You can try to split your String into two parts and manage their case separately.
{{ (Name.charAt(0) | uppercase) + "" + (Name.slice(1, element.length) | lowercase) }}
or
{{ Name.charAt(0) | uppercase }} {{ Name.slice(1, element.length) | lowercase }}
I guess you are looking for brace expansion:
cp /home/ankur/folder/{file1,file2} /home/ankur/dest
take a look here, it would be helpful for you if you want to handle multiple files once :
http://www.tldp.org/LDP/abs/html/globbingref.html
For Debian users, I have this problem after modifying my locale to change machine's language. This is what I did:
Modify .bashrc:
export LANG=fr_FR.UTF-8
export LC_ALL=fr_FR.UTF-8
Uncomment line fr_FR.UTF-8
in file etc/locale.gen
-> sudo locale-gen
to generate the missing package
sudo update-locale
sudo dpkg-reconfigure locales
to configure my locale to fr_FR.UTF-8
Add extra lines to the etc/default/locale
file:
LANGUAGE=en_US.UTF-8
LC_ALL=en_US.UTF-8
LANG=en_US.UTF-8
LC_TYPE=en_US.UTF-8
Reboot my computer and everything works fine
For a solution that is free of fiddly external dependencies*, there is now readxl
:
The readxl package makes it easy to get data out of Excel and into R. Compared to many of the existing packages (e.g. gdata, xlsx, xlsReadWrite) readxl has no external dependencies so it's easy to install and use on all operating systems. It is designed to work with tabular data stored in a single sheet.
Readxl supports both the legacy .xls format and the modern xml-based .xlsx format. .xls support is made possible the with libxls C library, which abstracts away many of the complexities of the underlying binary format. To parse .xlsx, we use the RapidXML C++ library.
It can be installed like so:
install.packages("readxl") # CRAN version
or
devtools::install_github("hadley/readxl") # development version
Usage
library(readxl)
# read_excel reads both xls and xlsx files
read_excel("my-old-spreadsheet.xls")
read_excel("my-new-spreadsheet.xlsx")
# Specify sheet with a number or name
read_excel("my-spreadsheet.xls", sheet = "data")
read_excel("my-spreadsheet.xls", sheet = 2)
# If NAs are represented by something other than blank cells,
# set the na argument
read_excel("my-spreadsheet.xls", na = "NA")
* not strictly true, it requires the Rcpp
package, which in turn requires Rtools (for Windows) or Xcode (for OSX), which are dependencies external to R. But they don't require any fiddling with paths, etc., so that's an advantage over Java and Perl dependencies.
Update There is now the rexcel package. This promises to get Excel formatting, functions and many other kinds of information from the Excel file and into R.
No need to do anything on the commandline.
Just use spotlight to run simulator.app
Use this query:
DELETE FROM tableName;
Note: To delete some specific record you can give the condition in where clause in the query also.
OR you can use this query also:
truncate tableName;
Also remember that you should not have any relationship with other table. If there will be any foreign key constraint in the table then those record will not be deleted and will give the error.
Since setOnClickListener
is defined on View
not Button
, if you don't need the variable for something else, you could make it a little terser like this:
findViewById(R.id.buttonXName).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//DO SOMETHING! {RUN SOME FUNCTION ... DO CHECKS... ETC}
}
});
The "best" answer has already been submitted, but I thought I would add that you can use nested list comprehensions, as seen in the Python Tutorial.
Here is how you could get a transposed array:
def matrixTranspose( matrix ):
if not matrix: return []
return [ [ row[ i ] for row in matrix ] for i in range( len( matrix[ 0 ] ) ) ]
Building upon the type-hints answer (https://stackoverflow.com/a/9195565/2418922), which provides a better structured way to document types of parameters, there exist also a structured manner to document both type and descriptions of parameters:
def copy_net(
infile: (str, 'The name of the file to send'),
host: (str, 'The host to send the file to'),
port: (int, 'The port to connect to')):
pass
example adopted from: https://pypi.org/project/autocommand/
There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.
This can not have a variable:
create function Func() returns table
as
return
select 10 as ColName
You have to do like this instead:
create function Func()
returns @T table(ColName int)
as
begin
declare @Var int
set @Var = 10
insert into @T(ColName) values (@Var)
return
end
The XML editable
property is deprecated since API LEVEL 15.
You should use now the inputType
property with the value none
.
But there is a bug that makes this functionality useless.
Here you can follow the issue status.
I ended up trying something easy by resetting the Debug perspective, which seemed to work:
Window => Perspective => Reset Perspective...
Thanks for the comments.
Nothing new but I rewrote Brian Pressler solution to be easier on the eye, it might be useful to someone (even if it's just future me):
alter function [dbo].[fn_GenerateNumbers]
(
@start int,
@end int
) returns table
return
with
b0 as (select n from (values (0),(0x00000001),(0x00000002),(0x00000003),(0x00000004),(0x00000005),(0x00000006),(0x00000007),(0x00000008),(0x00000009),(0x0000000A),(0x0000000B),(0x0000000C),(0x0000000D),(0x0000000E),(0x0000000F)) as b0(n)),
b1 as (select n from (values (0),(0x00000010),(0x00000020),(0x00000030),(0x00000040),(0x00000050),(0x00000060),(0x00000070),(0x00000080),(0x00000090),(0x000000A0),(0x000000B0),(0x000000C0),(0x000000D0),(0x000000E0),(0x000000F0)) as b1(n)),
b2 as (select n from (values (0),(0x00000100),(0x00000200),(0x00000300),(0x00000400),(0x00000500),(0x00000600),(0x00000700),(0x00000800),(0x00000900),(0x00000A00),(0x00000B00),(0x00000C00),(0x00000D00),(0x00000E00),(0x00000F00)) as b2(n)),
b3 as (select n from (values (0),(0x00001000),(0x00002000),(0x00003000),(0x00004000),(0x00005000),(0x00006000),(0x00007000),(0x00008000),(0x00009000),(0x0000A000),(0x0000B000),(0x0000C000),(0x0000D000),(0x0000E000),(0x0000F000)) as b3(n)),
b4 as (select n from (values (0),(0x00010000),(0x00020000),(0x00030000),(0x00040000),(0x00050000),(0x00060000),(0x00070000),(0x00080000),(0x00090000),(0x000A0000),(0x000B0000),(0x000C0000),(0x000D0000),(0x000E0000),(0x000F0000)) as b4(n)),
b5 as (select n from (values (0),(0x00100000),(0x00200000),(0x00300000),(0x00400000),(0x00500000),(0x00600000),(0x00700000),(0x00800000),(0x00900000),(0x00A00000),(0x00B00000),(0x00C00000),(0x00D00000),(0x00E00000),(0x00F00000)) as b5(n)),
b6 as (select n from (values (0),(0x01000000),(0x02000000),(0x03000000),(0x04000000),(0x05000000),(0x06000000),(0x07000000),(0x08000000),(0x09000000),(0x0A000000),(0x0B000000),(0x0C000000),(0x0D000000),(0x0E000000),(0x0F000000)) as b6(n)),
b7 as (select n from (values (0),(0x10000000),(0x20000000),(0x30000000),(0x40000000),(0x50000000),(0x60000000),(0x70000000)) as b7(n))
select s.n
from (
select
b7.n
| b6.n
| b5.n
| b4.n
| b3.n
| b2.n
| b1.n
| b0.n
+ @start
n
from b0
join b1 on b0.n <= @end-@start and b1.n <= @end-@start
join b2 on b2.n <= @end-@start
join b3 on b3.n <= @end-@start
join b4 on b4.n <= @end-@start
join b5 on b5.n <= @end-@start
join b6 on b6.n <= @end-@start
join b7 on b7.n <= @end-@start
) s
where @end >= s.n
GO
$result= mysql_query("SELECT * FROM MY_TABLE");
while($row = mysql_fetch_array($result)){
echo $row['whatEverColumnName'];
}
This should not affect everyone, but one of the semi-hidden reasons of the repository size being large could be Git submodules.
You might have added one or more submodules, but stopped using it at some time, and some files remained in .git/modules
directory. To make redundant submodule files gone away, see this question.
However, just like the main repository, the other way is to navigate to the submodule directory in .git/modules
, and do a, for example, git gc --aggressive --prune
.
These should have a good impact in the repository size, but as long as you use Git submodules, e.g. especially with large libraries, your repository size should not change drastically.
I refactored the chosen answer here and improved on it. The chosen answer only works assuming you have one form per page. I solved this for multiple forms on same page (in my case I have 2 modals on same page) and my solution only checks for values on required fields. My solution gracefully degrades if JavaScript is disabled and includes a slick CSS button fade transition.
See working JS fiddle example: https://jsfiddle.net/bno08c44/4/
JS
$(function(){
function submitState(el) {
var $form = $(el),
$requiredInputs = $form.find('input:required'),
$submit = $form.find('input[type="submit"]');
$submit.attr('disabled', 'disabled');
$requiredInputs.keyup(function () {
$form.data('empty', 'false');
$requiredInputs.each(function() {
if ($(this).val() === '') {
$form.data('empty', 'true');
}
});
if ($form.data('empty') === 'true') {
$submit.attr('disabled', 'disabled').attr('title', 'fill in all required fields');
} else {
$submit.removeAttr('disabled').attr('title', 'click to submit');
}
});
}
// apply to each form element individually
submitState('#sign_up_user');
submitState('#login_user');
});
CSS
input[type="submit"] {
background: #5cb85c;
color: #fff;
transition: background 600ms;
cursor: pointer;
}
input[type="submit"]:disabled {
background: #555;
cursor: not-allowed;
}
HTML
<h4>Sign Up</h4>
<form id="sign_up_user" data-empty="" action="#" method="post">
<input type="email" name="email" placeholder="Email" required>
<input type="password" name="password" placeholder="Password" required>
<input type="password" name="password_confirmation" placeholder="Password Confirmation" required>
<input type="hidden" name="secret" value="secret">
<input type="submit" value="signup">
</form>
<h4>Login</h4>
<form id="login_user" data-empty="" action="#" method="post">
<input type="email" name="email" placeholder="Email" required>
<input type="password" name="password" placeholder="Password" required>
<input type="checkbox" name="remember" value="1"> remember me
<input type="submit" value="signup">
</form>
At first you need to add semi colon (;) after quantity INT NOT NULL)
then remove ** from ,genre,quantity)**
.
to insert a value with numeric data type like int, decimal, float, etc you don't need to add single quote.
I found this way of using ajax which helped me as it was better in use as not having complex json syntaxes
//fifth
function GetAjaxDataPromise(url, postData) {
debugger;
var promise = $.post(url, postData, function (promise, status) {
});
return promise;
};
$(function () {
$("#btnGet5").click(function () {
debugger;
var promises = GetAjaxDataPromise('@Url.Action("AjaxMethod", "Home")', { EmpId: $("#txtId").val(), EmpName: $("#txtName").val(), EmpSalary: $("#txtSalary").val() });
promises.done(function (response) {
debugger;
alert("Hello: " + response.EmpName + " Your Employee Id Is: " + response.EmpId + "And Your Salary Is: " + response.EmpSalary);
});
});
});
This method comes with jquery promise the best part was on controller we can received data by using separate parameters or just by using a model class.
[HttpPost]
public JsonResult AjaxMethod(PersonModel personModel)
{
PersonModel person = new PersonModel
{
EmpId = personModel.EmpId,
EmpName = personModel.EmpName,
EmpSalary = personModel.EmpSalary
};
return Json(person);
}
or
[HttpPost]
public JsonResult AjaxMethod(string empId, string empName, string empSalary)
{
PersonModel person = new PersonModel
{
EmpId = empId,
EmpName = empName,
EmpSalary = empSalary
};
return Json(person);
}
It works for both of the cases. SO you must try out this way. Got the reference from Using Ajax With Asp.Net MVC
There are few more ways of using Ajax explained there other than this one which you must try.
sudo apt-get remove nodejs
sudo apt-get remove npm
Then go to /etc/apt/sources.list.d
and remove any node list if you have. Then do a
sudo apt-get update
Check for any .npm
or .node
folder in your home folder and delete those.
If you type
which node
you can see the location of the node. Try which nodejs
and which npm
too.
I would recommend installing node using Node Version Manager(NVM). That saved a lot of headache for me. You can install nodejs and npm without sudo
using nvm.
Just go to vmvare edit->preferences->shared vms. Click on change settings and disable sharing.click on OK.xampp will work fine.
All, this is pretty simple. I have been trying for the same and this is what worked for me in VBA
Range("A1:R50").Select 'The range you want to remove blanks
With Selection
Selection.NumberFormat = "General"
.Value = .Value
End With
Regards, Anand Lanka
I think that Spring Data ignores the FetchMode. I always use the @NamedEntityGraph
and @EntityGraph
annotations when working with Spring Data
@Entity
@NamedEntityGraph(name = "GroupInfo.detail",
attributeNodes = @NamedAttributeNode("members"))
public class GroupInfo {
// default fetch mode is lazy.
@ManyToMany
List<GroupMember> members = new ArrayList<GroupMember>();
…
}
@Repository
public interface GroupRepository extends CrudRepository<GroupInfo, String> {
@EntityGraph(value = "GroupInfo.detail", type = EntityGraphType.LOAD)
GroupInfo getByGroupName(String name);
}
Check the documentation here
You can do it like this:
public void LogEmployees<T>(List<T> list) // Or IEnumerable<T> list
{
foreach (T item in list)
{
}
}
... but you won't get to do much with each item. You could call ToString, but you won't be able to use (say) Name
and Id
directly.
<font size="4"> <font color="#ffe680">something here</font><br>
I was trying all these methods but most didn't work properly for me, eventually I accidentally did this and it works great, it works on chrome and safari (the only things I tested on). Replace the colour code thing with your background colour code and the text will be invisible. you can also adjust the font size to make the line break bigger or smaller depending on your desire. It is really simple.
From Implementing toString:
public String toString() {
StringBuilder result = new StringBuilder();
String newLine = System.getProperty("line.separator");
result.append( this.getClass().getName() );
result.append( " Object {" );
result.append(newLine);
//determine fields declared in this class only (no fields of superclass)
Field[] fields = this.getClass().getDeclaredFields();
//print field names paired with their values
for ( Field field : fields ) {
result.append(" ");
try {
result.append( field.getName() );
result.append(": ");
//requires access to private field:
result.append( field.get(this) );
} catch ( IllegalAccessException ex ) {
System.out.println(ex);
}
result.append(newLine);
}
result.append("}");
return result.toString();
}
Is there a reason why you can't use the Excel ODBC connection to read and write to Excel? For example, I've used the following code to read from an Excel file row by row like a database:
private DataTable LoadExcelData(string fileName)
{
string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
OleDbConnection con = new OleDbConnection(Connection);
OleDbCommand command = new OleDbCommand();
DataTable dt = new DataTable(); OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$] WHERE LastName <> '' ORDER BY LastName, FirstName", con);
myCommand.Fill(dt);
Console.WriteLine(dt.Rows.Count);
return dt;
}
You can write to the Excel "database" the same way. As you can see, you can select the version number to use so that you can downgrade Excel versions for the machine with Excel 2003. Actually, the same is true for using the Interop. You can use the lower version and it should work with Excel 2003 even though you only have the higher version on your development PC.
You'll have to use the MySQLi extension if you don't want to execute a query twice:
if (mysqli_multi_query($link, $query))
{
$result1 = mysqli_store_result($link);
$result2 = null;
if (mysqli_more_results($link))
{
mysqli_next_result($link);
$result2 = mysqli_store_result($link);
}
// do something with both result sets.
if ($result1)
mysqli_free_result($result1);
if ($result2)
mysqli_free_result($result2);
}
Your NFS server disappeared.
Ideally your best bet is if the NFS server comes back.
If not, the "umount -f" should have done the trick. It doesn't ALWAYS work, but it often will.
If you happen to know what processes are USING the NFS filesystem, you could try killing those processes and then maybe an unmount would work.
Finally, I'd guess you need to reboot.
Also, DON'T soft-mount your NFS drives. You use hard-mounts to guarantee that they worked. That's necessary if you're doing writes.
Would something like this work for you?
SELECT * FROM FB WHERE Dte >= DATE(NOW() - INTERVAL 2 MONTH);
To add primary key in the column.
ALTER TABLE table_name ADD PRIMARY KEY (column_name);
To remove primary key from the table.
ALTER TABLE table_name DROP PRIMARY KEY;
I worked on the code given earlier by Eitan-T and reworked to output to CSV file. Found the results in earlier code weren't always giving correct values as well so i've improved it.
testservers.txt
SOMESERVER
DUDSERVER
results.csv
HOSTNAME LONGNAME IPADDRESS STATE
SOMESERVER SOMESERVER.DOMAIN.SUF 10.1.1.1 UP
DUDSERVER UNRESOLVED UNRESOLVED DOWN
pingtest.bat
@echo off
setlocal enabledelayedexpansion
set OUTPUT_FILE=result.csv
>nul copy nul %OUTPUT_FILE%
echo HOSTNAME,LONGNAME,IPADDRESS,STATE >%OUTPUT_FILE%
for /f %%i in (testservers.txt) do (
set SERVER_ADDRESS_I=UNRESOLVED
set SERVER_ADDRESS_L=UNRESOLVED
for /f "tokens=1,2,3" %%x in ('ping -n 1 %%i ^&^& echo SERVER_IS_UP') do (
if %%x==Pinging set SERVER_ADDRESS_L=%%y
if %%x==Pinging set SERVER_ADDRESS_I=%%z
if %%x==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
)
echo %%i [!SERVER_ADDRESS_L::=!] !SERVER_ADDRESS_I::=! is !SERVER_STATE!
echo %%i,!SERVER_ADDRESS_L::=!,!SERVER_ADDRESS_I::=!,!SERVER_STATE! >>%OUTPUT_FILE%
)
First open Your cmd pannel And enter mysql -u root -p (And Hit Enter) After cmd ask's for mysql password (if you have mysql password so enter now and hit enter again) now type source mysqldata.sql(Hit Enter) Your database will import without any error
I know it's old question but if you really need use $scope.$applyAsync();
What is the difference between the list methods append and extend?
append
adds its argument as a single element to the end of a list. The length of the list itself will increase by one.extend
iterates over its argument adding each element to the list, extending the list. The length of the list will increase by however many elements were in the iterable argument.append
The list.append
method appends an object to the end of the list.
my_list.append(object)
Whatever the object is, whether a number, a string, another list, or something else, it gets added onto the end of my_list
as a single entry on the list.
>>> my_list
['foo', 'bar']
>>> my_list.append('baz')
>>> my_list
['foo', 'bar', 'baz']
So keep in mind that a list is an object. If you append another list onto a list, the first list will be a single object at the end of the list (which may not be what you want):
>>> another_list = [1, 2, 3]
>>> my_list.append(another_list)
>>> my_list
['foo', 'bar', 'baz', [1, 2, 3]]
#^^^^^^^^^--- single item at the end of the list.
extend
The list.extend
method extends a list by appending elements from an iterable:
my_list.extend(iterable)
So with extend, each element of the iterable gets appended onto the list. For example:
>>> my_list
['foo', 'bar']
>>> another_list = [1, 2, 3]
>>> my_list.extend(another_list)
>>> my_list
['foo', 'bar', 1, 2, 3]
Keep in mind that a string is an iterable, so if you extend a list with a string, you'll append each character as you iterate over the string (which may not be what you want):
>>> my_list.extend('baz')
>>> my_list
['foo', 'bar', 1, 2, 3, 'b', 'a', 'z']
__add__
(+
) and __iadd__
(+=
)Both +
and +=
operators are defined for list
. They are semantically similar to extend.
my_list + another_list
creates a third list in memory, so you can return the result of it, but it requires that the second iterable be a list.
my_list += another_list
modifies the list in-place (it is the in-place operator, and lists are mutable objects, as we've seen) so it does not create a new list. It also works like extend, in that the second iterable can be any kind of iterable.
Don't get confused - my_list = my_list + another_list
is not equivalent to +=
- it gives you a brand new list assigned to my_list.
Append has constant time complexity, O(1).
Extend has time complexity, O(k).
Iterating through the multiple calls to append
adds to the complexity, making it equivalent to that of extend, and since extend's iteration is implemented in C, it will always be faster if you intend to append successive items from an iterable onto a list.
You may wonder what is more performant, since append can be used to achieve the same outcome as extend. The following functions do the same thing:
def append(alist, iterable):
for item in iterable:
alist.append(item)
def extend(alist, iterable):
alist.extend(iterable)
So let's time them:
import timeit
>>> min(timeit.repeat(lambda: append([], "abcdefghijklmnopqrstuvwxyz")))
2.867846965789795
>>> min(timeit.repeat(lambda: extend([], "abcdefghijklmnopqrstuvwxyz")))
0.8060121536254883
A commenter said:
Perfect answer, I just miss the timing of comparing adding only one element
Do the semantically correct thing. If you want to append all elements in an iterable, use extend
. If you're just adding one element, use append
.
Ok, so let's create an experiment to see how this works out in time:
def append_one(a_list, element):
a_list.append(element)
def extend_one(a_list, element):
"""creating a new list is semantically the most direct
way to create an iterable to give to extend"""
a_list.extend([element])
import timeit
And we see that going out of our way to create an iterable just to use extend is a (minor) waste of time:
>>> min(timeit.repeat(lambda: append_one([], 0)))
0.2082819009956438
>>> min(timeit.repeat(lambda: extend_one([], 0)))
0.2397019260097295
We learn from this that there's nothing gained from using extend
when we have only one element to append.
Also, these timings are not that important. I am just showing them to make the point that, in Python, doing the semantically correct thing is doing things the Right Way™.
It's conceivable that you might test timings on two comparable operations and get an ambiguous or inverse result. Just focus on doing the semantically correct thing.
We see that extend
is semantically clearer, and that it can run much faster than append
, when you intend to append each element in an iterable to a list.
If you only have a single element (not in an iterable) to add to the list, use append
.
I prefer this way of handling this. You can check if the file exists synchronously:
var file = 'info.json';
var content = '';
// Check that the file exists locally
if(!fs.existsSync(file)) {
console.log("File not found");
}
// The file *does* exist
else {
// Read the file and do anything you want
content = fs.readFileSync(file, 'utf-8');
}
Note: if your program also deletes files, this has a race condition as noted in the comments. If however you only write or overwrite files, without deleting them, then this is totally fine.
One quick solution that came to mind :-
<input type="checkbox" id="markitem" name="markitem" value="1" onchange="GetMarkedItems(1)">
<label for="markitem" style="position:absolute; top:1px; left:165px;"> </label>
<!-- Fire the below javascript everytime the page reloads -->
<script type=text/javascript>
document.getElementById("markitem").checked = false;
</script>
<!-- Tested on Latest FF, Chrome, Opera and IE. -->
It is naming convention used when passing callbacks in situations that require serial execution of actions, e.g. scan directory -> read file data -> do something with data. This is in preference to deeply nesting the callbacks. The first three sections of the following article on Tim Caswell's HowToNode blog give a good overview of this:
http://howtonode.org/control-flow
Also see the Sequential Actions section of the second part of that posting:
This worked for me:
<div class="text-right">
<button type="button">Button 1</button>
<button type="button">Button 2</button>
</div>
In my case the database statistics had become corrupt. The statement
delete from tablename where col1 = 'v1'
was taking 30 seconds even though there were no matching records but
delete from tablename where col1 = 'rubbish'
ran instantly
running
update statistics tablename
fixed the issue
If I had to guess, you did this:
import datetime
at the top of your code. This means that you have to do this:
datetime.datetime.strptime(date, "%Y-%m-%d")
to access the strptime
method. Or, you could change the import statement to this:
from datetime import datetime
and access it as you are.
The people who made the datetime
module also named their class datetime
:
#module class method
datetime.datetime.strptime(date, "%Y-%m-%d")
It is very simple to make a variable global in a class:
a = 0
class b():
global a
a = 10
>>> a
10
You can use a combination of other LINQ methods to handle not matching condition:
var res = dictionary.Where(x => x.Value.ID == someID)
.Select(x => x.Value.DisplayName)
.DefaultIfEmpty("Unknown")
.First();
You're right: String is a subset of Object. Since String is more "precise" than Object, you should cast it to use it as an argument for System.out.println().
I liked the look of WenhaoWuI's idea above, but I needed to identify the div with class .ui-tree
in the PrimeNG tree component to set the height dynamically.
All the answers I could find required the div to be named (ie #treediv) to enable the use of @ViewChild()
, @ViewChildren()
, @ContentChild()
, @ContentChilden()
etc. This was messy with a third party component.
I finally found a snippet from Günter Zöchbauer :
ngAfterViewInit() {
this.elRef.nativeElement.querySelector('.myClass');
}
This made it easy:
@Input() height: number;
treeheight: number = 400; //default value
constructor(private renderer: Renderer2, private elRef: ElementRef) { }
ngOnInit() {
this.loading = true;
if (this.height != null) {
this.treeheight = this.height;
}
}
ngAfterViewInit() {
this.renderer.setStyle(this.elRef.nativeElement.querySelector('.ui-tree'), 'height', this.treeheight + "px");
}
<?php
$output = file_get_contents('http://host/path/another.php?param=value ');
echo $output;
?>
Not sure if this is what you're after, but it will loop through the range that you gave it and if it finds an "A" it will remove it from the cell. I'm not sure what oldStr is used for...
Private Sub foo()
Dim myString As String
RowCount = WorksheetFunction.CountA(Range("A:A"))
For i = 2 To RowCount
myString = Trim(Cells(i, 1).Value)
If InStr(myString, "A") > 0 Then
Cells(i, 1).Value = Left(myString, InStr(myString, "A"))
End If
Next
End Sub
If you don't have the ability to edit the java code to insert the .setLogLevel()
statements and you don't want yet more external files to deploy, you can use a brute force way to solve this. Just filter out the INFO lines using grep.
spark-submit --deploy-mode client --master local <rest-of-cmd> | grep -v -F "INFO"
To answer the final question (the others seem thoroughly answered above), "Should I bubble up the exact exception or mask it using Exception?"
I am assuming you mean something like this:
public void myMethod() throws Exception {
// ... something that throws FileNotFoundException ...
}
No, always declare the most precise exception possible, or a list of such. The exceptions you declare your method as capable of throwing are a part of the contract between your method and the caller. Throwing "FileNotFoundException"
means that it is possible the file name isn't valid and the file will not be found; the caller will need to handle that intelligently. Throwing Exception
means "Hey, sh*t happens. Deal." Which is a very poor API
.
In the comments on the first article there are some examples where "throws Exception
" is a valid and reasonable declaration, but that's not the case for most "normal
" code you will ever write.
Enhanced diff command with color, side by side and alias
Let's say the file contents are like:
cat /tmp/test1.txt
1
2
3
4
5
8
9
and
cat /tmp/test2.txt
1
1.5
2
4
5
6
7
Now comparing side-by-side
diff --width=$COLUMNS --suppress-common-lines --side-by-side --color=always /tmp/test1.txt /tmp/test2.txt
> 1.5
3 <
8 | 6
9 | 7
You can define alias to use
alias diff='diff --width=$COLUMNS --suppress-common-lines --side-by-side --color=always'
Then new diff result:
diff /tmp/test1.txt /tmp/test2.txt
> 1.5
3 <
8 | 6
9 | 7
I encountered the same issue. This worked:
>>> import pkg_resources
>>> pkg_resources.require("google-api-python-client")
[google-api-python-client 1.5.3 (c:\python27), uritemplate 0.6 (c:\python27\lib\site-packages\uritemplate-0.6-py2.7.egg), six 1.10.0 (c:\python27\lib\site-packages\six-1.10.0-py2.7.egg), oauth2client 3.0.0 (c:\python27\lib\site-packages\oauth2client-3.0.0-py2.7.egg), httplib2 0.9.2 (c:\python27\lib\site-packages\httplib2-0.9.2-py2.7.egg), simplejson 3.8.2 (c:\python27\lib\site-packages\simplejson-3.8.2-py2.7-win32.egg), six 1.10.0 (c:\python27\lib\site-packages\six-1.10.0-py2.7.egg), rsa 3.4.2 (c:\python27\lib\site-packages\rsa-3.4.2-py2.7.egg), pyasn1-modules 0.0.8 (c:\python27\lib\site-packages\pyasn1_modules-0.0.8-py2.7.egg), pyasn1 0.1.9 (c:\python27\lib\site-packages\pyasn1-0.1.9-py2.7.egg)]
>>> from apiclient.discovery import build
>>>
If you are using ng-show to limit the values, the {{$last ? '' : ', '}}
won`t work since it will still take into consideration all the values.Example
<div ng-repeat="x in records" ng-show="x.email == 1">{{x}}{{$last ? '' : ', '}}</div>
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function($scope) {
$scope.records = [
{"email": "1"},
{"email": "1"},
{"email": "2"},
{"email": "3"}
]
});
Results in adding a comma after the "last" value,since with ng-show it still takes into consideration all 4 values
{"email":"1"},
{"email":"1"},
One solution is to add a filter directly into ng-repeat
<div ng-repeat="x in records | filter: { email : '1' } ">{{x}}{{$last ? '' : ', '}}</div>
Results
{"email":"1"},
{"email":"1"}
ORA-01031: insufficient privileges Solution: Go to Your System User. then Write This Code:
SQL> grant dba to UserName; //Put This username which user show this error message.
Grant succeeded.
Pylint message control is documented in the Pylint manual:
Is it possible to locally disable a particular message?
Yes, this feature has been added in Pylint 0.11. This may be done by adding
# pylint: disable=some-message,another-one
at the desired block level or at the end of the desired line of code.
You can use the message code or the symbolic names.
For example,
def test():
# Disable all the no-member violations in this function
# pylint: disable=no-member
...
global VAR # pylint: disable=global-statement
The manual also has further examples.
There is a wiki that documents all Pylint messages and their codes.
You would use indexOf
like this:
if(window.location.href.indexOf("franky") != -1){....}
Also notice the addition of href
for the string otherwise you would do:
if(window.location.toString().indexOf("franky") != -1){....}
To see the current locale information use locale
command. Below is an example on RHEL 7.8
[usr@host ~]$ locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=
If you want to prevent resize by dragging sizegrips and by the maximize button and by maximize by doubleclick on the header text, than insert the following code in the load event of the form:
Me.FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle ' Prevent size grips
Me.MaximumSize = Me.Size ' Prevent maximize (also by doubleclick of header text)
Of course all choices of a formborderstyle beginning with Fixed will do.
urllib2.urlopen
handles ftp links.
In bootstrap 4 I just use $(el).tooltip('dispose');
then recreate as normal. So you can put the dispose before a function that creates a tooltip to be sure it doesn't double up.
Having to check the state and tinker with values seems less friendly.
This has been fully answered here.
See Oracle's docs on SELECT to see how subquery factoring works, and Mark's example:
WITH employee AS (SELECT * FROM Employees)
SELECT * FROM employee WHERE ID < 20
UNION ALL
SELECT * FROM employee WHERE Sex = 'M'
If your web application is configured to impersonate a client, then using a trusted connection will potentially have a negative performance impact. This is because each client must use a different connection pool (with the client's credentials).
Most web applications don't use impersonation / delegation, and hence don't have this problem.
See this MSDN article for more information.
You can replicate those brackets in the left join:
LEFT JOIN bookings
ON rooms.id = bookings.room_type_id
AND ( bookings.arrival between ? and ?
OR bookings.departure between ? and ? )
is
->leftJoin('bookings', function($join){
$join->on('rooms.id', '=', 'bookings.room_type_id');
$join->on(DB::raw('( bookings.arrival between ? and ? OR bookings.departure between ? and ? )'), DB::raw(''), DB::raw(''));
})
You'll then have to set the bindings later using "setBindings" as described in this SO post: How to bind parameters to a raw DB query in Laravel that's used on a model?
It's not pretty but it works.
RDP will not do that natively.
As other answers have said -- you'll need to do some scripting and make policy changes as a kludge to make it hard for RDP logins to run anything but the intended application.
However, as of 2008, Microsoft has released application virtualization technology via Terminal Services that will allow you to do this seamlessly.
For AndroidX implement following lib in gridle
implementation 'androidx.palette:palette:1.0.0'
and import following class in activity -
import androidx.palette.graphics.Palette;
for more info see class and mapping for AndroidX https://developer.android.com/jetpack/androidx/migrate/artifact-mappings https://developer.android.com/jetpack/androidx/migrate/class-mappings
Below, I have written an answer for n
equals to 5, but you can apply same approach to draw DFAs for any value of n
and 'any positional number system' e.g binary, ternary...
First lean the term 'Complete DFA', A DFA defined on complete domain in d:Q × S?Q is called 'Complete DFA'. In other words we can say; in transition diagram of complete DFA there is no missing edge (e.g. from each state in Q there is one outgoing edge present for every language symbol in S). Note: Sometime we define partial DFA as d ? Q × S?Q (Read: How does “d:Q × S?Q” read in the definition of a DFA).
Step-1: When you divide a number ? by n
then reminder can be either 0, 1, ..., (n - 2) or (n - 1). If remainder is 0
that means ? is divisible by n
otherwise not. So, in my DFA there will be a state qr that would be corresponding to a remainder value r
, where 0 <= r <= (n - 1)
, and total number of states in DFA is n
.
After processing a number string ? over S, the end state is qr implies that ? % n => r (% reminder operator).
In any automata, the purpose of a state is like memory element. A state in an atomata stores some information like fan's switch that can tell whether the fan is in 'off' or in 'on' state. For n = 5, five states in DFA corresponding to five reminder information as follows:
Using above information, we can start drawing transition diagram TD of five states as follows:
Figure-1
So, 5 states for 5 remainder values. After processing a string ? if end-state becomes q0 that means decimal equivalent of input string is divisible by 5. In above figure q0 is marked final state as two concentric circle.
Additionally, I have defined a transition rule d:(q0, 0)?q0 as a self loop for symbol '0'
at state q0, this is because decimal equivalent of any string consist of only '0'
is 0 and 0 is a divisible by n
.
Step-2: TD above is incomplete; and can only process strings of '0'
s. Now add some more edges so that it can process subsequent number's strings. Check table below, shows new transition rules those can be added next step:
+-------------------------------------+ ¦Number¦Binary¦Remainder(%5)¦End-state¦ +------+------+-------------+---------¦ ¦One ¦1 ¦1 ¦q1 ¦ +------+------+-------------+---------¦ ¦Two ¦10 ¦2 ¦q2 ¦ +------+------+-------------+---------¦ ¦Three ¦11 ¦3 ¦q3 ¦ +------+------+-------------+---------¦ ¦Four ¦100 ¦4 ¦q4 ¦ +-------------------------------------+
'1'
there should be a transition rule d:(q0, 1)?q1 '10'
, end-state should be q2, and to process '10'
, we just need to add one more transition rule d:(q1, 0)?q2'11'
, end-state is q3, and we need to add a transition rule d:(q1, 1)?q3'100'
, end-state is q4. TD already processes prefix string '10'
and we just need to add a new transition rule d:(q2, 0)?q4Figure-2
Step-3: Five = 101
Above transition diagram in figure-2 is still incomplete and there are many missing edges, for an example no transition is defined for d:(q2, 1)-?. And the rule should be present to process strings like '101'
.
Because '101'
= 5 is divisible by 5, and to accept '101'
I will add d:(q2, 1)?q0 in above figure-2.
Path: ?(q0)-1?(q1)-0?(q2)-1?(q0)
with this new rule, transition diagram becomes as follows:
Figure-3
Below in each step I pick next subsequent binary number to add a missing edge until I get TD as a 'complete DFA'.
Step-4: Six = 110.
We can process '11'
in present TD in figure-3 as: ?(q0)-11?(q3) -0?(?). Because 6 % 5 = 1 this means to add one rule d:(q3, 0)?q1.
Figure-4
Step-5: Seven = 111
+--------------------------------------------------------------+ ¦Number¦Binary¦Remainder(%5)¦End-state¦ Path ¦ Add ¦ +------+------+-------------+---------+------------+-----------¦ ¦Seven ¦111 ¦7 % 5 = 2 ¦q2 ¦ q0-11?q3 ¦ q3-1?q2 ¦ +--------------------------------------------------------------+
Figure-5
Step-6: Eight = 1000
+----------------------------------------------------------+ ¦Number¦Binary¦Remainder(%5)¦End-state¦ Path ¦ Add ¦ +------+------+-------------+---------+----------+---------¦ ¦Eight ¦1000 ¦8 % 5 = 3 ¦q3 ¦q0-100?q4 ¦ q4-0?q3 ¦ +----------------------------------------------------------+
Figure-6
Step-7: Nine = 1001
+----------------------------------------------------------+ ¦Number¦Binary¦Remainder(%5)¦End-state¦ Path ¦ Add ¦ +------+------+-------------+---------+----------+---------¦ ¦Nine ¦1001 ¦9 % 5 = 4 ¦q4 ¦q0-100?q4 ¦ q4-1?q4 ¦ +----------------------------------------------------------+
Figure-7
In TD-7, total number of edges are 10 == Q × S = 5 × 2. And it is a complete DFA that can accept all possible binary strings those decimal equivalent is divisible by 5.
Step-1 Exactly same as for binary, use figure-1.
Step-2 Add Zero, One, Two
+------------------------------------------------------+ ¦Decimal¦Ternary¦Remainder(%5)¦End-state¦ Add ¦ +-------+-------+-------------+---------+--------------¦ ¦Zero ¦0 ¦0 ¦q0 ¦ d:(q0,0)?q0 ¦ +-------+-------+-------------+---------+--------------¦ ¦One ¦1 ¦1 ¦q1 ¦ d:(q0,1)?q1 ¦ +-------+-------+-------------+---------+--------------¦ ¦Two ¦2 ¦2 ¦q2 ¦ d:(q0,2)?q3 ¦ +------------------------------------------------------+
Figure-8
Step-3 Add Three, Four, Five
+-----------------------------------------------------+ ¦Decimal¦Ternary¦Remainder(%5)¦End-state¦ Add ¦ +-------+-------+-------------+---------+-------------¦ ¦Three ¦10 ¦3 ¦q3 ¦ d:(q1,0)?q3 ¦ +-------+-------+-------------+---------+-------------¦ ¦Four ¦11 ¦4 ¦q4 ¦ d:(q1,1)?q4 ¦ +-------+-------+-------------+---------+-------------¦ ¦Five ¦12 ¦0 ¦q0 ¦ d:(q1,2)?q0 ¦ +-----------------------------------------------------+
Figure-9
Step-4 Add Six, Seven, Eight
+-----------------------------------------------------+ ¦Decimal¦Ternary¦Remainder(%5)¦End-state¦ Add ¦ +-------+-------+-------------+---------+-------------¦ ¦Six ¦20 ¦1 ¦q1 ¦ d:(q2,0)?q1 ¦ +-------+-------+-------------+---------+-------------¦ ¦Seven ¦21 ¦2 ¦q2 ¦ d:(q2,1)?q2 ¦ +-------+-------+-------------+---------+-------------¦ ¦Eight ¦22 ¦3 ¦q3 ¦ d:(q2,2)?q3 ¦ +-----------------------------------------------------+
Figure-10
Step-5 Add Nine, Ten, Eleven
+-----------------------------------------------------+ ¦Decimal¦Ternary¦Remainder(%5)¦End-state¦ Add ¦ +-------+-------+-------------+---------+-------------¦ ¦Nine ¦100 ¦4 ¦q4 ¦ d:(q3,0)?q4 ¦ +-------+-------+-------------+---------+-------------¦ ¦Ten ¦101 ¦0 ¦q0 ¦ d:(q3,1)?q0 ¦ +-------+-------+-------------+---------+-------------¦ ¦Eleven ¦102 ¦1 ¦q1 ¦ d:(q3,2)?q1 ¦ +-----------------------------------------------------+
Figure-11
Step-6 Add Twelve, Thirteen, Fourteen
+------------------------------------------------------+ ¦Decimal ¦Ternary¦Remainder(%5)¦End-state¦ Add ¦ +--------+-------+-------------+---------+-------------¦ ¦Twelve ¦110 ¦2 ¦q2 ¦ d:(q4,0)?q2 ¦ +--------+-------+-------------+---------+-------------¦ ¦Thirteen¦111 ¦3 ¦q3 ¦ d:(q4,1)?q3 ¦ +--------+-------+-------------+---------+-------------¦ ¦Fourteen¦112 ¦4 ¦q4 ¦ d:(q4,2)?q4 ¦ +------------------------------------------------------+
Figure-12
Total number of edges in transition diagram figure-12 are 15 = Q × S = 5 * 3 (a complete DFA). And this DFA can accept all strings consist over {0, 1, 2} those decimal equivalent is divisible by 5.
If you notice at each step, in table there are three entries because at each step I add all possible outgoing edge from a state to make a complete DFA (and I add an edge so that qr state gets for remainder is r
)!
To add further, remember union of two regular languages are also a regular. If you need to design a DFA that accepts binary strings those decimal equivalent is either divisible by 3 or 5, then draw two separate DFAs for divisible by 3 and 5 then union both DFAs to construct target DFA (for 1 <= n <= 10 your have to union 10 DFAs).
If you are asked to draw DFA that accepts binary strings such that decimal equivalent is divisible by 5 and 3 both then you are looking for DFA of divisible by 15 ( but what about 6 and 8?).
Note: DFAs drawn with this technique will be minimized DFA only when there is no common factor between number n
and base e.g. there is no between 5 and 2 in first example, or between 5 and 3 in second example, hence both DFAs constructed above are minimized DFAs. If you are interested to read further about possible mini states for number n
and base b
read paper: Divisibility and State Complexity.
below I have added a Python script, I written it for fun while learning Python library pygraphviz. I am adding it I hope it can be helpful for someone in someway.
So we can apply above trick to draw DFA to recognize number strings in any base 'b'
those are divisible a given number 'n'
. In that DFA total number of states will be n
(for n
remainders) and number of edges should be equal to 'b' * 'n' — that is complete DFA: 'b' = number of symbols in language of DFA and 'n' = number of states.
Using above trick, below I have written a Python Script to Draw DFA for input base
and number
. In script, function divided_by_N
populates DFA's transition rules in base * number
steps. In each step-num, I convert num
into number string num_s
using function baseN()
. To avoid processing each number string, I have used a temporary data-structure lookup_table
. In each step, end-state for number string num_s
is evaluated and stored in lookup_table
to use in next step.
For transition graph of DFA, I have written a function draw_transition_graph
using Pygraphviz library (very easy to use). To use this script you need to install graphviz
. To add colorful edges in transition diagram, I randomly generates color codes for each symbol get_color_dict
function.
#!/usr/bin/env python
import pygraphviz as pgv
from pprint import pprint
from random import choice as rchoice
def baseN(n, b, syms="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
""" converts a number `n` into base `b` string """
return ((n == 0) and syms[0]) or (
baseN(n//b, b, syms).lstrip(syms[0]) + syms[n % b])
def divided_by_N(number, base):
"""
constructs DFA that accepts given `base` number strings
those are divisible by a given `number`
"""
ACCEPTING_STATE = START_STATE = '0'
SYMBOL_0 = '0'
dfa = {
str(from_state): {
str(symbol): 'to_state' for symbol in range(base)
}
for from_state in range(number)
}
dfa[START_STATE][SYMBOL_0] = ACCEPTING_STATE
# `lookup_table` keeps track: 'number string' -->[dfa]--> 'end_state'
lookup_table = { SYMBOL_0: ACCEPTING_STATE }.setdefault
for num in range(number * base):
end_state = str(num % number)
num_s = baseN(num, base)
before_end_state = lookup_table(num_s[:-1], START_STATE)
dfa[before_end_state][num_s[-1]] = end_state
lookup_table(num_s, end_state)
return dfa
def symcolrhexcodes(symbols):
"""
returns dict of color codes mapped with alphabets symbol in symbols
"""
return {
symbol: '#'+''.join([
rchoice("8A6C2B590D1F4E37") for _ in "FFFFFF"
])
for symbol in symbols
}
def draw_transition_graph(dfa, filename="filename"):
ACCEPTING_STATE = START_STATE = '0'
colors = symcolrhexcodes(dfa[START_STATE].keys())
# draw transition graph
tg = pgv.AGraph(strict=False, directed=True, decorate=True)
for from_state in dfa:
for symbol, to_state in dfa[from_state].iteritems():
tg.add_edge("Q%s"%from_state, "Q%s"%to_state,
label=symbol, color=colors[symbol],
fontcolor=colors[symbol])
# add intial edge from an invisible node!
tg.add_node('null', shape='plaintext', label='start')
tg.add_edge('null', "Q%s"%START_STATE,)
# make end acception state as 'doublecircle'
tg.get_node("Q%s"%ACCEPTING_STATE).attr['shape'] = 'doublecircle'
tg.draw(filename, prog='circo')
tg.close()
def print_transition_table(dfa):
print("DFA accepting number string in base '%(base)s' "
"those are divisible by '%(number)s':" % {
'base': len(dfa['0']),
'number': len(dfa),})
pprint(dfa)
if __name__ == "__main__":
number = input ("Enter NUMBER: ")
base = input ("Enter BASE of number system: ")
dfa = divided_by_N(number, base)
print_transition_table(dfa)
draw_transition_graph(dfa)
Execute it:
~/study/divide-5/script$ python script.py
Enter NUMBER: 5
Enter BASE of number system: 4
DFA accepting number string in base '4' those are divisible by '5':
{'0': {'0': '0', '1': '1', '2': '2', '3': '3'},
'1': {'0': '4', '1': '0', '2': '1', '3': '2'},
'2': {'0': '3', '1': '4', '2': '0', '3': '1'},
'3': {'0': '2', '1': '3', '2': '4', '3': '0'},
'4': {'0': '1', '1': '2', '2': '3', '3': '4'}}
~/study/divide-5/script$ ls
script.py filename.png
~/study/divide-5/script$ display filename
Output:
DFA accepting number strings in base 4 those are divisible by 5
Similarly, enter base = 4 and number = 7 to generate - dfa accepting number string in base '4' those are divisible by '7'
Btw, try changing filename
to .png
or .jpeg
.
References those I use to write this script:
➊ Function baseN
from "convert integer to a string in a given numeric base in python"
➋ To install "pygraphviz": "Python does not see pygraphviz"
➌ To learn use of Pygraphviz: "Python-FSM"
➍ To generate random hex color codes for each language symbol: "How would I make a random hexdigit code generator using .join and for loops?"
The following should do it:
$("input[type='checkbox']").click(function() {
var index = $(this).attr('name').substr(2);
$('table tr').each(function() {
$('td:eq(' + index + ')',this).toggle();
});
});
This is untested code, but the principle is that you choose the table cell in each row that corresponds to the chosen index extracted from the checkbox name. You could of course limit the selectors with a class or an ID.
All tables within the bootstrap stretch according to their container, which you can easily do by placing your table inside a .span*
grid element of your choice. If you wish to remove this property you can create your own table class and simply add it to the table you want to expand with the content within:
.table-nonfluid {
width: auto !important;
}
You can add this class inside your own stylesheet and simply add it to the container of your table like so:
<table class="table table-nonfluid"> ... </table>
This way your change won't affect the bootstrap stylesheet itself (you might want to have a fluid table somewhere else in your document).
Quoting Jacob Hallen:
The proper use of
__slots__
is to save space in objects. Instead of having a dynamic dict that allows adding attributes to objects at anytime, there is a static structure which does not allow additions after creation. [This use of__slots__
eliminates the overhead of one dict for every object.] While this is sometimes a useful optimization, it would be completely unnecessary if the Python interpreter was dynamic enough so that it would only require the dict when there actually were additions to the object.Unfortunately there is a side effect to slots. They change the behavior of the objects that have slots in a way that can be abused by control freaks and static typing weenies. This is bad, because the control freaks should be abusing the metaclasses and the static typing weenies should be abusing decorators, since in Python, there should be only one obvious way of doing something.
Making CPython smart enough to handle saving space without
__slots__
is a major undertaking, which is probably why it is not on the list of changes for P3k (yet).
variable.blank? will do it. It returns true if the string is empty or if the string is nil.
you have to do following:
1-Download the full project from here https://github.com/JakeWharton/ViewPagerIndicator ViewPager Indicator 2- Import into the Eclipse.
After importing if you want to make following type of screen then follow below steps -
change in
Sample circles Default
package com.viewpagerindicator.sample;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import com.viewpagerindicator.CirclePageIndicator;
public class SampleCirclesDefault extends BaseSampleActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_circles);
mAdapter = new TestFragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
// mPager.setAdapter(mAdapter);
ImageAdapter adapter = new ImageAdapter(SampleCirclesDefault.this);
mPager.setAdapter(adapter);
mIndicator = (CirclePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
}
ImageAdapter
package com.viewpagerindicator.sample;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
public class ImageAdapter extends PagerAdapter {
private Context mContext;
private Integer[] mImageIds = { R.drawable.about1, R.drawable.about2,
R.drawable.about3, R.drawable.about4, R.drawable.about5,
R.drawable.about6, R.drawable.about7
};
public ImageAdapter(Context context) {
mContext = context;
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
@Override
public Object instantiateItem(ViewGroup container, final int position) {
LayoutInflater inflater = (LayoutInflater) container.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View convertView = inflater.inflate(R.layout.gallery_view, null);
ImageView view_image = (ImageView) convertView
.findViewById(R.id.view_image);
TextView description = (TextView) convertView
.findViewById(R.id.description);
view_image.setImageResource(mImageIds[position]);
view_image.setScaleType(ImageView.ScaleType.FIT_XY);
description.setText("The natural habitat of the Niligiri tahr,Rajamala Rajamala is 2695 Mts above sea level"
+ "The natural habitat of the Niligiri tahr,Rajamala Rajamala is 2695 Mts above sea level"
+ "The natural habitat of the Niligiri tahr,Rajamala Rajamala is 2695 Mts above sea level");
((ViewPager) container).addView(convertView, 0);
return convertView;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((View) object);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ViewGroup) object);
}
}
gallery_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/about_bg"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/about_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1" >
<LinearLayout
android:id="@+id/about_layout1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".4"
android:orientation="vertical" >
<ImageView
android:id="@+id/view_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/about1">
</ImageView>
</LinearLayout>
<LinearLayout
android:id="@+id/about_layout2"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight=".6"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SIGNATURE LANDMARK OF MALAYSIA-SINGAPORE CAUSEWAY"
android:textColor="#000000"
android:gravity="center"
android:padding="18dp"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearance" />
<ScrollView
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:fillViewport="false"
android:orientation="vertical"
android:scrollbars="none"
android:layout_marginBottom="10dp"
android:padding="10dp" >
<TextView
android:id="@+id/description"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#000000"
android:text="TextView" />
</ScrollView>
</LinearLayout>
</LinearLayout>
Just to add my two cents.
A simpler way to understand what the bias is: it is somehow similar to the constant b of a linear function
y = ax + b
It allows you to move the line up and down to fit the prediction with the data better. Without b the line always goes through the origin (0, 0) and you may get a poorer fit.
Use a different function, like VLOOKUP:
=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", VLOOKUP(A1,B:C,2,FALSE))
Have you tried your own code?
This should work:
SELECT * FROM people WHERE age BETWEEN x AND y
When using google gson library.
var getRowData =
[{
"dayOfWeek": "Sun",
"date": "11-Mar-2012",
"los": "1",
"specialEvent": "",
"lrv": "0"
},
{
"dayOfWeek": "Mon",
"date": "",
"los": "2",
"specialEvent": "",
"lrv": "0.16"
}];
JsonElement root = new JsonParser().parse(request.getParameter("getRowData"));
JsonArray jsonArray = root.getAsJsonArray();
JsonObject jsonObject1 = jsonArray.get(0).getAsJsonObject();
String dayOfWeek = jsonObject1.get("dayOfWeek").toString();
// when using jackson library
JsonFactory f = new JsonFactory();
ObjectMapper mapper = new ObjectMapper();
JsonParser jp = f.createJsonParser(getRowData);
// advance stream to START_ARRAY first:
jp.nextToken();
// and then each time, advance to opening START_OBJECT
while (jp.nextToken() == JsonToken.START_OBJECT) {
Map<String,Object> userData = mapper.readValue(jp, Map.class);
userData.get("dayOfWeek");
// process
// after binding, stream points to closing END_OBJECT
}
Some (relatively) recent ideas against excessive mocking and pure unit-testing:
You can change style directly for scene using .root
class:
.root {
-fx-background-image: url("https://www.google.com/images/srpr/logo3w.png");
}
Add this to CSS and load it as "Uluk Biy" described in his answer.
FormulaR1C1 has the same behavior as Formula, only using R1C1 style annotation, instead of A1 annotation. In A1 annotation you would use:
Worksheets("Sheet1").Range("A5").Formula = "=A4+A10"
In R1C1 you would use:
Worksheets("Sheet1").Range("A5").FormulaR1C1 = "=R4C1+R10C1"
It doesn't act upon row 1 column 1, it acts upon the targeted cell or range. Column 1 is the same as column A, so R4C1 is the same as A4, R5C2 is B5, and so forth.
The command does not change names, the targeted cell changes. For your R2C3 (also known as C2) example :
Worksheets("Sheet1").Range("C2").FormulaR1C1 = "=your formula here"
In the accepted answer the ConcurrentBag is not required. Here's an implementation without it:
var tasks = myCollection.Select(GetData).ToList();
await Task.WhenAll(tasks);
var results = tasks.Select(t => t.Result);
Any of the "// some pre stuff" and "// some post stuff" can go into the GetData implementation (or another method that calls GetData)
Aside from being shorter, there's no use of an "async void" lambda, which is an anti pattern.
I have done the following to overcome the problem (ex.js script)
$ cat ex.js
import { Stack } from 'es-collections';
console.log("Successfully Imported");
$ node ex.js
/Users/nsaboo/ex.js:1
(function (exports, require, module, __filename, __dirname) { import { Stack } from 'es-collections';
^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:152:10)
at Module._compile (module.js:624:28)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Function.Module.runMain (module.js:701:10)
at startup (bootstrap_node.js:194:16)
at bootstrap_node.js:618:3
# npm package installation
npm install --save-dev babel-preset-env babel-cli es-collections
# .babelrc setup
$ cat .babelrc
{
"presets": [
["env", {
"targets": {
"node": "current"
}
}]
]
}
# execution with node
$ npx babel ex.js --out-file ex-new.js
$ node ex-new.js
Successfully Imported
# or execution with babel-node
$ babel-node ex.js
Successfully Imported
# Json to object
$obj = $obj | ConvertFrom-Json
Write-host $obj.PropertyName
In Firefox, just ctrl-a (select everything on the screen) then right click "View Selection Source". This captures any changes made by JavaScript to the DOM.
You can disabled the many of the outputs of hibernate setting this props of hibernate (hb configuration) a false:
hibernate.show_sql
hibernate.generate_statistics
hibernate.use_sql_comments
But if you want to disable all console info you must to set the logger level a NONE of FATAL of class org.hibernate
like Juha say.
The SQLite command line utility has a .schema TABLENAME
command that shows you the create statements.
exDict = {1:1, 2:2, 3:3}
with open('file.txt', 'w+') as file:
file.write(str(exDict))
$(".price").each(function(){
total_price += parseFloat($(this).val());
});
please try like this...
You can still do this in top. While top is running, press '1' on your keyboard, it will then show CPU usage per core.
Limit the processes shown by having that specific process run under a specific user account and use Type 'u' to limit to that user
Most easiest way in a single line of code
var base64Image = new Buffer( blob, 'binary' ).toString('base64');
on particular computer color codes can be assigned to different RGB color by editing color values in cmd window properties. Easy click color on color palete and change their rgb values.
change this
audio.src='audio/ogg/' + document.getElementById(song1.ogg);
to
audio.src='audio/ogg/' + document.getElementById('song1');
Just Follow Simple 1-2-3 Steps :
1) Go to Taskbar
2) Click on WAMP icon (Left Click)
3) Now Go to Apache > Services > Apache Module and check Rewrite_module is enable or not ! if its not then click on it ! WAMP will be automatically restarted and you're done !
Same principle as the solutions above. But I had issues with Firefox 52.0 (32 bit) where large files (>40 MBytes) are truncated at random positions. Re-scheduling the call of revokeObjectUrl() fixes this issue.
function saveFile(blob, filename) {
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, filename);
} else {
const a = document.createElement('a');
document.body.appendChild(a);
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = filename;
a.click();
setTimeout(() => {
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}, 0)
}
}
The simplest way to get the visitor’s/client’s IP address is using the $_SERVER['REMOTE_ADDR']
or $_SERVER['REMOTE_HOST']
variables.
However, sometimes this does not return the correct IP address of the visitor, so we can use some other server variables to get the IP address.
The below both functions are equivalent with the difference only in how and from where the values are retrieved.
getenv() is used to get the value of an environment variable in PHP.
// Function to get the client IP address
function get_client_ip() {
$ipaddress = '';
if (getenv('HTTP_CLIENT_IP'))
$ipaddress = getenv('HTTP_CLIENT_IP');
else if(getenv('HTTP_X_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
else if(getenv('HTTP_X_FORWARDED'))
$ipaddress = getenv('HTTP_X_FORWARDED');
else if(getenv('HTTP_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_FORWARDED_FOR');
else if(getenv('HTTP_FORWARDED'))
$ipaddress = getenv('HTTP_FORWARDED');
else if(getenv('REMOTE_ADDR'))
$ipaddress = getenv('REMOTE_ADDR');
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
$_SERVER is an array that contains server variables created by the web server.
// Function to get the client IP address
function get_client_ip() {
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
The following SQL statement:
select edition,version from v$instance
returns:
(select privilege on the v$instance view is of course necessary)
My solution was to include babel-node path while running nodemon as follows:
nodemon node_modules/.bin/babel-node index.js
you can add in your package.json script as :
debug: nodemon node_modules/.bin/babel-node index.js
NOTE: My entry file is index.js replace it with your entry file (many have app.js/server.js).
Here is a simple function for converting a byte buffer to string:
public String byteBufferToString(ByteBuffer bufferData) {
byte[] buffer = new byte[bufferData.readableByteCount()];
// read bufferData and insert into buffer
data.read(buffer);
// CharsetUtil supports UTF_16, ASCII, and many more
String text = new String(buffer, CharsetUtil.UTF_8);
System.out.println("Text: "+text);
return text;
}
On Linux it's Monospace
10 pt. (the exact monospace font used may vary on different Linux distributions or versions), on Windows it's Consolas
10 pt., and on OS X it's Menlo Regular
12 pt.
(The color scheme is Neon
, the syntax highlighting is from PackageDev
, and the font is Liberation Mono
This information is found in the Packages/Default
directory (where Packages
is the directory opened by the Preferences ? Browse Packages...
menu option), in the Preferences (OS).sublime-settings
file where OS
is one of Windows
, Linux
, or OSX
.
You should only customize the font (or any other setting) in Packages/User/Preferences.sublime-settings
, opened by Preferences ? Settings—User
, as Settings—Default
is over-written on upgrade, and also serves as a backup in case you really screw something up in your user settings. This is the case for both the main Sublime settings as well as those for extra packages/plugins.
These default fonts are the same in Sublime Text 2, Sublime Text 3, and the new version currently in development.
In Simple word- package.json of your project has not property of repository you must have to add it,
and you have to add repository in your package.json like below
and Let me explain according to your scenario
you must have to add repository field something like below
"repository" : {
"type" : "git",
"url" : "http://github.com/npm/express.git"
}
You can type sudo install (name of script) /usr/local/bin/(what you want to type to execute said script)
ex: sudo install quickcommit.sh /usr/local/bin/quickcommit
enter password
now can run without .sh and in any directory
svnadmin setlog /path/to/repository -r revision_number --bypass-hooks message_file.txt
Along with
<action android:name="android.intent.action.BOOT_COMPLETED" />
also use,
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
HTC devices dont seem to catch BOOT_COMPLETED
there is an Eclipse app called Import Jar As Project. I think it is quite simple and useful. https://marketplace.eclipse.org/content/import-jar-project?mpc=true&mpc_state=
There is something fundamentally wrong with what you're trying to do. Binary floating-points values do not have decimal places. You cannot meaningfully round one to a given number of decimal places, because most "round" decimal values simply cannot be represented as a binary fraction. Which is why one should never use float
or double
to represent money.
So if you want decimal places in your result, that result must either be a String
(which you already got with the DecimalFormat
), or a BigDecimal
(which has a setScale()
method that does exactly what you want). Otherwise, the result cannot be what you want it to be.
Read The Floating-Point Guide for more information.
@Logan has put this perfectly. Potentially something worth pointing out also is that you can use
printf(whatever you want to print);
For example if you were printing a string:
printf("hello");
For people having the same error with a similar code:
$(function(){
var app = angular.module("myApp", []);
app.controller('myController', function(){
});
});
Removing the $(function(){ ... }); solved the error.
For others who are looking to remove a built-in library, the route is to get into PackageContents -> Java -> libraries.
BUT : IT MAKES NO SENSE TO ELIMINATE LIBRARIES inside the app, they don't take space, don't have any influence on performance, and if you don't know what you are doing, you can harm the program. I did it because Arduino told me about libraries to update, showing then a board I don't have, and when saying ok it wanted to install a lot of new dependencies - I just felt forced to something I don't want, so I deinstalled that board.
Typographically, the correct glyph to use in sentence punctuation is the quote mark, both single (including for apostrophes) and double quotes. The straight-looking mark that we often see on the web is called a prime, which also comes in single and double varieties and has limited uses, mostly for measurements.
This article explains how to use them correctly.
Does anyone know how to get sed to print the position of the illegal byte sequence? Or does anyone know what the illegal byte sequence is?
$ uname -a
Darwin Adams-iMac 18.7.0 Darwin Kernel Version 18.7.0: Tue Aug 20 16:57:14 PDT 2019; root:xnu-4903.271.2~2/RELEASE_X86_64 x86_64
I got part of the way to answering the above just by using tr.
I have a .csv file that is a credit card statement and I am trying to import it into Gnucash. I am based in Switzerland so I have to deal with words like Zürich. Suspecting Gnucash does not like " " in numeric fields, I decide to simply replace all
; ;
with
;;
Here goes:
$ head -3 Auswertungen.csv | tail -1 | sed -e 's/; ;/;;/g'
sed: RE error: illegal byte sequence
I used od to shed some light: Note the 374 halfway down this od -c output
$ head -3 Auswertungen.csv | tail -1 | od -c
0000000 1 6 8 7 9 6 1 9 7 1 2 2 ; 5
0000020 4 6 8 8 7 X X X X X X 2 6
0000040 6 0 ; M Y N A M E I S X ; 1
0000060 4 . 0 2 . 2 0 1 9 ; 9 5 5 2 -
0000100 M i t a r b e i t e r r e s t
0000120 Z 374 r i c h
0000140 C H E ; R e s t a u r a n t s ,
0000160 B a r s ; 6 . 2 0 ; C H F ;
0000200 ; C H F ; 6 . 2 0 ; ; 1 5 . 0
0000220 2 . 2 0 1 9 \n
0000227
Then I thought I might try to persuade tr to substitute 374 for whatever the correct byte code is. So first I tried something simple, which didn't work, but had the side effect of showing me where the troublesome byte was:
$ head -3 Auswertungen.csv | tail -1 | tr . . ; echo
tr: Illegal byte sequence
1687 9619 7122;5468 87XX XXXX 2660;MY NAME ISX;14.02.2019;9552 - Mitarbeiterrest Z
You can see tr bails at the 374 character.
Using perl seems to avoid this problem
$ head -3 Auswertungen.csv | tail -1 | perl -pne 's/; ;/;;/g'
1687 9619 7122;5468 87XX XXXX 2660;ADAM NEALIS;14.02.2019;9552 - Mitarbeiterrest Z?rich CHE;Restaurants, Bars;6.20;CHF;;CHF;6.20;;15.02.2019
OK, placeholders behave differently in different browsers, so you need using browser prefix in your CSS to make them identical, for example Firefox gives a transparency to placeholder by default, so need to add opacity 1 to your css, plus the color, it's not a big concern most of the times, but good to have them consistent:
*::-webkit-input-placeholder { /* WebKit browsers */
color: #ccc;
}
*:-moz-placeholder { /* Mozilla Firefox <18 */
color: #ccc;
opacity: 1;
}
*::-moz-placeholder { /* Mozilla Firefox 19+ */
color: #ccc;
opacity: 1;
}
*:-ms-input-placeholder { /* Internet Explorer 10-11 */
color: #ccc;
}
For an oneliner, on linux or cygwin, you need to do public key authentication on the host, otherwise ssh will be asking for password.
gunzip -c numbers.sql.gz | ssh user@host mysql --user=user_name --password=your_password db_name
Or do port forwarding and connect to the remote mysql using a "local" connection:
ssh -L some_port:host:local_mysql_port user@host
then do the mysql connection on your local machine to localhost:some_port.
The port forwarding will work from putty too, with the similar -L option or you can configure it from the settings panel, somewhere down on the tree.
If none of the TargetDir or other macros point to the right place, use the ".." directory to go backwards up the folder hierarchy.
ie. Use $(SolutionDir)\..\..
to get your base directory.
For list of all macros, see here:
I spent ages trying to figure this out but it is simple! You can use length(·)
. length(mylist)
will tell you the number of objects mylist
contains.
... and just realised someone had already answered this- sorry!