If you are trying to display an Image in this way inside a loop, then you need to wrap the Image constructor in a display method.
from IPython.display import Image, display
listOfImageNames = ['/path/to/images/1.png',
'/path/to/images/2.png']
for imageName in listOfImageNames:
display(Image(filename=imageName))
If you are using 5.5.x:
const UPDATED_AT = null;
And for 'created_at' field, you can use:
const CREATED_AT = null;
Make sure you are on the newest version. (This was broken in Laravel 5.5.0 and fixed again in 5.5.5).
Try this DEMO:
$(document).ready(function () {
$("input[name='vehicle']").change(function () {
var maxAllowed = 3;
var cnt = $("input[name='vehicle']:checked").length;
if (cnt > maxAllowed)
{
$(this).prop("checked", "");
alert('Select maximum ' + maxAllowed + ' Levels!');
}
});
});
Best way is to handle this in an Ant script. You can create 2 different tasks for the 2 jar files. Specify class A as the main class in the manifst file for the first jar. similarly specify class B as the main class in the manifest file for the second jar.
you can easily run the Ant tasks from Netbeans.
Cygwin has issue recognizing space in between the PC name. So to solve this, you have to use "\" after the first word then include the space, then the last name.
such as ".../my\ dir/"
$ cd /cygdrive/c/Users/my\ dir/Documents
Another interesting and simple way to do it, is to put the directory in quotation marks ("")
e.g run it as follows:
$ cd c:
$ cd Users
$ cd "my dir"
$ cd Documents
Hope it works?
In php you just prepend $bom to your $csv_string:
$bom = sprintf( "%c%c%c", 239, 187, 191); // EF BB BF
file_put_contents( $file_name, $bom . $csv_string );
Tested with MS Excel 2016, php 7.2.4
This is a warning for usual. You can either disable it by
#pragma warning(disable:4996)
or simply use fopen_s like Microsoft has intended.
But be sure to use the pragma before other headers.
Quoting directly from the help page for factor
:
To transform a factor f to its original numeric values, as.numeric(levels(f))[f]
is recommended and slightly more efficient than as.numeric(as.character(f))
.
Ubuntu 16.04 64bit. I got the problem for apparently no reasons. The night before I watched a movie on my VideoLan instance, that night I would like to watch another one with VideoLan. VLC just didn't want to run because of the error into the question. I google a bit and I found the solution it solved my problem: from now on, VLC is runnable just like before. The solution is this comand:
sudo ln -sf /usr/lib/x86_64-linux-gnu/qt5/plugins/platforms/ /usr/bin/
I am not able to explain what are its consequencies, but I know it creates some missing symbolic link.
In the spectrum of kernel designs the two extreme points are monolithic kernels and microkernels.
The (classical) Linux kernel for instance is a monolithic kernel (and so is every commercial OS to date as well - though they might claim otherwise);
In that its code is a
single C file giving rise to a single process that implements all of the above
services.
To exemplify the encapsulation of the Linux kernel we remark that
the Linux kernel does not even have access to any of the standard C libraries.
Indeed the Linux kernel cannot use rudimentary C library functions such as
printf. Instead it implements its own printing function (called prints).
This seclusion of the Linux kernel and self-containment provide Linux kernel
with its main advantage: the kernel resides in a single address space1
enabling
all features to communicate in the fastest way possible without resorting to
any type of message passing.
In particular, a monolithic kernel implements all of the device drivers
of the system.
This however is the main drawback of a monolithic kernel:
introduction of any new unsupported hardware requires a rewrite of the
kernel (in the relevant parts), recompilation of it, and re-installing the entire
OS.
More importantly, if any device driver crashes the entire kernel suffers
as a result.
This un-modular approach to hardware additions and hardware crashes
is the main argument for supporting the other extreme design approach
for kernels. A microkernel is in a sense a minimalistic kernel that houses
only the very basic of OS services (like process management and file system
management). In a microkernel the device drivers lie outside of the kernel
allowing for addition and removal of device drivers while the OS is running
and require no alternations of the kernel.
I don't like adding new package into my project just to handle this simple task.
And also, I try my best to avoid RECURSIVE algorithm.... since, for most cases it is slower compared to non Recursive one.
So I made a function to get all the folder content (and its sub folder).... NON-Recursively
var getDirectoryContent = function(dirPath) {
/*
get list of files and directories from given dirPath and all it's sub directories
NON RECURSIVE ALGORITHM
By. Dreamsavior
*/
var RESULT = {'files':[], 'dirs':[]};
var fs = fs||require('fs');
if (Boolean(dirPath) == false) {
return RESULT;
}
if (fs.existsSync(dirPath) == false) {
console.warn("Path does not exist : ", dirPath);
return RESULT;
}
var directoryList = []
var DIRECTORY_SEPARATOR = "\\";
if (dirPath[dirPath.length -1] !== DIRECTORY_SEPARATOR) dirPath = dirPath+DIRECTORY_SEPARATOR;
directoryList.push(dirPath); // initial
while (directoryList.length > 0) {
var thisDir = directoryList.shift();
if (Boolean(fs.existsSync(thisDir) && fs.lstatSync(thisDir).isDirectory()) == false) continue;
var thisDirContent = fs.readdirSync(thisDir);
while (thisDirContent.length > 0) {
var thisFile = thisDirContent.shift();
var objPath = thisDir+thisFile
if (fs.existsSync(objPath) == false) continue;
if (fs.lstatSync(objPath).isDirectory()) { // is a directory
let thisDirPath = objPath+DIRECTORY_SEPARATOR;
directoryList.push(thisDirPath);
RESULT['dirs'].push(thisDirPath);
} else { // is a file
RESULT['files'].push(objPath);
}
}
}
return RESULT;
}
the only drawback of this function is that this is Synchronous function... You have been warned ;)
I put together something that does exactly what I was looking for and looks great. Using the scrollHeight of an element gets you the height of when it was loaded in the DOM.
var clickers = document.querySelectorAll('.clicker');_x000D_
clickers.forEach(clicker => {_x000D_
clicker.addEventListener('click', function (e) {_x000D_
var node = e.target.parentNode.childNodes[5];_x000D_
if (node.style.height == "0px" || node.style.height == "") {_x000D_
$(node).animate({ height: node.scrollHeight });_x000D_
}_x000D_
else {_x000D_
$(node).animate({ height: 0 });_x000D_
}_x000D_
});_x000D_
});
_x000D_
.answer{_x000D_
font-size:15px;_x000D_
color:blue;_x000D_
height:0px;_x000D_
overflow:hidden;_x000D_
_x000D_
}
_x000D_
<div class="row" style="padding-top:20px;">_x000D_
<div class="row" style="border-color:black;border-style:solid;border-radius:4px;border-width:4px;">_x000D_
<h1>This is an animation tester?</h1>_x000D_
<span class="clicker">click me</span>_x000D_
<p class="answer">_x000D_
I will be using this to display FAQ's on a website and figure you would like this. The javascript will allow this to work on all of the FAQ divs made by my razor code. the Scrollheight is the height of the answer element on the DOM load. Happy Coding :)_x000D_
Lorem ipsum dolor sit amet, mea an quis vidit autem. No mea vide inani efficiantur, mollis admodum accusata id has, eam dolore nemore eu. Mutat partiendo ea usu, pri duis vulputate eu. Vis mazim noluisse oportere id. Cum porro labore in, est accumsan euripidis scripserit ei. Albucius scaevola elaboraret usu eu. Ad sed vivendo persecuti, harum movet instructior eam ei._x000D_
</p>_x000D_
</div>_x000D_
</div>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
_x000D_
Jeremy's answer is great. If, like me, you're unsure of how to implement range(), you can see my version using range().
<?php
$character_array = array_merge(range('a', 'z'), range(0, 9));
$string = "";
for($i = 0; $i < 6; $i++) {
$string .= $character_array[rand(0, (count($character_array) - 1))];
}
echo $string;
?>
This does the exact same thing as Jeremy's but uses merged arrays where he uses a string, and uses count() where he uses strlen().
I wrote a VBA file to add a tool cleaning these abnormally biggest file. This script clear all columns and rows after the last cells realy used to reset the last cells ( [Ctrl]+[End] ), and it also provides enable images compression.
I dev an AddIns with auto install (just run it with macro enabled) to include in context menu many new buttons:
This is based on KB of Microsoft office 2003 and answer of PP. with personals improvement :
SOLUTION > you can download my *.xlam file ToolsKit
the main code is
Sub ClearExcessRowsAndColumns()
Dim ar As Range, r As Double, c As Double, tr As Double, tc As Double
Dim wksWks As Worksheet, ur As Range, arCount As Integer, i As Integer
Dim blProtCont As Boolean, blProtScen As Boolean, blProtDO As Boolean
Dim shp As Shape
Application.ScreenUpdating = False
On Error Resume Next
For Each wksWks In ActiveWorkbook.Worksheets
Err.Clear
'Store worksheet protection settings and unprotect if protected.
blProtCont = wksWks.ProtectContents
blProtDO = wksWks.ProtectDrawingObjects
blProtScen = wksWks.ProtectScenarios
wksWks.Unprotect ""
If Err.Number = 1004 Then
Err.Clear
MsgBox "'" & wksWks.Name & "' is protected with a password and cannot be checked.", vbInformation
Else
Application.StatusBar = "Checking " & wksWks.Name & ", Please Wait..."
r = 0
c = 0
'Determine if the sheet contains both formulas and constants
Set ur = Union(wksWks.UsedRange.SpecialCells(xlCellTypeConstants), wksWks.UsedRange.SpecialCells(xlCellTypeFormulas))
'If both fails, try constants only
If Err.Number = 1004 Then
Err.Clear
Set ur = wksWks.UsedRange.SpecialCells(xlCellTypeConstants)
End If
'If constants fails then set it to formulas
If Err.Number = 1004 Then
Err.Clear
Set ur = wksWks.UsedRange.SpecialCells(xlCellTypeFormulas)
End If
'If there is still an error then the worksheet is empty
If Err.Number <> 0 Then
Err.Clear
If wksWks.UsedRange.Address <> "$A$1" Then
ur.EntireRow.Delete
Else
Set ur = Nothing
End If
End If
'On Error GoTo 0
If Not ur Is Nothing Then
arCount = ur.Areas.Count
'determine the last column and row that contains data or formula
For Each ar In ur.Areas
i = i + 1
tr = ar.Range("A1").Row + ar.Rows.Count - 1
tc = ar.Range("A1").Column + ar.Columns.Count - 1
If tc > c Then c = tc
If tr > r Then r = tr
Next
'Determine the area covered by shapes
'so we don't remove shading behind shapes
For Each shp In wksWks.Shapes
tr = shp.BottomRightCell.Row
tc = shp.BottomRightCell.Column
If tc > c Then c = tc
If tr > r Then r = tr
Next
Application.StatusBar = "Clearing Excess Cells in " & wksWks.Name & ", Please Wait..."
Set ur = wksWks.Rows(r + 1 & ":" & wksWks.Rows.Count)
'Reset row height which can also cause the lastcell to be innacurate
ur.EntireRow.RowHeight = wksWks.StandardHeight
ur.Clear
Set ur = wksWks.Columns(ColLetter(c + 1) & ":" & ColLetter(wksWks.Columns.Count))
'Reset column width which can also cause the lastcell to be innacurate
ur.EntireColumn.ColumnWidth = wksWks.StandardWidth
ur.Clear
End If
End If
'Reset protection.
wksWks.Protect "", blProtDO, blProtCont, blProtScen
Err.Clear
Next
Application.StatusBar = False
' prepare les combinaison de touches pour la validation automatique de la fenetre
' Application.SendKeys "%(oe)~{TAB}~"
' ouvre la fenetre de compression des images
Application.CommandBars.ExecuteMso "PicturesCompress"
Application.ScreenUpdating = True
End Sub
Function ColLetter(ColNumber As Integer) As String
ColLetter = Left(Cells(1, ColNumber).Address(False, False), Len(Cells(1, ColNumber).Address(False, False)) - 1)
End Function
After looking for an answer for myself for some time, i could find something. in general if we are using it for just one property it appears same even if we do a "View Source" of generated HTML Below is generated HTML for example, when i want to display only Name property for my class
<td>
myClassNameProperty
</td>
<td>
myClassNameProperty, This is direct from Item
</td>
This is the generated HTML from below code
<td>
@Html.DisplayFor(modelItem=>item.Genre.Name)
</td>
<td>
@item.Genre.Name, This is direct from Item
</td>
At the same time now if i want to display all properties in one statement for my class "Genre" in this case, i can use @Html.DisplayFor() to save on my typing, for least
i can write @Html.DisplayFor(modelItem=>item.Genre) in place of writing a separate statement for each property of Genre as below
@item.Genre.Name
@item.Genre.Id
@item.Genre.Description
and so on depending on number of properties.
I know this question is quite old, but I have not seen this solution here before:
If you rewrite the <body>
tag to.
<body oncontextmenu="return false;">
you can prevent the right click without using javascript.
However, you can't prevent keyboard shortcuts with HTML. For this, you must use Javascript.
Let's try .... How to create a simple popup by using HTML, CSS, and jquery ...
$(function() {
// Open Popup
$('[popup-open]').on('click', function() {
var popup_name = $(this).attr('popup-open');
$('[popup-name="' + popup_name + '"]').fadeIn(300);
});
// Close Popup
$('[popup-close]').on('click', function() {
var popup_name = $(this).attr('popup-close');
$('[popup-name="' + popup_name + '"]').fadeOut(300);
});
// Close Popup When Click Outside
$('.popup').on('click', function() {
var popup_name = $(this).find('[popup-close]').attr('popup-close');
$('[popup-name="' + popup_name + '"]').fadeOut(300);
}).children().click(function() {
return false;
});
});
_x000D_
body {
font-family:Arial, Helvetica, sans-serif;
}
p {
font-size: 16px;
line-height: 26px;
letter-spacing: 0.5px;
color: #484848;
}
/* Popup Open button */
.open-button{
color:#FFF;
background:#0066CC;
padding:10px;
text-decoration:none;
border:1px solid #0157ad;
border-radius:3px;
}
.open-button:hover{
background:#01478e;
}
.popup {
position:fixed;
top:0px;
left:0px;
background:rgba(0,0,0,0.75);
width:100%;
height:100%;
display:none;
}
/* Popup inner div */
.popup-content {
width: 700px;
margin: 0 auto;
box-sizing: border-box;
padding: 40px;
margin-top: 100px;
box-shadow: 0px 2px 6px rgba(0,0,0,1);
border-radius: 3px;
background: #fff;
position: relative;
}
/* Popup close button */
.close-button {
width: 25px;
height: 25px;
position: absolute;
top: -10px;
right: -10px;
border-radius: 20px;
background: rgba(0,0,0,0.8);
font-size: 20px;
text-align: center;
color: #fff;
text-decoration:none;
}
.close-button:hover {
background: rgba(0,0,0,1);
}
@media screen and (max-width: 720px) {
.popup-content {
width:90%;
}
}
_x000D_
<!DOCTYPE html>
<html>
<head>
<title> Popup </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<a class="open-button" popup-open="popup-1" href="javascript:void(0)"> Popup
Preview</a>
<div class="popup" popup-name="popup-1">
<div class="popup-content">
<h2>Title of Popup </h2>
<p>Popup 1 content will be here. Lorem ipsum dolor sit amet,
consectetur adipiscing elit. Aliquam consequat diam ut tortor
dignissim, vel accumsan libero venenatis. Nunc pretium volutpat
convallis. Integer at metus eget neque hendrerit vestibulum.
Aenean vel mattis purus. Fusce condimentum auctor tellus eget
ullamcorper. Vestibulum sagittis pharetra tellus mollis vestibulum.
Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<a class="close-button" popup-close="popup-1" href="javascript:void(0)">x</a>
</div>
</div>
</body>
</html>
_x000D_
You could do it without javascript and simply use anchor tags? Then it would be accessible to those js free.
although as you are using modals, I assume you don't care about being js free. ;)
TL:DR
row lock = A$5
column lock = $A5
Both = $A$5
Below are examples of how to use the Excel lock reference $
when creating your formulas
To prevent increments when moving from one row to another put the $ after the column letter and before the row number. e.g. A$5
To prevent increments when moving from one column to another put the $ before the row number. e.g. $A5
To prevent increments when moving from one column to another or from one row to another put the $ before the row number and before the column letter. e.g. $A$5
Using the lock reference will also prevent increments when dragging cells over to duplicate calculations.
Based on what @J. Calleja said, you have two choices
If you want to random access the element of Mat, just simply use
Mat.at<data_Type>(row_num, col_num) = value;
If you want to continuous access, OpenCV provides Mat iterator compatible with STL iterator
and it's more C++
style
MatIterator_<double> it, end;
for( it = I.begin<double>(), end = I.end<double>(); it != end; ++it)
{
//do something here
}
or
for(int row = 0; row < mat.rows; ++row) {
float* p = mat.ptr(row); //pointer p points to the first place of each row
for(int col = 0; col < mat.cols; ++col) {
*p++; // operation here
}
}
If you have any difficulty to understand how Method 2 works, I borrow the picture from a blog post in the article Dynamic Two-dimensioned Arrays in C, which is much more intuitive and comprehensible.
See the picture below.
First off it's important to understand that there are two kinds of "event listeners":
Scope event listeners registered via $on
:
$scope.$on('anEvent', function (event, data) {
...
});
Event handlers attached to elements via for example on
or bind
:
element.on('click', function (event) {
...
});
When $scope.$destroy()
is executed it will remove all listeners registered via $on
on that $scope.
It will not remove DOM elements or any attached event handlers of the second kind.
This means that calling $scope.$destroy()
manually from example within a directive's link function will not remove a handler attached via for example element.on
, nor the DOM element itself.
Note that remove
is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.
When element.remove()
is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on
.
It will not destroy the $scope associated with the element.
To make it more confusing there is also a jQuery event called $destroy
. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:
element.on('$destroy', function () {
scope.$destroy();
});
This depends on how the directive is "destroyed".
A normal case is that a directive is destroyed because ng-view
changes the current view. When this happens the ng-view
directive will destroy the associated $scope, sever all the references to its parent scope and call remove()
on the element.
This means that if that view contains a directive with this in its link function when it's destroyed by ng-view
:
scope.$on('anEvent', function () {
...
});
element.on('click', function () {
...
});
Both event listeners will be removed automatically.
However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references
.
Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.
For example if you have registered a listener on $rootScope
:
var unregisterFn = $rootScope.$on('anEvent', function () {});
scope.$on('$destroy', unregisterFn);
This is needed since $rootScope
is never destroyed during the lifetime of the application.
The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.
Another situation would be to cancel $interval
/$timeout
:
var promise = $interval(function () {}, 1000);
scope.$on('$destroy', function () {
$interval.cancel(promise);
});
If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:
var windowClick = function () {
...
};
angular.element(window).on('click', windowClick);
scope.$on('$destroy', function () {
angular.element(window).off('click', windowClick);
});
These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view
or ng-if
.
If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.
You can use the already mentioned built in Responsive Design Mode (via dev tools) for setting customised screen sizes together with the Random Agent Spoofer Plugin to modify your headers to simulate you are using Mobile, Tablet etc. Many websites specify their content according to these identified headers.
As dev tools you can use the built in Developer Tools (Ctrl + Shift + I or Cmd + Shift + I for Mac) which have become quite similar to Chrome dev tools by now.
Use Integer.parseInt, and make sure you catch the NumberFormatException that it throws if the input is not an integer.
Here is a simple example
from pandas import DataFrame
# Create data set
d = {'Revenue':[100,111,222],
'Cost':[333,444,555]}
df = DataFrame(d)
# mask = Return True when the value in column "Revenue" is equal to 111
mask = df['Revenue'] == 111
print mask
# Result:
# 0 False
# 1 True
# 2 False
# Name: Revenue, dtype: bool
# Select * FROM df WHERE Revenue = 111
df[mask]
# Result:
# Cost Revenue
# 1 444 111
.bak
is a backup file generated in SQL Server.
Backup files importing means restoring a database, you can restore on a database created in SQL Server 2012 but the backup file should be from SQL Server 2005, 2008, 2008 R2, 2012 database.
You restore database by using following command...
RESTORE DATABASE YourDB FROM DISK = 'D:BackUpYourBaackUpFile.bak' WITH Recovery
You want to learn about how to restore .bak
file follow the below link:
http://msdn.microsoft.com/en-us/library/ms186858(v=sql.90).aspx
Check the Namespace.
You might assign System.Web.Webpages.Html.SelectListItem in the Controller, instead of System.Web.Mvc.SelectListItem.
I think that ignoring the warning might be legitimate if you want to give the child class the ability to set or override a property that the parent constructor will use right away:
internal class Parent
{
public Parent()
{
Console.WriteLine("Parent ctor");
Console.WriteLine(Something);
}
protected virtual string Something { get; } = "Parent";
}
internal class Child : Parent
{
public Child()
{
Console.WriteLine("Child ctor");
Console.WriteLine(Something);
}
protected override string Something { get; } = "Child";
}
The risk here would be for the child class to set the property from its constructor in which case the change in the value would occur after the base class constructor has been called.
My use case is that I want the child class to provide a specific value or a utility class such as a converter and I don't want to have to call an initialization method on the base.
The output of the above when instantiating the child class is:
Parent ctor
Child
Child ctor
Child
a=123
if [ `echo $a | tr -d [:digit:] | wc -w` -eq 0 ]
then
echo numeric
else
echo ng
fi
numeric
a=12s3
if [ `echo $a | tr -d [:digit:] | wc -w` -eq 0 ]
then
echo numeric
else
echo ng
fi
ng
This should work:
window.onload = function() {
document.getElementById('about').className = 'expand';
};
Or if you're using jQuery:
$(function() {
$('#about').addClass('expand');
});
This could be because of wrong configuration, esp if your other sites are working fine.
<VirtualHost cmsdemo.git:88>
DocumentRoot "C:/Projects/rwp/"
ServerName cmsdemo.git
<Directory C:/Projects/cmsdemo/>
Require all granted
AllowOverride All
</Directory>
</VirtualHost>
Notice in DocumentRoot I am specifying one folder and in Directory, I am specifying another hence 403 Error. This fixed my problem.
Why not just:
$('#b').click(function () {
var val = $(this).val();
})
Or if you don't click it (and I guess you won't) and you will use submit button, you can use prev()
function either.
I tried to add another join(), and it seems worked. Here is code
from threading import Thread
from time import sleep
def function01(arg,name):
for i in range(arg):
print(name,'i---->',i,'\n')
print (name,"arg---->",arg,'\n')
sleep(1)
def test01():
thread1 = Thread(target = function01, args = (10,'thread1', ))
thread1.start()
thread2 = Thread(target = function01, args = (10,'thread2', ))
thread2.start()
thread1.join()
thread2.join()
print ("thread finished...exiting")
test01()
Based on my observations:
$request->request->add(['variable' => 'value']);
will (mostly) work in POST, PUT & DELETE methods, because there is value(s) passed, one of those is _token
. Like example below.
<form action="{{ route('process', $id) }}" method="POST">
@csrf
</form>
public function process(Request $request, $id){
$request->request->add(['id' => $id]);
}
But [below code] won't work because there is no value(s) passed, it doesn't really add.
<a href='{{ route('process', $id) }}'>PROCESS</a>
public function process(Request $request, $id){
$request->request->add(['id' => $id]);
}
public function process($id){
$request = new Request(['id' => $id]);
}
Or you can use merge
. This is better actually than $request->request->add(['variable' => 'value']);
because can initialize, and add request values that will work for all methods (GET, POST, PUT, DELETE)
public function process(Request $request, $id){
$request->merge(['id' => $id]);
}
Tag: laravel5.8.11
I use function for returning index for the matching element (Python 2.6):
def index(l, f):
return next((i for i in xrange(len(l)) if f(l[i])), None)
Then use it via lambda function for retrieving needed element by any required equation e.g. by using element name.
element = mylist[index(mylist, lambda item: item["name"] == "my name")]
If i need to use it in several places in my code i just define specific find function e.g. for finding element by name:
def find_name(l, name):
return l[index(l, lambda item: item["name"] == name)]
And then it is quite easy and readable:
element = find_name(mylist,"my name")
DEMO
In the content area you can provide whatever you want to display in it.
.black_overlay {_x000D_
display: none;_x000D_
position: absolute;_x000D_
top: 0%;_x000D_
left: 0%;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
background-color: black;_x000D_
z-index: 1001;_x000D_
-moz-opacity: 0.8;_x000D_
opacity: .80;_x000D_
filter: alpha(opacity=80);_x000D_
}_x000D_
.white_content {_x000D_
display: none;_x000D_
position: absolute;_x000D_
top: 25%;_x000D_
left: 25%;_x000D_
width: 50%;_x000D_
height: 50%;_x000D_
padding: 16px;_x000D_
border: 16px solid orange;_x000D_
background-color: white;_x000D_
z-index: 1002;_x000D_
overflow: auto;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<title>LIGHTBOX EXAMPLE</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<p>This is the main content. To display a lightbox click <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">here</a>_x000D_
</p>_x000D_
<div id="light" class="white_content">This is the lightbox content. <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Close</a>_x000D_
</div>_x000D_
<div id="fade" class="black_overlay"></div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Just drop the option v
.
-v
is for verbose. If you don't use it then it won't display:
tar -zxf tmp.tar.gz -C ~/tmp1
See SBQL4J. It's type-safe strong query language integrated with Java. Allows to write complicated and multiply nested queries. There is a lot of operators, Java methods can be invoked inside queries so as constructors. Queries are translated to pure Java code (there is no reflection at runtime) so execution is very fast.
EDIT: Well, so far SBQL4J it's the ONLY extension to Java language which gives query capabilities similar to LINQ. There are some interesting project like Quaere and JaQue but they are only API's, not syntax / semantics extension with strong type safety in compile time.
I also had the same problem after installing 32 bit version of java it solved.
If you use rs.next() you will move the cursor, than you should to move first() why don't check using first() directly?
public void fetchData(ResultSet res, JTable table) throws SQLException{
ResultSetMetaData metaData = res.getMetaData();
int fieldsCount = metaData.getColumnCount();
for (int i = 1; i <= fieldsCount; i++)
((DefaultTableModel) table.getModel()).addColumn(metaData.getColumnLabel(i));
if (!res.first())
JOptionPane.showMessageDialog(rootPane, "no data!");
else
do {
Vector<Object> v = new Vector<Object>();
for (int i = 1; i <= fieldsCount; i++)
v.addElement(res.getObject(i));
((DefaultTableModel) table.getModel()).addRow(v);
} while (res.next());
res.close();
}
in devices which has Android 4.3 and above you should follow these steps:
How to enable Developer Options:
Launch Settings menu.
Find the open the ‘About Device’ menu.
Scroll down to ‘Build Number’.
Next, tap on the ‘build number’ section seven times.
After the seventh tap you will be told that you are now a developer.
Go back to Settings menu and the Developer Options menu will now be displayed.
In order to enable the USB Debugging you will simply need to open Developer Options, scroll down and tick the box that says ‘USB Debugging’. That’s it.
CPUnit (http://cpunit.sourceforge.net) is a framework that is similar to Google Test, but which relies on less macos (asserts are functions), and where the macros are prefixed to avoid the usual macro pitfall. Tests look like:
#include <cpunit>
namespace MyAssetTest {
using namespace cpunit;
CPUNIT_FUNC(MyAssetTest, test_stuff) {
int some_value = 42;
assert_equals("Wrong value!", 666, some_value);
}
// Fixtures go as follows:
CPUNIT_SET_UP(MyAssetTest) {
// Setting up suite here...
// And the same goes for tear-down.
}
}
They auto-register, so you need not more than this. Then it is just compile and run. I find using this framework very much like using JUnit, for those who have had to spend some time programming Java. Very nice!
I've been using this in Python 3, including pattern matching on the filename.
from pathlib import Path
def latest_file(path: Path, pattern: str = "*"):
files = path.glob(pattern)
return max(files, key=lambda x: x.stat().st_ctime)
Get the number of text fields from the user and assign it to a variable.
var no = document.getElementById("idname").value
To create input fields, use createElement
method and specify element name i.e. "input" as parameter like below and assign it to a variable.
var textfield = document.createElement("input");
Then assign necessary attributes to the variable.
textfield.type = "text";
textfield.value = "";
At last append variable to the form element using appendChild
method. so that the input element will be created in the form element itself.
document.getElementById('form').appendChild(textfield);
Loop the 2,3 and 4 step to create desired number of input elements given by the user inside the form element.
for(var i=0;i<no;i++) {
var textfield = document.createElement("input");
textfield.type = "text"; textfield.value = "";
document.getElementById('form').appendChild(textfield);
}
Here's the complete code
function fun() {
/*Getting the number of text fields*/
var no = document.getElementById("idname").value;
/*Generating text fields dynamically in the same form itself*/
for(var i=0;i<no;i++) {
var textfield = document.createElement("input");
textfield.type = "text";
textfield.value = "";
document.getElementById('form').appendChild(textfield);
}
}
_x000D_
<form id="form">
<input type="type" id="idname" oninput="fun()" value="">
</form>
_x000D_
There is no structure in numpy that allows you to append more data later.
Instead, numpy puts all of your data into a contiguous chunk of numbers (basically; a C array), and any resize requires allocating a new chunk of memory to hold it. Numpy's speed comes from being able to keep all the data in a numpy array in the same chunk of memory; e.g. mathematical operations can be parallelized for speed and you get less cache misses.
So you will have two kinds of solutions:
images = []
for i in range(100):
new_image = # pull image from somewhere
images.append(new_image)
images = np.stack(images, axis=3)
Note that there is no need to expand the dimensions of the individual image arrays first, nor do you need to know how many images you expect ahead of time.
Download the latest CMake Mac binary distribution here: https://cmake.org/download/ (current latest is: https://cmake.org/files/v3.17/cmake-3.17.1-Darwin-x86_64.dmg)
Double click the downloaded .dmg file to install it. In the window that pops up, drag the CMake icon into the Application folder.
Add this line to your .bashrc file: PATH="/Applications/CMake.app/Contents/bin":"$PATH"
Reload your .bashrc file: source ~/.bashrc
Verify the latest cmake version is installed: cmake --version
You can launch the CMake GUI by clicking on LaunchPad and typing cmake. Click on the CMake icon that appears.
The difference is that variant 1 forces you to use an ArrayList
while variant 2 only guarantees you have anything that implements List<String>
.
Later on you could change that to List<String> arrayList = new LinkedList<String>();
without much hassle. Variant 1 might require you to change not only that line but other parts as well if they rely on working with an ArrayList<String>
.
Thus I'd use List<String>
in almost any case, except when I'd need to call the additional methods that ArrayList
provides (which was never the case so far): ensureCapacity(int)
and trimToSize()
.
"files" in *nix type systems are very much an abstract concept.
They can be areas on disk organized by a file system, but they could equally well be a network connection, a bit of shared memory, the buffer output from another process, a screen or a keyboard.
In order for perl to be really useful it mirrors this model very closely, and does not treat files by emulating a magnetic tape as many 4gls do.
So it tried an "IOCTL" operation 'open for write' on a file handle which does not allow write operations which is an inappropriate IOCTL operation for that device/file.
The easiest thing to do is stick an " or die 'Cannot open $myfile'
statement at the end of you open and you can choose your own meaningful message.
It looks like not all of your prerequisites are really working as they should be. Also, you'll want to make sure that you are installing from the console itself and not through any kind of remote session at all. (I know, this is a pain in the a@@, but sometimes it makes a difference.)
You can acess the SQL Server 2005 Books Online on the Web at: http://msdn.microsoft.com/en-us/library/ms130214(SQL.90).aspx. This documentation should help you decipher the logs.
Bonus tidbit: Once you get that far, if you plan on installing SP2 without getting an installation that fails and rolls back, another little pearl of wisdom is described here: http://blog.andreloker.de/post/2008/07/17/SQL-Server-hotfix-KB948109-fails-with-error-1920.aspx. (My issue was that the "SQL Server VSS Writer" (Service) was not even installed.) Good luck!
For further visitors:
// Executes: SELECT * FROM mytable LIMIT 10 OFFSET 20
// get([$table = ''[, $limit = NULL[, $offset = NULL]]])
$query = $this->db->get('mytable', 10, 20);
// get_where sample,
$query = $this->db->get_where('mytable', array('id' => $id), 10, 20);
// Produces: LIMIT 10
$this->db->limit(10);
// Produces: LIMIT 10 OFFSET 20
// limit($value[, $offset = 0])
$this->db->limit(10, 20);
I used this code so I still could support older Android versions and use recreate()
on newer Android versions.
Code:
public static void restartActivity(Activity activity){
if (Build.VERSION.SDK_INT >= 11) {
activity.recreate();
} else {
activity.finish();
activity.startActivity(activity.getIntent());
}
}
Sample:
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Activity mActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mActivity = MainActivity.this;
Button button = (Button) findViewById(R.id.restart_button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
restartActivity(mActivity);
}
});
}
public static void restartActivity(Activity activity) {
if (Build.VERSION.SDK_INT >= 11) {
activity.recreate();
} else {
activity.finish();
activity.startActivity(activity.getIntent());
}
}
}
There are two ways to resize an image. The new size can be specified:
Manually;
height, width = src.shape[:2]
dst = cv2.resize(src, (2*width, 2*height), interpolation = cv2.INTER_CUBIC)
By a scaling factor.
dst = cv2.resize(src, None, fx = 2, fy = 2, interpolation = cv2.INTER_CUBIC)
,
where fx is the scaling factor along the horizontal axis and fy along the vertical axis.
To shrink an image, it will generally look best with INTER_AREA interpolation, whereas to enlarge an image, it will generally look best with INTER_CUBIC (slow) or INTER_LINEAR (faster but still looks OK).
import cv2
img = cv2.imread('YOUR_PATH_TO_IMG')
height, width = img.shape[:2]
max_height = 300
max_width = 300
# only shrink if img is bigger than required
if max_height < height or max_width < width:
# get scaling factor
scaling_factor = max_height / float(height)
if max_width/float(width) < scaling_factor:
scaling_factor = max_width / float(width)
# resize image
img = cv2.resize(img, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA)
cv2.imshow("Shrinked image", img)
key = cv2.waitKey()
import cv2 as cv
im = cv.imread(path)
height, width = im.shape[:2]
thumbnail = cv.resize(im, (round(width / 10), round(height / 10)), interpolation=cv.INTER_AREA)
cv.imshow('exampleshq', thumbnail)
cv.waitKey(0)
cv.destroyAllWindows()
A nice trick to use in place of the various print formats:
(1) Pad with spaces to the right:
('hi' + ' ')[:8]
(2) Pad with leading zeros on the left:
('0000' + str(2))[-4:]
This works fine as far as characters restriction, Any suggestions on error msg prompt with my code if it's not C OR L
Private Sub TXTBOX_TextChanged(sender As System.Object, e As System.EventArgs) Handles TXTBOX.TextChanged
Dim allowed As String = "C,L"
For Each C As Char In TXTBOX.Text
If allowed.Contains(C) = False Then
TXTBOX.Text = TXTBOX.Text.Remove(TXTBOX.SelectionStart - 1, 1)
TXTBOX.Select(TXTBOX.Text.Count, 0)
End If
Next
End Sub
Something to be aware of, the $_SESSION
variables are still set in the same page after calling session_destroy()
where as this is not the case when using unset($_SESSION)
or $_SESSION = array()
. Also, unset($_SESSION)
blows away the $_SESSION
superglobal so only do this when you're destroying a session.
With all that said, it's best to do like the PHP docs has it in the first example for session_destroy()
.
word
is on the stack and goes out of scope as soon as getStr()
returns. You are invoking undefined behavior.
I think you want to cast your dt
to a date
and fix the format of your date literal:
SELECT *
FROM table
WHERE dt::date = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD
Or the standard version:
SELECT *
FROM table
WHERE CAST(dt AS DATE) = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD
The extract
function doesn't understand "date" and it returns a number.
UPDATE user_account
SET (student_education_facility_id) = (
SELECT teacher.education_facility_id
FROM user_account teacher
WHERE teacher.user_account_id = teacher_id
AND teacher.user_type = 'ROLE_TEACHER'
)
WHERE user_type = 'ROLE_STUDENT'
Above are the sample update query...
You can write sub query with update SQL statement, you don't need to give alias name for that table. give alias name to sub query table. I tried and it's working fine for me....
Stack memory is specifically the range of memory that is accessible via the Stack register of the CPU. The Stack was used as a way to implement the "Jump-Subroutine"-"Return" code pattern in assembly language, and also as a means to implement hardware-level interrupt handling. For instance, during an interrupt, the Stack was used to store various CPU registers, including Status (which indicates the results of an operation) and Program Counter (where was the CPU in the program when the interrupt occurred).
Stack memory is very much the consequence of usual CPU design. The speed of its allocation/deallocation is fast because it is strictly a last-in/first-out design. It is a simple matter of a move operation and a decrement/increment operation on the Stack register.
Heap memory was simply the memory that was left over after the program was loaded and the Stack memory was allocated. It may (or may not) include global variable space (it's a matter of convention).
Modern pre-emptive multitasking OS's with virtual memory and memory-mapped devices make the actual situation more complicated, but that's Stack vs Heap in a nutshell.
You can rename a file using git
's mv
command:
$ git mv file_from file_to
Example:
$ git mv helo.txt hello.txt
$ git status
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# renamed: helo.txt -> hello.txt
#
$ git commit -m "renamed helo.txt to hello.txt"
[master 14c8c4f] renamed helo.txt to hello.txt
1 files changed, 0 insertions(+), 0 deletions(-)
rename helo.txt => hello.txt (100%)
I suggest my code.
DllExport void get_local_ips(boost::container::vector<wstring>& ips)
{
IP_ADAPTER_ADDRESSES* adapters = NULL;
IP_ADAPTER_ADDRESSES* adapter = NULL;
IP_ADAPTER_UNICAST_ADDRESS* adr = NULL;
ULONG adapter_size = 0;
ULONG err = 0;
SOCKADDR_IN* sockaddr = NULL;
err = ::GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME, NULL, NULL, &adapter_size);
adapters = (IP_ADAPTER_ADDRESSES*)malloc(adapter_size);
err = ::GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME, NULL, adapters, &adapter_size);
for (adapter = adapters; NULL != adapter; adapter = adapter->Next)
{
if (adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK) continue; // Skip Loopback
if (adapter->OperStatus != IfOperStatusUp) continue; // Live connection only
for (adr = adapter->FirstUnicastAddress;adr != NULL; adr = adr->Next)
{
sockaddr = (SOCKADDR_IN*)(adr->Address.lpSockaddr);
char ipstr [INET6_ADDRSTRLEN] = { 0 };
wchar_t ipwstr[INET6_ADDRSTRLEN] = { 0 };
inet_ntop(AF_INET, &(sockaddr->sin_addr), ipstr, INET_ADDRSTRLEN);
mbstowcs(ipwstr, ipstr, INET6_ADDRSTRLEN);
wstring wstr(ipwstr);
if (wstr != "0.0.0.0") ips.push_back(wstr);
}
}
free(adapters);
adapters = NULL; }
For situations where you must put text or html content within an anchor tag, but you simply don't want any action to be taken at all when that element is clicked (like when you want a paginator link to be in the disabled state because it's the current page), simply cut out the href. ;)
<a>3 (current page, I'm totally disabled!)</a>
The answer by @michael-meadows tipped me off to this, but his was still addressing scenarios where you still have to / are working with jQuery/JS. In this case, if you have control over writing the html itself, simply x-ing the href tag is all you need to do, so the solution is a pure HTML one!
Other solutions without jQuery finagling which keep the href require you to put a # in the href, but that causes the page to bounce to the top, and you just want it to be plain old disabled. Or leaving it empty, but depending on browser, that still does stuff like jump to the top, and, it is invalid HTML according to the IDEs. But apparently an a
tag is totally valid HTML without an HREF.
Lastly, you might say: Okay, why not just dump the a tag altogether than? Because often you can't, the a
tag is used for styling purposes in the CSS framework or control you're using, like Bootstrap's paginator:
http://twitter.github.io/bootstrap/components.html#pagination
You cannot do it with just method, unless you use some javascript framework like jquery which supports it ..
string s = '<div id="myDiv"></div>'
var htmlObject = $(s); // jquery call
but still, it would not be found by the getElementById
because for that to work the element must be in the DOM... just creating in the memory does not insert it in the dom.
You would need to use append
or appendTo
or after
etc.. to put it in the dom first..
Of'course all these can be done through regular javascript but it would take more steps to accomplish the same thing... and the logic is the same in both cases..
Install an interval:
<script type="text/javascript">
setInterval(page_refresh, 5*60000); //NOTE: period is passed in milliseconds
</script>
If it's a local development tomcat launched from IDE, then restarting this IDE and rebuild project also helps.
Update:
You could also try to find if there is any running tomcat process in the background and kill it.
You're on a 32-bit machine or a 64-bit Windows machine. On my 64-bit machine (running a Unix-derivative O/S, not Windows), sizeof(int) == 4
, but sizeof(long) == 8
.
They're different types — sometimes the same size as each other, sometimes not.
(In the really old days, sizeof(int) == 2
and sizeof(long) == 4
— though that might have been the days before C++ existed, come to think of it. Still, technically, it is a legitimate configuration, albeit unusual outside of the embedded space, and quite possibly unusual even in the embedded space.)
When a variable is declared static inside a class then it becomes a shared variable for all objects of that class which means that the variable is longer specific to any object. For example: -
#include<iostream.h>
#include<conio.h>
class test
{
void fun()
{
static int a=0;
a++;
cout<<"Value of a = "<<a<<"\n";
}
};
void main()
{
clrscr();
test obj1;
test obj2;
test obj3;
obj1.fun();
obj2.fun();
obj3.fun();
getch();
}
This program will generate the following output: -
Value of a = 1
Value of a = 2
Value of a = 3
The same goes for globally declared static variable. The above code will generate the same output if we declare the variable a outside function void fun()
Whereas if u remove the keyword static and declare a as a non-static local/global variable then the output will be as follows: -
Value of a = 1
Value of a = 1
Value of a = 1
An alternative is Joda-Time.
Use DateTime
DateTime date = new DateTime(new Date());
date.isBeforeNow();
or
date.isAfterNow();
This is an updated version of aphoria's Answer.
I Replaced PSLIST and PSEXEC with TASKKILL and TASKLIST`. As they seem to work better, I couldn't get PSLIST to run in Windows 7.
Also replaced Sleep with TIMEOUT.
This Was everything i needed to get the script running well, and all the additions was provided by the great guys who posted the comments.
Also if there is a delay before the .exe starts it might be worth inserting a Timeout before the :loop.
@ECHO OFF
TASKKILL NOTEPAD
START "" "C:\Program Files\Windows NT\Accessories\wordpad.exe"
:LOOP
tasklist | find /i "WORDPAD" >nul 2>&1
IF ERRORLEVEL 1 (
GOTO CONTINUE
) ELSE (
ECHO Wordpad is still running
Timeout /T 5 /Nobreak
GOTO LOOP
)
:CONTINUE
NOTEPAD
All others answers are related to jQuery UI datepicker
, but the question is about bootstrap-datepicker
.
You can use the on changeDate
event to trigger a change event on the related input, and then handle both ways of changing the date from the onChange
handler:
changeDate
Fired when the date is changed.
Example:
$('#dp3').datepicker().on('changeDate', function (ev) {
$('#date-daily').change();
});
$('#date-daily').val('0000-00-00');
$('#date-daily').change(function () {
console.log($('#date-daily').val());
});
Here is a working fiddle: http://jsfiddle.net/IrvinDominin/frjhgpn8/
I had a similar problem. I am posting my solution here because I believe it might help one of the commenters.
For me, the obstacle was that the page required a login and then gave me a new URL through javascript. Here is what I had to do:
curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <URL>
Note that j_username
and j_password
is the name of the fields for my website's login form. You will have to open the source of the webpage to see what the 'name' of the username field and the 'name' of the password field is in your case.
After that I go an html file with java script in which the new URL was embedded. After parsing this out just resubmit with the new URL:
curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <NEWURL>
it can also be in your capistrano config (Capfile
):
set :rbenv_ruby, "2.7.1"
You can simply do it like this with an object literal:
function makeGamePlayer(name,totalScore,gamesPlayed) {
return {
name: name,
totalscore: totalScore,
gamesPlayed: gamesPlayed
};
}
Adding to Jim's elaborate answer:
Check the typing
module -- this module supports type hints as specified by PEP 484.
For example, the function below takes and returns values of type str
and is annotated as follows:
def greeting(name: str) -> str:
return 'Hello ' + name
The typing
module also supports:
Why unicode? Because ASCII has just 127 characters. Those from 128 to 255 differ in different countries, that's why there are codepages. So they said lets have up to 1114111 characters. So how do you store the highest codepoint? You'll need to store it using 21 bits, so you'll use a DWORD having 32 bits with 11 bits wasted. So if you use a DWORD to store a unicode character, it is the easiest way because the value in your DWORD matches exactly the codepoint. But DWORD arrays are of course larger than WORD arrays and of course even larger than BYTE arrays. That's why there is not only utf-32, but also utf-16. But utf-16 means a WORD stream, and a WORD has 16 bits so how can the highest codepoint 1114111 fit into a WORD? It cannot! So they put everyything higher than 65535 into a DWORD which they call a surrogate-pair. Such surrogate-pair are two WORDS and can get detected by looking at the first 6 bits. So what about utf-8? It is a byte array or byte stream, but how can the highest codepoint 1114111 fit into a byte? It cannot! Okay, so they put in also a DWORD right? Or possibly a WORD, right? Almost right! They invented utf-8 sequences which means that every codepoint higher than 127 must get encoded into a 2-byte, 3-byte or 4-byte sequence. Wow! But how can we detect such sequences? Well, everything up to 127 is ASCII and is a single byte. What starts with 110 is a two-byte sequence, what starts with 1110 is a three-byte sequence and what starts with 11110 is a four-byte sequence. The remaining bits of these so called "startbytes" belong to the codepoint. Now depending on the sequence, following bytes must follow. A following byte starts with 10, the remaining bits are 6 bits of payload bits and belong to the codepoint. Concatenate the payload bits of the startbyte and the following byte/s and you'll have the codepoint. That's all the magic of utf-8.
just add static keyword at the starting of the function return type.. and then you can access the member function of the class without object:) for ex:
static void Name_pairs::read_names()
{
cout << "Enter name: ";
cin >> name;
names.push_back(name);
cout << endl;
}
I know this is an old post, but for anyone using Retrofit, this can be useful useful.
If you are using Retrofit + Jackson + Kotlin + Data classes, you need:
implement group: 'com.fasterxml.jackson.module', name: 'jackson-module-kotlin', version: '2.7.1-2'
to your dependencies, so that Jackson can de-serialize into Data classes val jsonMapper = com.fasterxml.jackson.module.kotlin.jacksonObjectMapper()
val retrofit = Retrofit.Builder()
...
.addConverterFactory(JacksonConverterFactory.create(jsonMapper))
.build()
Note: If Retrofit is not being used, @Jayson Minard has a more general approach answer.
There is no such thing as "SOAP protocol". SOAP is an XML schema.
It usually runs over HTTP (port 80), however.
try:
SELECT COUNT(*) FROM USER_TABLES;
Well i dont have oracle on my machine, i run mysql (OP comment)
at the time of writing, this site was great for testing on a variety of database types.
Transparent background will help you see what behind the element, in this case what behind your td
is in fact the parent table. So we have no way to achieve what you want using pure CSS. Even using script can't solve it in a direct way. We can just have a workaround using script based on the idea of using the same background for both the body and the td
. However we have to update the background-position
accordingly whenver the window is resized. Here is the code you can use with the default background position of body
(which is left top
, otherwise you have to change the code to update the background-position
of the td
correctly):
HTML:
<table id = "MainTable">
<tr>
<td width = "20%"></td>
<td width = "80%" id='test'>
<table>
<tr><td>something interesting here</td></tr>
<tr><td>another thing also interesting out there</td></tr>
</table>
</td>
</tr>
</table>
CSS:
/* use the same background for the td #test and the body */
#test {
padding:40px;
background:url('http://placekitten.com/800/500');
}
body {
background:url('http://placekitten.com/800/500');
}
JS (better use jQuery):
//code placed in onload event handler
function updateBackgroundPos(){
var pos = $('#test').offset();
$('#test').css('background-position',
-pos.left + 'px' + " " + (-pos.top + 'px'));
};
updateBackgroundPos();
$(window).resize(updateBackgroundPos);
Try resizing the viewport, you'll see the background-position
updated correctly, which will make an effect looking like the background of the td
is transparent to the body.
var mapped = _.reduce({ one: 1, two: 2, three: 3 }, function(obj, val, key) {_x000D_
obj[key] = val*3;_x000D_
return obj;_x000D_
}, {});_x000D_
_x000D_
console.log(mapped);
_x000D_
<script src="http://underscorejs.org/underscore-min.js"></script>_x000D_
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
_x000D_
// Another simple example
var a = 11;
a == 10 ? alert("true") : alert("false");
It is possible to use setOnKeyListener
. In this method, we can customize the input edittext
!
It's a bit late but I think your issue may be that you've created a zero-length array, rather than an array of length 1.
A string is a series of characters followed by a string terminator ('\0'
). An empty string (""
) consists of no characters followed by a single string terminator character - i.e. one character in total.
So I would try the following:
string[1] = ""
Note that this behaviour is not the emulated by strlen
, which does not count the terminator as part of the string length.
It's impossible to draw a line on screen that's thinner than one pixel. Try using a more subtle color for the border instead.
I created extension methods with a property that retrieves the connection string from configuration. This lets the callers not have to know anything about the connection, whether it's open or closed, etc. This method does limit you a bit since you're hiding some of the Dapper functionality, but in our fairly simple app it's worked fine for us, and if we needed more functionality from Dapper we could always add a new extension method that exposes it.
internal static string ConnectionString = new Configuration().ConnectionString;
internal static IEnumerable<T> Query<T>(string sql, object param = null)
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
return conn.Query<T>(sql, param);
}
}
internal static int Execute(string sql, object param = null)
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
return conn.Execute(sql, param);
}
}
You can use advanced string formatting, available in Python 2.6 and Python 3.x:
incoming = 'arbit'
result = '{0} hello world {0} hello world {0}'.format(incoming)
Sorry to dig up an old question but in case someone stumbles onto this thread and wants a quicker solution.
Bulk inserting a unknown width file with \n row terminators into a temp table that is created outside of the EXEC statement.
DECLARE @SQL VARCHAR(8000)
IF OBJECT_ID('TempDB..#BulkInsert') IS NOT NULL
BEGIN
DROP TABLE #BulkInsert
END
CREATE TABLE #BulkInsert
(
Line VARCHAR(MAX)
)
SET @SQL = 'BULK INSERT #BulkInser FROM ''##FILEPATH##'' WITH (ROWTERMINATOR = ''\n'')'
EXEC (@SQL)
SELECT * FROM #BulkInsert
Further support that dynamic SQL within an EXEC statement has access to temp tables outside of the EXEC statement. http://sqlfiddle.com/#!3/d41d8/19343
DECLARE @SQL VARCHAR(8000)
IF OBJECT_ID('TempDB..#BulkInsert') IS NOT NULL
BEGIN
DROP TABLE #BulkInsert
END
CREATE TABLE #BulkInsert
(
Line VARCHAR(MAX)
)
INSERT INTO #BulkInsert
(
Line
)
SELECT 1
UNION SELECT 2
UNION SELECT 3
SET @SQL = 'SELECT * FROM #BulkInsert'
EXEC (@SQL)
Further support, written for MSSQL2000 http://technet.microsoft.com/en-us/library/aa175921(v=sql.80).aspx
Example at the bottom of the link
DECLARE @cmd VARCHAR(1000), @ExecError INT
CREATE TABLE #ErrFile (ExecError INT)
SET @cmd = 'EXEC GetTableCount ' +
'''pubs.dbo.authors''' +
'INSERT #ErrFile VALUES(@@ERROR)'
EXEC(@cmd)
SET @ExecError = (SELECT * FROM #ErrFile)
SELECT @ExecError AS '@@ERROR'
Seems to work too...
let regex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
func validate(email: String) -> Bool {
let matches = email.rangeOfString(regex, options: .RegularExpressionSearch)
if let _ = matches {
return true
}
return false
}
The construction is usually used in "existence" checks
if exists(select 1 from customer_table where customer = 'xxx')
or
if exists(select * from customer_table where customer = 'xxx')
Both constructions are equivalent. In the past people said the select * was better because the query governor would then use the best indexed column. This has been proven not true.
Read these tutorials Asp.net Update Panel and Introduction to the UpdatePanel Control
Simple and understandable
In Galileo and Helios Provisioning Platform were introduced, and non-update-site plugins now should be placed in "dropins" subfolder ("eclipse/dropins/plugin_name/features", "eclipse/dropins/plugin_name/plugins") instead of Eclipse's folder ("eclipse/features" and "eclipse/plugins").
Also for programming needs the best Eclipse is the latest Eclipse. It has too many bugs for now, and all the Eclipse team is now doing is fixing the bugs. There are very few interface enhancements since Europa. IMHO.
If you don't really need the button element, just move the classes to a regular link:
<div class="btn-group">
<a href="/save/1" class="btn btn-primary active">
<i class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></i> Save
</a>
<a href="/cancel/1" class="btn btn-default">Cancel</a>
</div>
Conversely, you can also change a button to appear like a link:
<button type="button" class="btn btn-link">Link</button>
Mongodb user management:
roles list:
read
readWrite
dbAdmin
userAdmin
clusterAdmin
readAnyDatabase
readWriteAnyDatabase
userAdminAnyDatabase
dbAdminAnyDatabase
create user:
db.createUser(user, writeConcern)
db.createUser({ user: "user",
pwd: "pass",
roles: [
{ role: "read", db: "database" }
]
})
update user:
db.updateUser("user",{
roles: [
{ role: "readWrite", db: "database" }
]
})
drop user:
db.removeUser("user")
or
db.dropUser("user")
view users:
db.getUsers();
more information: https://docs.mongodb.com/manual/reference/security/#read
Simply do this:
import * as importedConfig from '../config.json';
Then use it like the following:
const config = importedConfig.default;
Well, since an UUID gets added the hyphens (dashes) on toString() we can steal the implementation from Java's own implementation, shorting the byte array to 32 and adjusting the offset.
public static String special() {
UUID uuid = UUID.randomUUID();
return fastUUID(uuid.getLeastSignificantBits(), uuid.getMostSignificantBits());
}
private static String fastUUID(long lsb, long msb) {
byte[] buf = new byte[32];
formatUnsignedLong0(lsb, 4, buf, 20, 12);
formatUnsignedLong0(lsb >>> 48, 4, buf, 16, 4);
formatUnsignedLong0(msb, 4, buf, 12, 4);
formatUnsignedLong0(msb >>> 16, 4, buf, 8, 4);
formatUnsignedLong0(msb >>> 32, 4, buf, 0, 8);
return new String(buf, 0);
}
private static final char[] digits = {
'0' , '1' , '2' , '3' , '4' , '5' ,
'6' , '7' , '8' , '9' , 'a' , 'b' ,
'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
'o' , 'p' , 'q' , 'r' , 's' , 't' ,
'u' , 'v' , 'w' , 'x' , 'y' , 'z'
};
private static void formatUnsignedLong0(long val, int shift, byte[] buf, int offset, int len) {
int charPos = offset + len;
int radix = 1 << shift;
int mask = radix - 1;
do {
buf[--charPos] = (byte)digits[((int) val) & mask];
val >>>= shift;
} while (charPos > offset);
}
Running it:
public static void main(String[] args) {
IntStream.range(0, 100).forEach(i-> {
System.out.println(special());
});
}
Generates:
23f57da8a2784bb5acca553030f82e61
a14427efd8d147fdae315c1cf20fc53c
ee972aa1cf85414ca364bef5c74a7e57
6877ef35eab94b9485c5dd7c8c5a8a56
578721476629422381c0f625e22564a8
dbf60f068b5443d7bc6e5280696fed9f
dd611e870700480d81d394dd2125316c
04d71b9379ef4db49c28e113485ea76d
fd4e8cf3f85a45ae8c1b9bfe3e489a4a
858c4e8297f849b784b65b6096dec4d4
b30a8ca318a349b486b5693814422555
351c2fab9bc1426fa3bb512484628f12
9ce59e01db38405aab82d46f2a236880
5ffb5acb547a4f15a4621b406391bc0d
541b5fba8ddb4f1ebbd59cdcd5f59f7c
77f9460c4baa43a7bbaaf7f2aff205bd
85fa5254305b4c72b1b7c0103aaee269
062d45aa86694b06aad841236b839341
7a265293560f4223ab8248fda502c89b
b748c13ac45747b99aead4b0a2d7d179
cbcbf623c75d407fa3c88cfc89a90ed4
da263eed8771496faebb6290527f77fa
22231088dec04cffa40fb79ff56c6453
594a66de4b874b3491649c5d033917f6
4f6802ebd0cc4a39b25a67191c3af09d
8878b7ab8aa445cdadbef0f7c70d3deb
2c3ed0154f0c4ddbad498b7ae928b9bc
cac1dcaa80e54e2db3248987d2dbda4a
f9a3567e6dd54bf5900444c8b1c03815
f0d25d7b615a4495b51c01ab15093a88
243e45926311437c8b26cede2dc7de25
e4738c50e4cd448fbac252571c0907df
261d3593cc054569bcd645885d22c2ee
64a4796356a04cc4a09506aeb6f5b8fd
9aeebcbdde074ed69738589ca9bde0f1
ec040c956861466b84ed7f7cec601be0
18bd233781e44e7cb152800db4c4edc7
1b7b251df1244e8db46a45c186aada2b
3e32f644c9074cb3bbb15c5be1d9b95e
625309e3ffd14a90bfbd6d48142ac60e
664f0cf347ce4767add576da584526e7
fe3893fd376849fe9fed00e328e61470
254ce1441bbf4a7eae1cdf8d288e61e8
90896c6b309a49f48cc3b7a1570e1846
5f47acd1319245648098c1aec9b95f23
f798033052614b9eae8da7eba4ba3475
3471c4320e4e431eb1fa9f5eb5cb21e0
855f473fed034b1fa17f4f65b850e03b
1245de826d0d4373bdd4cf2157792954
543a8b16efca4fa2b5263315e8b21660
2dc186d699274257922853d783c0ec13
a92e6b1783db4b49a4aaa424b9e1b03f
16773feb48054cf0942a2a27204b3572
1e58da2107ac4ee39e28a93b32e1df1d
67622c19498d4178a1bab6b19087f2c2
412b6b4474fc43ccbeb1e7707b6420ee
7d0fd632913c425eb5f087600ccea870
439687baddb44852a43048b04d38427c
8b2dcc4e50464429a18b11e4aacf51a2
2fccb1c832894fe6b0b61bbdf175cd39
6d224b3d6e8747319fcf01b0309d8a0f
b4982e3b4b594cb4b334c95c2c96355e
c47fbaf90d1d4e9caf211f93b742631f
9440271e8ba6447d9a008e89a93016a6
8d24274b6a3f436a88362438aa6a221d
60452bd3f71747ed8c3706abb2235bd5
6fa93f2ee30740b89496439dd7227a4f
cc17504cf80641f882c8665ae166ba44
743efe8eac6e47a789928da4fb5b6f70
4c4d2df3461448c4a3e934cf4a7ea74f
b231eb3fb46240d38157764e8906aa7b
a234ae65f7ed48f6b1887644eed36cc2
c9cd5ed3df3f4a27957b45498f0c48ef
3eb2fbbb0a714bb7986aef3ee34f0254
d15968e605f0440c9e740e3f4e498a9f
63a8d50e8db24b91a13d4ac2fb6f7d5b
5377df9296154c57926672ca8b3c9478
a4db4a3a9d5148648a23aa7f4f77f1e0
d0aee355a2ba42de89d659385514b0fa
e92e7702481a4575a66d59c061459c5b
1b6c542d8f994d85a1312ab2cf4545ce
88e347a515474ec59013673e5402b97f
2187d9b2dc2b4d96baceade5ae99db44
4d641e69ca5b4acf90f8afe238d8a940
9c0f4c101c434831b928114c5fc0c401
140e16f6cf134785a98ae9baee5b9e7b
4dac5910f4d047e1b213c058e2230bf3
fb50a7e6333f49e4b469234426d5002f
c96c5f2fa167458eaa6d01997d90a980
1e79721e587c4a92aa55cdf8195c8c55
0da27fc5d8384ce299197b4e06cda1d4
a5e32d9cf5834e86b3fe02bc0e3104d6
2dc1826647594b1fb728de67d3df363c
0276371815254198bd22cc76f901b332
bf9d77b7b4a64e7a97ade2a62af1f8e0
268cce3249f64895b6b47e86cf296e5b
d523201fc950435f803bf89d5f042c45
607a4306b90b467f8b19c2c943bc92ef
adfa9fb63a874ca1ad746ff573f03f28
fe88132c70d141e8839ce9e7f0308750
Should be just as efficient (more effecient) than Javas actually.
I often do this:
C#:
public string CatStrings(string p1) {return p1;}
public string CatStrings(string p1, int p2) {return p1+p2.ToString();}
public string CatStrings(string p1, int p2, bool p3) {return p1+p2.ToString()+p3.ToString();}
CatStrings("one"); // result = one
CatStrings("one",2); // result = one2
CatStrings("one",2,true); // result = one2true
JavaScript Equivalent:
function CatStrings(p1, p2, p3)
{
var s = p1;
if(typeof p2 !== "undefined") {s += p2;}
if(typeof p3 !== "undefined") {s += p3;}
return s;
};
CatStrings("one"); // result = one
CatStrings("one",2); // result = one2
CatStrings("one",2,true); // result = one2true
This particular example is actually more elegant in javascript than C#. Parameters which are not specified are 'undefined' in javascript, which evaluates to false in an if statement. However, the function definition does not convey the information that p2 and p3 are optional. If you need a lot of overloading, jQuery has decided to use an object as the parameter, for example, jQuery.ajax(options). I agree with them that this is the most powerful and clearly documentable approach to overloading, but I rarely need more than one or two quick optional parameters.
EDIT: changed IF test per Ian's suggestion
To be able to call notify() you need to synchronize on the same object.
synchronized (someObject) {
someObject.wait();
}
/* different thread / object */
synchronized (someObject) {
someObject.notify();
}
Something like this:
class Class {
// visibility will default to private unless you specify it
struct Struct {
//specify members here;
};
};
Suppose you bound your combobox to a List<Person>
List<Person> pp = new List<Person>();
pp.Add(new Person() {id = 1, name="Steve"});
pp.Add(new Person() {id = 2, name="Mark"});
pp.Add(new Person() {id = 3, name="Charles"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
At this point you cannot set the Text property as you like, but instead you need to add an item to your list before setting the datasource
pp.Insert(0, new Person() {id=-1, name="--SELECT--"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
cbo1.SelectedIndex = 0;
Of course this means that you need to add a checking code when you try to use the info from the combobox
if(cbo1.SelectedValue != null && Convert.ToInt32(cbo1.SelectedValue) == -1)
MessageBox.Show("Please select a person name");
else
......
The code is the same if you use a DataTable instead of a list. You need to add a fake row at the first position of the Rows collection of the datatable and set the initial index of the combobox to make things clear. The only thing you need to look at are the name of the datatable columns and which columns should contain a non null value before adding the row to the collection
In a table with three columns like ID, FirstName, LastName with ID,FirstName and LastName required you need to
DataRow row = datatable.NewRow();
row["ID"] = -1;
row["FirstName"] = "--Select--";
row["LastName"] = "FakeAddress";
dataTable.Rows.InsertAt(row, 0);
This only works in situations where you have a numeric field, but you can put a minus sign in front of the field name like so:
reportingNameGroups = reportingNameGroups.OrderBy(x=> - x.GroupNodeId);
However this works a little bit different than OrderByDescending
when you have are running it on an int?
or double?
or decimal?
fields.
What will happen is on OrderByDescending
the nulls will be at the end, vs with this method the nulls will be at the beginning. Which is useful if you want to shuffle nulls around without splitting data into pieces and splicing it later.
<script type="text/javascript">
$(function() {
$("#datepicker").datepicker({
onSelect: function(value, date) {
window.location = 'day.jsp' ;
}
});
});
</script>
<div id="datepicker"></div>
I think you can try this .It works fine .
Implement custom adapter for your class:
public class MyClassAdapter extends ArrayAdapter<MyClass> {
private static class ViewHolder {
private TextView itemView;
}
public MyClassAdapter(Context context, int textViewResourceId, ArrayList<MyClass> items) {
super(context, textViewResourceId, items);
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(this.getContext())
.inflate(R.layout.listview_association, parent, false);
viewHolder = new ViewHolder();
viewHolder.itemView = (TextView) convertView.findViewById(R.id.ItemView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
MyClass item = getItem(position);
if (item!= null) {
// My layout has only one TextView
// do whatever you want with your string and long
viewHolder.itemView.setText(String.format("%s %d", item.reason, item.long_val));
}
return convertView;
}
}
For those not very familiar with the Android framework, this is explained in better detail here: https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView.
Well.. arrays are useful to pass as constants (if they were) as variants parameters.
There are probably embedded tabs (CHAR(9)
) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:
DECLARE @var NVARCHAR(255), @i INT;
SET @i = 1;
SELECT @var = AccountType FROM dbo.Account
WHERE AccountNumber = 200
AND AccountType LIKE '%Daily%';
CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));
WHILE @i <= LEN(@var)
BEGIN
INSERT #x
SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));
SET @i = @i + 1;
END
SELECT i,c,a FROM #x ORDER BY i;
You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.
Alternative: Stream.concat()
Stream.concat(map.values().stream(), listContainer.lst.stream())
.collect(Collectors.toList()
You can make a background
occupying all the screen size transparent
and listen to the onClick
event to dismiss
it.
I would use filter
:
str_list = filter(None, str_list)
str_list = filter(bool, str_list)
str_list = filter(len, str_list)
str_list = filter(lambda item: item, str_list)
Python 3 returns an iterator from filter
, so should be wrapped in a call to list()
str_list = list(filter(None, str_list))
You can get the total number of rows containing a specific name using:
SELECT COUNT(*) FROM tbl_foo WHERE name = 'sarmen'
Given the count, you can now get the nth row using:
SELECT * FROM tbl_foo WHERE name = 'sarmen' LIMIT (n - 1), 1
Where 1 <= n <= COUNT(*) from the first query.
Example:
getting the 3rd row
SELECT * FROM tbl_foo WHERE name = 'sarmen' LIMIT 2, 1
Along the same lines as some of the suggestions you would need to do at least the following:
An example CSS could be as simple as this:
@media print {
body * {
display:none;
}
body .printable {
display:block;
}
}
Your JavaScript would then only need to apply the "printable" class to your target div and it will be the only thing visible (as long as there are no other conflicting CSS rules -- a separate exercise) when printing happens.
<script type="text/javascript">
function divPrint() {
// Some logic determines which div should be printed...
// This example uses div3.
$("#div3").addClass("printable");
window.print();
}
</script>
You may want to optionally remove the class from the target after printing has occurred, and / or remove the dynamically-added CSS after printing has occurred.
Below is a full working example, the only difference is that the print CSS is not loaded dynamically. If you want it to really be unobtrusive then you will need to load the CSS dynamically like in this answer.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Print Portion Example</title>
<style type="text/css">
@media print {
body * {
display:none;
}
body .printable {
display:block;
}
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<h1>Print Section Example</h1>
<div id="div1">Div 1</div>
<div id="div2">Div 2</div>
<div id="div3">Div 3</div>
<div id="div4">Div 4</div>
<div id="div5">Div 5</div>
<div id="div6">Div 6</div>
<p><input id="btnSubmit" type="submit" value="Print" onclick="divPrint();" /></p>
<script type="text/javascript">
function divPrint() {
// Some logic determines which div should be printed...
// This example uses div3.
$("#div3").addClass("printable");
window.print();
}
</script>
</body>
</html>
Please use view.getLocationOnScreen(int[] location);
(see Javadocs). The answer is in the integer array (x = location[0]
and y = location[1]
).
We got this error because we forgot to multiply by sizeof(int). Note the argument to malloc(..) is a number of bytes, not number of machine words or whatever.
If you think of import
as just syntax sugar for Node.js modules, objects, and destructuring, I find it's pretty intuitive.
// bar.js
module = {};
module.exports = {
functionA: () => {},
functionB: ()=> {}
};
// Really all that is is this:
var module = {
exports: {
functionA, functionB
}
};
// Then, over in foo.js
// The whole exported object:
var fump = require('./bar.js'); //= { functionA, functionB }
// Or
import fump from './bar' // The same thing - object functionA and functionB properties
// Just one property of the object
var fump = require('./bar.js').functionA;
// Same as this, right?
var fump = { functionA, functionB }.functionA;
// And if we use ES6 destructuring:
var { functionA } = { functionA, functionB };
// We get same result
// So, in import syntax:
import { functionA } from './bar';
Add toString()
method to your address
class then do
System.out.println(Arrays.toString(houseAddress));
Sometimes the switch variable can also make that error for example:
switch(view.getTag()) {//which is an Object type
case 0://will give compiler error that says Constant expression required
//...
}
To solve you should cast the variable to int(in this case). So:
switch((int)view.getTag()) {//will be int
case 0: //No Error
//...
}
JavaScript that allows for syntax checking
JSHint-Eclipse
and autosuggestions for .js files in Eclipse?
http://www.nodeclipse.org/updates/anide/
As Nodeclipse lead, I am always looking for what is available in Eclipse ecosystem. Nodeclipse site has even more links, and I am inviting to collaborate on the JavaScript tools on GitHub
1.question answer-In your mobile having Developer Option in settings and enable that one. after In android studio project source file in bin--> apk file .just copy the apk file and paste in mobile memory in ur pc.. after all finished .you click that apk file in your mobile is automatically installed.
2.question answer-Your mobile is Samsung are just add Samsung Kies software in your pc..its helps to android code run in your mobile ...
Normally yes, .gitignore
is useful for everyone who wants to work with the repository. On occasion you'll want to ignore more private things (maybe you often create LOG
or something. In those cases you probably don't want to force that on anyone else.
You can't use delete
to remove an item from an array. This is only used to remove a property from an object.
You should use splice to remove an element from an array:
deleteMsg(msg:string) {
const index: number = this.data.indexOf(msg);
if (index !== -1) {
this.data.splice(index, 1);
}
}
I wouldn't push regular code into an exception block. Just check whether any rows exist that meet your condition, and proceed from there:
declare
any_rows_found number;
begin
select count(*)
into any_rows_found
from my_table
where rownum = 1 and
... other conditions ...
if any_rows_found = 1 then
...
else
...
end if;
Use \x
Example from postgres manual:
postgres=# \x
postgres=# SELECT * FROM pg_stat_statements ORDER BY total_time DESC LIMIT 3;
-[ RECORD 1 ]------------------------------------------------------------
userid | 10
dbid | 63781
query | UPDATE branches SET bbalance = bbalance + $1 WHERE bid = $2;
calls | 3000
total_time | 20.716706
rows | 3000
-[ RECORD 2 ]------------------------------------------------------------
userid | 10
dbid | 63781
query | UPDATE tellers SET tbalance = tbalance + $1 WHERE tid = $2;
calls | 3000
total_time | 17.1107649999999
rows | 3000
-[ RECORD 3 ]------------------------------------------------------------
userid | 10
dbid | 63781
query | UPDATE accounts SET abalance = abalance + $1 WHERE aid = $2;
calls | 3000
total_time | 0.645601
rows | 3000
mimetype headers are recognised by the browser for the purpose of a (fast) possible identifying a handler to use the downloaded file as target, for example, PDF would be downloaded and your Adobe Reader program would be executed with the path of the PDF file as an argument,
If your needs are to write a browser extension to handle your downloaded file, through your operation-system, or you simply want to make you project a more 'professional looking' go ahead and select a unique mimetype for you to use, it would make no difference since the operation-system would have no handle to open it with (some browsers has few bundled-plugins, for example new Google Chrome versions has a built-in PDF-reader),
if you want to make sure the file would be downloaded have a look at this answer: https://stackoverflow.com/a/34758866/257319
if you want to make your file type especially organised, it might be worth adding a few letters in the first few bytes of the file, for example, every JPG has this at it's file start:
if you can afford a jump of 4 or 8 bytes it could be very helpful for you in the rest of the way
:)
QR codes have three parameters: Datatype, size (number of 'pixels') and error correction level. How much information can be stored there also depends on these parameters. For example the lower the error correction level, the more information that can be stored, but the harder the code is to recognize for readers.
The maximum size and the lowest error correction give the following values:
Numeric only Max. 7,089 characters
Alphanumeric Max. 4,296 characters
Binary/byte Max. 2,953 characters (8-bit bytes)
I would recommend using Offset
assuming that the Headers are in Row 1. See this example
Option Explicit
Sub Sample()
Dim rRange As Range, filRange As Range, Rng as Range
'Remove any filters
ActiveSheet.AutoFilterMode = False
'~~> Set your range
Set rRange = Sheets("Sheet1").Range("A1:E10")
With rRange
'~~> Set your criteria and filter
.AutoFilter Field:=1, Criteria1:="=1"
'~~> Filter, offset(to exclude headers)
Set filRange = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
Debug.Print filRange.Address
For Each Rng In filRange
'~~> Your Code
Next
End With
'Remove any filters
ActiveSheet.AutoFilterMode = False
End Sub
Another way of doing this would be using Aggregation. You should be able to achieve a similar result using a single query. Such as this:
Item.objects.values("contest").annotate(Count("id"))
I did not test this specific query, but this should output a count of the items for each value in contests as a dictionary.
You can't as most of the posts are explaining, let me add another area:
On many websites you will find people saying that the way to avoid this is using a different AppDomain so if this happens the domain will be unloaded. That is absolutely wrong (unless you host your CLR) as the default behavior of the CLR will raise a KillProcess event, bringing down your default AppDomain.
It is actually 53 binary places, which translates to 15 stable decimal places, meaning that if you round a start out with a number with 15 decimal places, convert it to a double
, and then round the double
back to 15 decimal places you'll get the same number. To uniquely represent a double
you need 17 decimal places (meaning that for every number with 17 decimal places, there's a unique closest double
) which is why 17 places are showing up, but not all 17-decimal numbers map to different double
values (like in the examples in the other answers).
In case, like me, none of the above worked for you, I figured out a very stupid solution.
I'm using a HTC One X on a 2011 Macbook Pro. I just disabled NFC in Settings > Wireless & Networks > More > NFC and viola! Working normally.
[^,;]+
You haven't specified the regex implementation you are using. Most of them have a Split
method that takes delimiters and split by them. You might want to use that one with a "normal" (without ^
) character class:
[,;]+
Got it myself, it's a bit kludgy but it works:
substr(dirname($_SERVER['SCRIPT_NAME']), 0, strrpos(dirname($_SERVER['SCRIPT_NAME']), '/') + 1)
So if I have /path/to/folder/index.php
, this results in /path/to/
.
exec is shelling to the operating system, and unless the OS has some special way of knowing how to execute a file, then it's going to default to treating it as a shell script or similar. In this case, it has no idea how to run your php file. If this script absolutely has to be executed from a shell, then either execute php passing the filename as a parameter, e.g
exec ('/usr/local/bin/php -f /opt/lampp/htdocs/.../name.php)') ;
or use the punct at the top of your php script
#!/usr/local/bin/php
<?php ... ?>
If you can create a numbers table, that contains numbers from 1 to the maximum fields to split, you could use a solution like this:
select
tablename.id,
SUBSTRING_INDEX(SUBSTRING_INDEX(tablename.name, ',', numbers.n), ',', -1) name
from
numbers inner join tablename
on CHAR_LENGTH(tablename.name)
-CHAR_LENGTH(REPLACE(tablename.name, ',', ''))>=numbers.n-1
order by
id, n
Please see fiddle here.
If you cannot create a table, then a solution can be this:
select
tablename.id,
SUBSTRING_INDEX(SUBSTRING_INDEX(tablename.name, ',', numbers.n), ',', -1) name
from
(select 1 n union all
select 2 union all select 3 union all
select 4 union all select 5) numbers INNER JOIN tablename
on CHAR_LENGTH(tablename.name)
-CHAR_LENGTH(REPLACE(tablename.name, ',', ''))>=numbers.n-1
order by
id, n
an example fiddle is here.
You can use the datepicker's onSelect
event.
$(".date").datepicker({
onSelect: function(dateText) {
console.log("Selected date: " + dateText + "; input's current value: " + this.value);
}
});
Live example:
$(".date")_x000D_
.datepicker({_x000D_
onSelect: function(dateText) {_x000D_
console.log("Selected date: " + dateText + "; input's current value: " + this.value);_x000D_
}_x000D_
})_x000D_
.on("change", function() {_x000D_
console.log("Got change event from field");_x000D_
});
_x000D_
<link href="http://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />_x000D_
<input type='text' class='date'>_x000D_
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>_x000D_
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
_x000D_
Unfortunately, onSelect
fires whenever a date is selected, even if it hasn't changed. This is a design flaw in the datepicker: It always fires onSelect
(even if nothing changed), and doesn't fire any event on the underlying input on change. (If you look in the code of that example, we're listening for changes, but they aren't being raised.) It should probably fire an event on the input when things change (possibly the usual change
event, or possibly a datepicker-specific one).
If you like, of course, you can make the change
event on the input
fire:
$(".date").datepicker({
onSelect: function() {
$(this).change();
}
});
That will fire change
on the underlying input
for any handler hooked up via jQuery. But again, it always fires it. If you want to only fire on a real change, you'll have to save the previous value (possibly via data
) and compare.
Live example:
$(".date")_x000D_
.datepicker({_x000D_
onSelect: function(dateText) {_x000D_
console.log("Selected date: " + dateText + "; input's current value: " + this.value);_x000D_
$(this).change();_x000D_
}_x000D_
})_x000D_
.on("change", function() {_x000D_
console.log("Got change event from field");_x000D_
});
_x000D_
<link href="http://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />_x000D_
<input type='text' class='date'>_x000D_
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>_x000D_
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
_x000D_
I often use trigger ('change') to make it work
$('#selectBox option:eq(position_index)').prop('selected', true).trigger('change');
Example with id select = selectA1 and position_index = 0 (frist option in select):
$('#selectA1 option:eq(0)').prop('selected', true).trigger('change');
I had a table change and it created another entity with a number 1 at the end (such as MyEntity1
and a MyEntity
) as confirmed by the edmx model browser. Something about the two entities together confused the processing.
Removal of the table and re-adding it fixed it.
Note that if TFS is hooked up, then do a check-in of the edmx in after the delete. Then and only then get the latest and re-add it in a definite two step process. Otherwise TFS gets confused with the delete and re-add of same named entity(ies) which seems to cause problems.
You do not have to use sc.textFile(...) to convert local files into dataframes. One of options is, to read a local file line by line and then transform it into Spark Dataset. Here is an example for Windows machine in Java:
StructType schemata = DataTypes.createStructType(
new StructField[]{
createStructField("COL1", StringType, false),
createStructField("COL2", StringType, false),
...
}
);
String separator = ";";
String filePath = "C:\\work\\myProj\\myFile.csv";
SparkContext sparkContext = new SparkContext(new SparkConf().setAppName("MyApp").setMaster("local"));
JavaSparkContext jsc = new JavaSparkContext (sparkContext );
SQLContext sqlContext = SQLContext.getOrCreate(sparkContext );
List<String[]> result = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
String[] vals = line.split(separator);
result.add(vals);
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
throw new RuntimeException(ex);
}
JavaRDD<String[]> jRdd = jsc.parallelize(result);
JavaRDD<Row> jRowRdd = jRdd .map(RowFactory::create);
Dataset<Row> data = sqlContext.createDataFrame(jRowRdd, schemata);
Now you can use dataframe data
in your code.
This might be because you are using two method for inserting data into database and this cause the site to slow down.
def add_subscriber(request, email=None):
if request.method == 'POST':
email = request.POST['email_field']
e = Subscriber.objects.create(email=email).save() <====
return HttpResponseRedirect('/')
else:
return HttpResponseRedirect('/')
In above function, the error is where arrow is pointing. The correct implementation is below:
def add_subscriber(request, email=None):
if request.method == 'POST':
email = request.POST['email_field']
e = Subscriber.objects.create(email=email)
return HttpResponseRedirect('/')
else:
return HttpResponseRedirect('/')
I had the exact same problem you describe above (Galaxy Nexus on t-mobile USA) it is because mobile data is turned off.
In Jelly Bean it is: Settings > Data Usage > mobile data
Note that I have to have mobile data turned on PRIOR to sending an MMS OR receiving one. If I receive an MMS with mobile data turned off, I will get the notification of a new message and I will receive the message with a download button. But if I do not have mobile data on prior, the incoming MMS attachment will not be received. Even if I turn it on after the message was received.
For some reason when your phone provider enables you with the ability to send and receive MMS you must have the Mobile Data enabled, even if you are using Wifi, if the Mobile Data is enabled you will be able to receive and send MMS, even if Wifi is showing as your internet on your device.
It is a real pain, as if you do not have it on, the message can hang a lot, even when turning on Mobile Data, and might require a reboot of the device.
Dawid Ferenczy's answer is pretty complete but after I tried almost all of his options I've found that the Chocolatey’s cyg-get was the best (at least the only one that I could get to work).
I was wanting to install wget
, the steps was this:
choco install cyg-get
Then:
cyg-get wget
df <- data.frame(x=rnorm(10), y=rnorm(10))
rownames(df) <- letters[1:10]
df[c('a','b'),]
You need to have a server running on port 8080 when you run the code above that simply returns the request back through the response. Copy the code below to a separate file (say 'server.js') and start this server using the node command (node server.js). You can then separately run your code above (node app.js) from a separate command line.
var http = require('http');
http.createServer(function(request, response){
//The following code will print out the incoming request text
request.pipe(response);
}).listen(8080, '127.0.0.1');
console.log('Listening on port 8080...');
My problem was actually a problem of bad planning with the JSON object rather than an actual logic issue. What I ended up doing was organize the object as follows, per a suggestion from user2736012.
{
"dialog":
{
"trunks":[
{
"trunk_id" : "1",
"message": "This is just a JSON Test"
},
{
"trunk_id" : "2",
"message": "This is a test of a bit longer text. Hopefully this will at the very least create 3 lines and trigger us to go on to another box. So we can test multi-box functionality, too."
}
]
}
}
At that point, I was able to do a fairly simple for loop based on the total number of objects.
var totalMessages = Object.keys(messages.dialog.trunks).length;
for ( var i = 0; i < totalMessages; i++)
{
console.log("ID: " + messages.dialog.trunks[i].trunk_id + " Message " + messages.dialog.trunks[i].message);
}
My method for getting totalMessages is not supported in all browsers, though. For my project, it actually doesn't matter, but beware of that if you choose to use something similar to this.
You can use sort() function. sort() exists in algorithm header file
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
string str = "sharlock";
sort(str.begin(), str.end());
cout<<str<<endl;
return 0;
}
Output:
achklors
Having had a similar itch to scratch (altough only for some files of a given repository) this script proved to be really helpful: git-import
The short version is that it creates patch files of the given file or directory ($object
) from the existing repository:
cd old_repo
git format-patch --thread -o "$temp" --root -- "$object"
which then get applied to a new repository:
cd new_repo
git am "$temp"/*.patch
For details please look up:
Write a:hover::before
instead of a::before:hover
: example.
Try to remove any trace of cocoapods pods using pod deintegrate
then
Run pod install
You can use lapply
to pass each column to str_length
, then cbind
it to your original data.frame
...
library(stringr)
out <- lapply( df , str_length )
df <- cbind( df , out )
# col1 col2 col1 col2
#1 abc adf qqwe 3 8
#2 abcd d 4 1
#3 a e 1 1
#4 abcdefg f 7 1
Model.select(:rating).distinct
DataFrame.compare
With pandas 1.1, you could essentially replicate Ted Petrou's output with a single function call. Example taken from the docs:
pd.__version__
# '1.1.0'
df1.compare(df2)
score isEnrolled Comment
self other self other self other
1 1.11 1.21 NaN NaN NaN NaN
2 NaN NaN 1.0 0.0 NaN On vacation
Here, "self" refers to the LHS dataFrame, while "other" is the RHS DataFrame. By default, equal values are replaced with NaNs so you can focus on just the diffs. If you want to show values that are equal as well, use
df1.compare(df2, keep_equal=True, keep_shape=True)
score isEnrolled Comment
self other self other self other
1 1.11 1.21 False False Graduated Graduated
2 4.12 4.12 True False NaN On vacation
You can also change the axis of comparison using align_axis
:
df1.compare(df2, align_axis='index')
score isEnrolled Comment
1 self 1.11 NaN NaN
other 1.21 NaN NaN
2 self NaN 1.0 NaN
other NaN 0.0 On vacation
This compares values row-wise, instead of column-wise.
You can change color of button text using this code:
alertC.view.tintColor = your color;
Maybe this will help you.
It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.
Let's say you have something like this in your code:
$str = "test";
echo($str{0});
since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:
$str = "test";
echo($str[0]);
Fixing the code in the question will look something like this:
public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
$records = $this->listRecords($zoneID, $type, $name);
if (isset($records->result[0]->id)) {
return $records->result[0]->id;
}
return false;
}
Try using input type="tel"
instead. It pops up a keyboard with numbers, and it doesn’t show spin boxes. It requires no JavaScript or CSS or plugins or anything else.
Try Destructuring
const a = {};
const { b } = a;
const emptryOrNot = (b) ? 'not Empty' : 'empty';
console.log(emptryOrNot)
The following constructor, JLabel(String, int)
, allow you to specify the horizontal alignment of the label.
JLabel label = new JLabel("The Label", SwingConstants.CENTER);
if you open localhost/phpmyadmin
you will find a tab called "User accounts". There you can define all your users that can access the mysql database, set their rights and even limit from where they can connect.
Adding to what @KyleMit said, consider using:
col-md-*
classes for the larger outer columnscol-xs-*
classes for the smaller inner columnsThis will be useful when you view the page on different screen sizes.
On a small screen, the wrapping of larger outer columns will then happen while maintaining the smaller inner columns, if possible
See my UPDATE at the end, before reading the following answer.
I have windows 8 and another pc with windows 8.1
I had License error saying "Prerelease software. License expired".
The only solution that I found which is inspired by the above solutions (Thanks!) was to run process monitor and see the exact registry keys that are accessed when I start the VS2013 which were:
HKCR\Licenses\E79B3F9C-6543-4897-BBA5-5BFB0A02BB5C
like what are mentioned in the previous posts. However the process monitor said that this registry is access denied.
So I opened regedit and found that registry key and I could not open it. It says I have no permission to see it.
SO I had to change its permission:
I found that this registry key has several sub keys, however you have to restart regedit to see them.
By seeing which other registry keys are access denied in process monitor , I knew that VS2013 will specifically deal with these subkeys which are ACCESS DENIED also: 06181 0bcad
and these subkeys should be changed their permissions as well like above.
After making these permission changes everything worked well.
The same thing has been done to Microsoft visual studio 2010 because an error in the license as well and the solution worked well.
UPDATE : It turned out that starting visual studio as administrator solved this issue without this registry massage. Seems that this happened to my pc after changing the 'required password to login' removed in the user settings. (I wanted to let the pc start running without any password after restart from a crash or anything else). This made a lot of programs not able to write into some folders like temp folders unless I start the application as admin. Even printing from excel would not work, if excel is not started as admin.
public Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}
It is because you set the width:100%
which by definition only spans the width of the screen. You want to set the min-width:100%
which sets it to the width of the screen... with the ability to grow beyond that.
Also make sure you set min-width:100%
for body
and html
.
check this out.. it's not perfect but it works and it's for IE only and doesn't affect FF. I used the regular javascript for onmousedown to establish IE only fix.. but the msie from jquery could be used as well in the onmousedown.. the main idea is the "onchange" and on blur to have the select box return to normal... decide you're own width for those. I needed 35%.
onmousedown="javascript:if(navigator.appName=='Microsoft Internet Explorer'){this.style.width='auto'}"
onchange="this.style.width='35%'"
onblur="this.style.width='35%'"
A HandlerInterceptor gives you more fine-grained control than a filter, because you have access to the actual target "handler" - this means that whatever action you perform can vary depending on what the request is actually doing (whereas the servlet filter is generically applied to all requests - only able to take into account the parameters of each request). The handlerInterceptor also provides 3 different methods, so that you can apply behavior prior to calling a handler, after the handler has completed but prior to view rendering (where you may even bypass view rendering altogether), or after the view itself has been rendered. Also, you can set up different interceptors for different groups of handlers - the interceptors are configured on the handlerMapping, and there may be multiple handlerMappings.
Therefore, if you have a need to do something completely generic (e.g. log all requests), then a filter is sufficient - but if the behavior depends on the target handler or you want to do something between the request handling and view rendering, then the HandlerInterceptor provides that flexibility.
Reference: http://static.springframework.org/sp...ng-interceptor
size param increases the hits displayed from from the default(10) to 500.
http://localhost:9200/[indexName]/_search?pretty=true&size=500&q=*:*
Change the from step by step to get all the data.
http://localhost:9200/[indexName]/_search?size=500&from=0
In Windows 10, I solved this problem with the Windows Credential Manager. I found multiple credentials for the NAS unit that I was having trouble with. After deleting both credentials, I was able to access the NAS mapped network drives without a problem.
A ViewGroup describes the layout of the Views in its group. The two basic examples of ViewGroups are LinearLayout and RelativeLayout. Breaking LinearLayout even further, you can have either Vertical LinearLayout or Horizontal LinearLayout. If you choose Vertical LinearLayout, your Views will stack vertically on your screen. The two most basic examples of Views are TextView and Button. Thus, if you have a ViewGroup of Vertical LinearLayout, your Views (e.g. TextViews and Buttons) would line up vertically down your screen.
When the other posters show nested ViewGroups, what they mean is, for example, one of the rows in my Vertical LinearLayout might actually, at the lower level, be several items arranged horizontally. In that case, I'd have a Horizontal LinearLayout as one of the children of my top level Vertical LinearLayout.
Example of Nested ViewGroups:
Parent ViewGroup = Vertical LinearLayout
Row1: TextView1
Row2: Button1
Row3: Image TextView2 Button2 <-- Horizontal Linear nested in Vertical Linear
Row4: TextView3
Row5: Button3
You can use:
SET PASSWORD FOR 'root' = PASSWORD('elephant7');
or, in latest versions:
SET PASSWORD FOR root = 'elephant7'
You can also use:
UPDATE user SET password=password('elephant7') WHERE user='root';
but in Mysql 5.7 the field password is no more there, and you have to use:
UPDATE user SET authentication_string=password('elephant7') WHERE user='root';
Regards
The best way to do this is disable it with webserver apache2. In my Ubuntu 14.X - open /etc/apache2/apache2.conf
change from
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
to
<Directory /var/www/>
Options FollowSymLinks
AllowOverride None
Require all granted
</Directory>
then restart apache by:
sudo service apache2 reload
This will disable directory listing from all folder that apache2 serves.
Another possible usage of Object.create is to clone immutable objects in a cheap and effective way.
var anObj = {
a: "test",
b: "jest"
};
var bObj = Object.create(anObj);
bObj.b = "gone"; // replace an existing (by masking prototype)
bObj.c = "brand"; // add a new to demonstrate it is actually a new obj
// now bObj is {a: test, b: gone, c: brand}
Notes: The above snippet creates a clone of an source object (aka not a reference, as in cObj = aObj). It benefits over the copy-properties method (see 1), in that it does not copy object member properties. Rather it creates another -destination- object with it's prototype set on the source object. Moreover when properties are modified on the dest object, they are created "on the fly", masking the prototype's (src's) properties.This constitutes a fast an effective way of cloning immutable objects.
The caveat here is that this applies to source objects that should not be modified after creation (immutable). If the source object is modified after creation, all the clone's unmasked properties will be modified, too.
Fiddle here(http://jsfiddle.net/y5b5q/1/) (needs Object.create capable browser).
You can combine the check and cast into one statement:
let touch = object.anyObject() as UITouch
if let picker = touch.view as? UIPickerView {
...
}
Then you can use picker
within the if
block.
You can also use COALESCE ( expression [ ,...n ] ) - returns first non-null like:
SELECT COALESCE(MAX(X),0) AS MaxX
FROM tbl
WHERE XID = 1
Select * from TableName Where ColumnName LIKE '%[^A-Za-z0-9, ]%'
This will give you all the row which contains any special character.
This is not a definitive answer, but it may shed some light on the causes of a TransactionTooLargeException
and help pinpoint the problem.
Although most answers refer to large amounts of data transferred, I see this exception being thrown incidentally after heavy scrolling and zooming and repeatedly opening an ActionBar spinner menu. The crash happens on tapping the action bar. (this is a custom mapping app)
The only data being passed around seem to be touches from the "Input Dispatcher" to the app. I think this cannot reasonably amount to anywhere near 1 mb in the "Transaction Buffer".
My app is running on a quad core 1.6 GHz device and uses 3 threads for heavylifting, keeping one core free for the UI thread. Furthermore, the app uses android:largeHeap, has 10 mb of unused heap left and has 100 mb of room left to grow the heap. So I wouldn't say it is a resource issue.
The crash is always immediately preceded by these lines:
W/InputDispatcher( 2271): channel ~ Consumer closed input channel or an error occurred. events=0x9
E/InputDispatcher( 2271): channel ~ Channel is unrecoverably broken and will be disposed!
E/JavaBinder(28182): !!! FAILED BINDER TRANSACTION !!!
Which are not neccesarily printed in that order, but (as far as I checked) happen on the same millisecond.
And the stack trace itself, for clarity, is the same as in the question:
E/AndroidRuntime(28182): java.lang.RuntimeException: Adding window failed
..
E/AndroidRuntime(28182): Caused by: android.os.TransactionTooLargeException
Delving into the source code of android one finds these lines:
frameworks/base/core/jni/android_util_Binder.cpp:
case FAILED_TRANSACTION:
ALOGE("!!! FAILED BINDER TRANSACTION !!!");
// TransactionTooLargeException is a checked exception, only throw from certain methods.
// FIXME: Transaction too large is the most common reason for FAILED_TRANSACTION
// but it is not the only one. The Binder driver can return BR_FAILED_REPLY
// for other reasons also, such as if the transaction is malformed or
// refers to an FD that has been closed. We should change the driver
// to enable us to distinguish these cases in the future.
jniThrowException(env, canThrowRemoteException
? "android/os/TransactionTooLargeException"
: "java/lang/RuntimeException", NULL);
To me it sounds like I'm possibly hitting this undocumented feature, where the transaction fails for other reasons than a Transaction being TooLarge. They should have named it TransactionTooLargeOrAnotherReasonException
.
At this time I did not solve the issue, but if I find something useful I will update this answer.
update: it turned out my code leaked some file descriptors, the number of which is maximized in linux (typically 1024), and this seems to have triggered the exception. So it was a resource issue after all. I verified this by opening /dev/zero
1024 times, which resulted in all kinds of weird exceptions in UI related actions, including the exception above, and even some SIGSEGV's. Apparently failure to open a file/socket is not something which is handled/reported very cleanly throughout Android.
The following works for me:
Map<String, String> propertyMap = getJsonAsMap(json);
where getJsonAsMap
is defined like so:
public HashMap<String, String> getJsonAsMap(String json)
{
try
{
ObjectMapper mapper = new ObjectMapper();
TypeReference<Map<String,String>> typeRef = new TypeReference<Map<String,String>>() {};
HashMap<String, String> result = mapper.readValue(json, typeRef);
return result;
}
catch (Exception e)
{
throw new RuntimeException("Couldnt parse json:" + json, e);
}
}
Note that this will fail if you have child objects in your json (because they're not a String
, they're another HashMap
), but will work if your json is a key value list of properties like so:
{
"client_id": "my super id",
"exp": 1481918304,
"iat": "1450382274",
"url": "http://www.example.com"
}
Use awk(another great bash utility) instead of grep where you dont have the line buffered option! It will continuously stream your data from tail.
this is how you use grep
tail -f <file> | grep pattern
This is how you would use awk
tail -f <file> | awk '/pattern/{print $0}'
I realize this is an old question, but it took me several hours to find a good solution and thought I'd pass on what I learned here and save someone else the trouble. Try, for example,
SELECT * FROM some_table WHERE id_column = ANY(@id_list)
where @id_list is bound to an int[] parameter by way of
command.Parameters.Add("@id_list", NpgsqlDbType.Array | NpgsqlDbType.Integer).Value = my_id_list;
where command is a NpgsqlCommand (using C# and Npgsql in Visual Studio).
You can use the HttpWebRequest class to do so.
Example here:
using System;
using System.Net;
using System.Text;
using System.IO;
public class Test
{
// Specify the URL to receive the request.
public static void Main (string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (args[0]);
// Set some reasonable limits on resources used by this request
request.MaximumAutomaticRedirections = 4;
request.MaximumResponseHeadersLength = 4;
// Set credentials to use for this request.
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
Console.WriteLine ("Content length is {0}", response.ContentLength);
Console.WriteLine ("Content type is {0}", response.ContentType);
// Get the stream associated with the response.
Stream receiveStream = response.GetResponseStream ();
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);
Console.WriteLine ("Response stream received.");
Console.WriteLine (readStream.ReadToEnd ());
response.Close ();
readStream.Close ();
}
}
/*
The output from this example will vary depending on the value passed into Main
but will be similar to the following:
Content length is 1542
Content type is text/html; charset=utf-8
Response stream received.
<html>
...
</html>
*/
To edit:
crontab -e
Add this command line:
30 2 * * * /your/command
MIN HOUR DOM MON DOW CMD
MIN Minute field 0 to 59
HOUR Hour field 0 to 23
DOM Day of Month 1-31
MON Month field 1-12
DOW Day Of Week 0-6
CMD Command Any command to be executed.
Restart cron with latest data:
service crond restart
I don't know of anyway to step through the execution of a .bat file but you can use echo
and pause
to help with debugging.
ECHO
Will echo a message in the batch file. Such as ECHO Hello World will print Hello World on the screen when executed. However, without @ECHO OFF at the beginning of the batch file you'll also get "ECHO Hello World" and "Hello World." Finally, if you'd just like to create a blank line, type ECHO. adding the period at the end creates an empty line.PAUSE
Prompt the user to press any key to continue.
Source: Batch File Help
@workmad3: answer has more good tips for working with the echo
command.
Another helpful resource... DDB: DOS Batch File Tips
Got it working for a compile file('...')
conflict by increasing minSdkVersion to 21 and enabling multidex. Not sure if that is the best solution but the only way I could get it working in my case.
Note: for compile file('...')
it appears that you cannot put in an exclude
clause so that option was not available.
I saw so much complexes answer, so this is my code. Working here. You can achieve this in two ways.
1) Stardard android compatiblity
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.NavUtils;
import android.view.MenuItem;
import android.view.View;
public class EditDiscoveryActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_discovery);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/*toolbar.setNavigationIcon(R.drawable.ic_arrow_white_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});*/
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
2) Use a custom icon
If you want to use code in comments you just have to add this file in drawable, called ic_arrow_white_24dp.xml
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#ffffff"
android:pathData="M20,11H7.83l5.59,-5.59L12,4l-8,8 8,8 1.41,-1.41L7.83,13H20v-2z"/>
</vector>
With this code.
toolbar.setNavigationIcon(R.drawable.ic_arrow_white_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
Hope it will helps some people here !
Arrays in C++ are very different from those in Java in that they are completely unmanaged. The compiler or run-time have no idea whatsoever what size the array is.
The information is only known at compile-time if the size is defined in the declaration:
char array[256];
In this case, sizeof(array) gives you the proper size.
If you use a pointer as an array however, the "array" will just be a pointer, and sizeof will not give you any information about the actual size of the array.
STL offers a lot of templates that allow you to have arrays, some of them with size information, some of them with variable sizes, and most of them with good accessors and bounds checking.
Here's how you can mock your FileConnection
Mock<IFileConnection> fileConnection = new Mock<IFileConnection>(
MockBehavior.Strict);
fileConnection.Setup(item => item.Get(It.IsAny<string>,It.IsAny<string>))
.Throws(new IOException());
Then instantiate your Transfer class and use the mock in your method call
Transfer transfer = new Transfer();
transfer.GetFile(fileConnection.Object, someRemoteFilename, someLocalFileName);
Update:
First of all you have to mock your dependencies only, not the class you are testing(Transfer class in this case). Stating those dependencies in your constructor make it easy to see what services your class needs to work. It also makes it possible to replace them with fakes when you are writing your unit tests. At the moment it's impossible to replace those properties with fakes.
Since you are setting those properties using another dependency, I would write it like this:
public class Transfer
{
public Transfer(IInternalConfig internalConfig)
{
source = internalConfig.GetFileConnection("source");
destination = internalConfig.GetFileConnection("destination");
}
//you should consider making these private or protected fields
public virtual IFileConnection source { get; set; }
public virtual IFileConnection destination { get; set; }
public virtual void GetFile(IFileConnection connection,
string remoteFilename, string localFilename)
{
connection.Get(remoteFilename, localFilename);
}
public virtual void PutFile(IFileConnection connection,
string localFilename, string remoteFilename)
{
connection.Get(remoteFilename, localFilename);
}
public virtual void TransferFiles(string sourceName, string destName)
{
var tempName = Path.GetTempFileName();
GetFile(source, sourceName, tempName);
PutFile(destination, tempName, destName);
}
}
This way you can mock internalConfig and make it return IFileConnection mocks that does what you want.
I think I might have figured this out on Windows. You can run different versions of Chrome at the same time!
Do the following:
Copy over the version number directory into the usual c:\users\yourUser\appdata\local\google\chrome\application directory (I am assuming you had a backup of the older chrome version directory before the update occurred)
Copy over the chrome.exe from the older version as a new name such as chrome_custom.exe
Run chrome as chrome_custom.exe --chrome-version=olderVersion --user-data-dir=newDir
That's it! I use this method to run automated test on Chrome with Selenium, until selenium catches up and works well with the latest Chrome.
For all the Kotlin developers out there:
Here is the Android Studio proposed solution to send data to your Fragment (= when you create a Blank-Fragment with File -> New -> Fragment -> Fragment(Blank) and you check "include fragment factory methods").
Put this in your Fragment:
class MyFragment: Fragment {
...
companion object {
@JvmStatic
fun newInstance(isMyBoolean: Boolean) = MyFragment().apply {
arguments = Bundle().apply {
putBoolean("REPLACE WITH A STRING CONSTANT", isMyBoolean)
}
}
}
}
.apply
is a nice trick to set data when an object is created, or as they state here:
Calls the specified function [block] with
this
value as its receiver and returnsthis
value.
Then in your Activity or Fragment do:
val fragment = MyFragment.newInstance(false)
... // transaction stuff happening here
and read the Arguments in your Fragment such as:
private var isMyBoolean = false
override fun onAttach(context: Context?) {
super.onAttach(context)
arguments?.getBoolean("REPLACE WITH A STRING CONSTANT")?.let {
isMyBoolean = it
}
}
To "send" data back to your Activity, simply define a function in your Activity and do the following in your Fragment:
(activity as? YourActivityClass)?.callYourFunctionLikeThis(date) // your function will not be called if your Activity is null or is a different Class
Enjoy the magic of Kotlin!
Sometimes if it is a new server you need to configure or install ASP.NET feature on IIS for it to be able to read your web.config file.
In my case this was the reason.
One option would be to reduce
the keys()
:
var o = {
a: {value:1},
b: {value:2},
c: {value:3}
};
Object.keys(o).reduce(function (previous, key) {
return previous + o[key].value;
}, 0);
With this, you'll want to specify an initial value or the 1st round will be 'a' + 2
.
If you want the result as an Object ({ value: ... }
), you'll have to initialize and return the object each time:
Object.keys(o).reduce(function (previous, key) {
previous.value += o[key].value;
return previous;
}, { value: 0 });
Make sure angular-cli is installed before trying to create a project. Windows users can install angular-cli without giving permission to command but MAC users have to use sudo before executing the command as follow:
sudo npm install -g angular-cli
Type a password when asked and press enter to proceed.
Not a direct answer to your question.. But following is the only syntax that used to work for me -
data: '{"winNumber": "' + win + '"}',
And the parameter-name match with the argument of the server method
After making no changes to a production server we began receiving this error. After trying several different things and thinking that perhaps there were DNS issues, restarting IIS fixed the issue (restarting only the site did not fix the issue). It likely won't work for everyone but if we tried that first it would have saved a lot of time.
A good example given in book: Practical Python By Magnus Lie Hetland
>>> zip(range(5), xrange(100000000))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
I wouldn’t recommend using range instead of xrange in the preceding example—although only the first five numbers are needed, range calculates all the numbers, and that may take a lot of time. With xrange, this isn’t a problem because it calculates only those numbers needed.
Yes I read @Brian's answer: In python 3, range() is a generator anyway and xrange() does not exist.
You need to download this from Microsoft: http://www.microsoft.com/en-us/download/details.aspx?id=7435.
The tool is called "Microsoft URL Rewrite Module 2.0 for IIS 7" and is described as follows by Microsoft: "URL Rewrite Module 2.0 provides a rule-based rewriting mechanism for changing requested URL’s before they get processed by web server and for modifying response content before it gets served to HTTP clients"
You can simply write
try
{
//Your Logic and code
}
catch (Exception ex)
{
//Error message in alert box
Response.Write("<script>alert('Error :" +ex.Message+"');</script>");
}
it will work fine
For people looking to change status bar for all viewcontrollers on: iOS 11, Swfit 4/5 solution is pretty easy.
1) Info.plist add:
View controller-based status bar appearance -> NO
2) Left side of XCode slect project > Targets > Select your project > Under General > Deployment Info > Select Status Bar Style: Light
If you want to change status bar only for one viewcontroller, on viewDidLoad add:
2.1) Info.plist
View controller-based status bar appearance -> YES
2.2)
override var preferredStatusBarStyle : UIStatusBarStyle {
return .lightContent
}
Objective-C (or react native) changing from App Delegate:
1) Info.plist add:
View controller-based status bar appearance -> NO
2) AppDelegate -> didFinishLaunchingWithOptions
[[UIApplication sharedApplication] setStatusBarHidden:NO animated:YES];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDarkContent animated:YES];
Changing status bar do not work trying to do push(navigation controllers), only on presenting modally viewcontrollers.
This gives you the needed results:
string time = "16:23:01";
var result = Convert.ToDateTime(time);
string test = result.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture);
//This gives you "04:23:01 PM" string
You could also use CultureInfo.CreateSpecificCulture("en-US")
as not all cultures will display AM/PM.
The computed columns make the problem.
Do not use SELECT *
. You must specify each fields after SELECT except computed fields
Don't use NULL
, C++ allows you to use the unadorned 0
instead:
previous = 0;
next = 0;
And, as at C++11, you generally shouldn't be using either NULL
or 0
since it provides you with nullptr
of type std::nullptr_t
, which is better suited to the task.
You can set autoplay=""
<video width="640" height="480" controls="controls" type="video/mp4" autoplay="">
<source src="http://example.com/mytestfile.mp4">
Your browser does not support the video tag.
</video>
ps. for enabling you can use autoplay
or autoplay="autoplay"
int power(int x,int y){
int r=1;
do{
r*=r;
if(y%2)
r*=x;
}while(y>>=1);
return r;
};
(iterative)
int power(int x,int y){
return y?(y%2?x:1)*power(x*x,y>>1):1;
};
(if it has to be recursive)
imo, the algorithm should definitely be O(logn)
If I've understood this right, bootstrap provides a CSS class for just this case. Add 'pull-right' to the menu 'ul':
<ul class="dropdown-menu pull-right">
..and the end result is that the menu options appear right-aligned, in line with the button they drop down from.
I solved this on my machine by just running sudo npm install
in the directory that I was getting the error.