The AWS-provided tools are not useful because they are not comprehensive.
In my own quest to mitigate this problem and pull a list of all of my AWS resources, I found this: https://github.com/JohannesEbke/aws_list_all
I have not tested it yet, but it looks legit.
You can use cv2.rectangle()
:
cv2.rectangle(img, pt1, pt2, color, thickness, lineType, shift)
Draws a simple, thick, or filled up-right rectangle.
The function rectangle draws a rectangle outline or a filled rectangle
whose two opposite corners are pt1 and pt2.
Parameters
img Image.
pt1 Vertex of the rectangle.
pt2 Vertex of the rectangle opposite to pt1 .
color Rectangle color or brightness (grayscale image).
thickness Thickness of lines that make up the rectangle. Negative values,
like CV_FILLED , mean that the function has to draw a filled rectangle.
lineType Type of the line. See the line description.
shift Number of fractional bits in the point coordinates.
I have a PIL Image object and I want to draw rectangle on this image, but PIL's ImageDraw.rectangle() method does not have the ability to specify line width. I need to convert Image object to opencv2's image format and draw rectangle and convert back to Image object. Here is how I do it:
# im is a PIL Image object
im_arr = np.asarray(im)
# convert rgb array to opencv's bgr format
im_arr_bgr = cv2.cvtColor(im_arr, cv2.COLOR_RGB2BGR)
# pts1 and pts2 are the upper left and bottom right coordinates of the rectangle
cv2.rectangle(im_arr_bgr, pts1, pts2,
color=(0, 255, 0), thickness=3)
im_arr = cv2.cvtColor(im_arr_bgr, cv2.COLOR_BGR2RGB)
# convert back to Image object
im = Image.fromarray(im_arr)
You can try this method that is developed by Chucai Yi and Yingli Tian.
They also share a software (which is based on Opencv-1.0 and it should run under Windows platform.) that you can use (though no source code available). It will generate all the text bounding boxes (shown in color shadows) in the image. By applying to your sample images, you will get the following results:
Note: to make the result more robust, you can further merge adjacent boxes together.
Update: If your ultimate goal is to recognize the texts in the image, you can further check out gttext, which is an OCR free software and Ground Truthing tool for Color Images with Text. Source code is also available.
With this, you can get recognized texts like:
This is an implementation of aforementioned StanLe's anwer, also fixing the case where his answer would produce no curve when using densities.
This replaces the existing but hidden hist.default()
function, to only add the normalcurve
parameter (which defaults to TRUE
).
The first three lines are to support roxygen2 for package building.
#' @noRd
#' @exportMethod hist.default
#' @export
hist.default <- function(x,
breaks = "Sturges",
freq = NULL,
include.lowest = TRUE,
normalcurve = TRUE,
right = TRUE,
density = NULL,
angle = 45,
col = NULL,
border = NULL,
main = paste("Histogram of", xname),
ylim = NULL,
xlab = xname,
ylab = NULL,
axes = TRUE,
plot = TRUE,
labels = FALSE,
warn.unused = TRUE,
...) {
# https://stackoverflow.com/a/20078645/4575331
xname <- paste(deparse(substitute(x), 500), collapse = "\n")
suppressWarnings(
h <- graphics::hist.default(
x = x,
breaks = breaks,
freq = freq,
include.lowest = include.lowest,
right = right,
density = density,
angle = angle,
col = col,
border = border,
main = main,
ylim = ylim,
xlab = xlab,
ylab = ylab,
axes = axes,
plot = plot,
labels = labels,
warn.unused = warn.unused,
...
)
)
if (normalcurve == TRUE & plot == TRUE) {
x <- x[!is.na(x)]
xfit <- seq(min(x), max(x), length = 40)
yfit <- dnorm(xfit, mean = mean(x), sd = sd(x))
if (isTRUE(freq) | (is.null(freq) & is.null(density))) {
yfit <- yfit * diff(h$mids[1:2]) * length(x)
}
lines(xfit, yfit, col = "black", lwd = 2)
}
if (plot == TRUE) {
invisible(h)
} else {
h
}
}
Quick example:
hist(g)
For dates it's bit different. For reference:
#' @noRd
#' @exportMethod hist.Date
#' @export
hist.Date <- function(x,
breaks = "months",
format = "%b",
normalcurve = TRUE,
xlab = xname,
plot = TRUE,
freq = NULL,
density = NULL,
start.on.monday = TRUE,
right = TRUE,
...) {
# https://stackoverflow.com/a/20078645/4575331
xname <- paste(deparse(substitute(x), 500), collapse = "\n")
suppressWarnings(
h <- graphics:::hist.Date(
x = x,
breaks = breaks,
format = format,
freq = freq,
density = density,
start.on.monday = start.on.monday,
right = right,
xlab = xlab,
plot = plot,
...
)
)
if (normalcurve == TRUE & plot == TRUE) {
x <- x[!is.na(x)]
xfit <- seq(min(x), max(x), length = 40)
yfit <- dnorm(xfit, mean = mean(x), sd = sd(x))
if (isTRUE(freq) | (is.null(freq) & is.null(density))) {
yfit <- as.double(yfit) * diff(h$mids[1:2]) * length(x)
}
lines(xfit, yfit, col = "black", lwd = 2)
}
if (plot == TRUE) {
invisible(h)
} else {
h
}
}
/*link*/
$q.when(scope.regions).then(function(result) {
console.log(result);
});
var Regions = $resource('mocks/regions.json');
$scope.regions = Regions.query().$promise.then(function(response) {
return response;
});
This error happens very rarely on my Windows machine. I ended up rebooting the machine, and the error went away.
According to w3.org the value attribute of the number input is defined as a floating-point number. The syntax of the floating-point number seems to only accept dots as decimal separators.
I've listed a few options below that might be helpful to you:
With the pattern attribute you can specify the allowed format with a regular expression in a HTML5 compatible way. Here you could specify that the comma character is allowed and a helpful feedback message if the pattern fails.
<input type="number" pattern="[0-9]+([,\.][0-9]+)?" name="my-num"
title="The number input must start with a number and use either comma or a dot as a decimal character."/>
Note: Cross-browser support varies a lot. It may be complete, partial or non-existant..
You could try to bind a simple callback to for example the onchange (and/or blur) event that would either replace the comma or validate all together.
Thirdly you could try to use the formnovalidate attribute on the number inputs with the intention of disabling browser validation for that field all together.
<input type="number" formnovalidate />
<input type="number" pattern="[0-9]+([,\.][0-9]+)?"
name="my-num" formnovalidate
title="The number input must start with a number and use either comma or a dot as a decimal character."/>
Line width in ggplot2
can be changed with argument lwd=
in geom_line()
.
geom_line(aes(x=..., y=..., color=...), lwd=1.5)
I use the old PHP way..It unsets all session variables and doesn't require to specify each one of them in an array. And after unsetting the variables we destroy the session
For collapse, you can try CTRL + M + O and expand using CTRL + M + P. This works in VS2008.
What you first tried should work, but the HTML is not what we would expect. I added an option to handle the initial "no item selected" case:
<select ng-options="region.code as region.name for region in regions" ng-model="region">
<option style="display:none" value="">select a region</option>
</select>
<br>selected: {{region}}
The above generates this HTML:
<select ng-options="..." ng-model="region" class="...">
<option style="display:none" value class>select a region</option>
<option value="0">Alabama</option>
<option value="1">Alaska</option>
<option value="2">American Samoa</option>
</select>
Even though Angular uses numeric integers for the value, the model (i.e., $scope.region) will be set to AL, AK, or AS, as desired. (The numeric value is used by Angular to lookup the correct array entry when an option is selected from the list.)
This may be confusing when first learning how Angular implements its "select" directive.
I suggest using this method :
public static int GetNumberOfDecimalPlaces(decimal value, int maxNumber)
{
if (maxNumber == 0)
return 0;
if (maxNumber > 28)
maxNumber = 28;
bool isEqual = false;
int placeCount = maxNumber;
while (placeCount > 0)
{
decimal vl = Math.Round(value, placeCount - 1);
decimal vh = Math.Round(value, placeCount);
isEqual = (vl == vh);
if (isEqual == false)
break;
placeCount--;
}
return Math.Min(placeCount, maxNumber);
}
Define an Outlet:
@IBOutlet weak var pickerView: UIPickerView! // for example
Then in your viewWillAppear or your viewDidLoad, for example, you can use the following:
pickerView.selectRow(rowMin, inComponent: 0, animated: true)
pickerView.selectRow(rowSec, inComponent: 1, animated: true)
If you inspect the Swift 2.0 framework you'll see .selectRow
defined as:
func selectRow(row: Int, inComponent component: Int, animated: Bool)
option clicking .selectRow in Xcode displays the following:
For some reason Candide's answer didn't build. It was helpful, though, as it led me to find this, which worked perfectly:
System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke((Action)(() =>
{
//your code here...
}));
It sounds indeed like video streaming more than image streaming, as someone suggested. JPEG/PNG compression isn't targeted for these types of speeds, so forget them.
Imagine having a recording codec on your system that can realtime record an incoming video stream (your screen). A bit like Fraps perhaps. Then imagine a video playback codec on the other side (the remote client). As HD recorders can do it (record live and even playback live from the same HD), so should you, in the end. The HD surely can't deliver images quicker than you can read your display, so that isn't the bottleneck. The bottleneck are the video codecs. You'll find the encoder much more of a problem than the decoder, as all decoders are mostly free.
I'm not saying it's simple; I myself have used DirectShow to encode a video file, and it's not realtime by far. But given the right codec I'm convinced it can work.
Another way of doing this is using nested IF statements. Suppose you have companies table and you want to count number of records in it. A sample query would be something like this
SELECT IF(
count(*) > 15,
'good',
IF(
count(*) > 10,
'average',
'poor'
)
) as data_count
FROM companies
Here second IF condition works when the first IF condition fails. So Sample Syntax of the IF statement would be IF ( CONDITION, THEN, ELSE). Hope it helps someone.
It's not because of a different code, but because of caching: RAM is slower than the CPU registers and a cache memory is inside the CPU to avoid to write the RAM every time a variable is changing. But the cache is not big as the RAM is, hence, it maps only a fraction of it.
The first code modifies distant memory addresses alternating them at each loop, thus requiring continuously to invalidate the cache.
The second code don't alternate: it just flow on adjacent addresses twice. This makes all the job to be completed in the cache, invalidating it only after the second loop starts.
This seems to work for me:
LANG=C grep --only-matching --byte-offset --binary --text --perl-regexp "<\x-hex pattern>" <file>
short form:
LANG=C grep -obUaP "<\x-hex pattern>" <file>
Example:
LANG=C grep -obUaP "\x01\x02" /bin/grep
Output (cygwin binary):
153: <\x01\x02>
33210: <\x01\x02>
53453: <\x01\x02>
So you can grep this again to extract offsets. But don't forget to use binary mode again.
Note: LANG=C
is needed to avoid utf8 encoding issues.
The problem with maintenance info sections
is that command tries to extract information from the section header of the binary. It does not work if the binary is tripped (e.g by sstrip
) or it gives wrong information when the loader may change the memory permission after loading (e.g. the case of RELRO
).
You can use .replaceWith()
$(function() {_x000D_
_x000D_
$(".region").click(function(e) {_x000D_
e.preventDefault();_x000D_
var content = $(this).html();_x000D_
$('#map').replaceWith('<div class="region">' + content + '</div>');_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="map">_x000D_
<div class="region"><a href="link1">region1</a></div>_x000D_
<div class="region"><a href="link2">region2</a></div>_x000D_
<div class="region"><a href="link3">region3</a></div>_x000D_
</div>
_x000D_
Type "ctor" and press the TAB key twice this will add the default constructor automatically
Not out of the box in Sql Server Management Studio, but it is a feature of the very good SSMS Tools Pack
Perhaps you can use something like Gaussian Mixture Models. Here's a Python package for doing GMMs (just did a Google search) http://www.ar.media.kyoto-u.ac.jp/members/david/softwares/em/
As the question is specifically about alternative tools to get data from PDF as XML so you may be interested to take a look at the commercial tool "ByteScout PDF Extractor SDK" that is capable of doing exactly this: extract text from PDF as XML along with the positioning data (x,y) and font information:
Text in the source PDF:
Products | Units | Price
Output XML:
<row>
<column>
<text fontName="Arial" fontSize="11.0" fontStyle="Bold" x="212" y="126" width="47" height="11">Products</text>
</column>
<column>
<text fontName="Arial" fontSize="11.0" fontStyle="Bold" x="428" y="126" width="27" height="11">Units</text>
</column>
<column>
<text fontName="Arial" fontSize="11.0" fontStyle="Bold" x="503" y="126" width="26" height="11">Price</text>
</column>
</row>
P.S.: additionally it also breaks the text into a table based structure.
Disclosure: I work for ByteScout
this should work in T-SQL
ALTER TABLE Countries ADD
HasPhotoInReadyStorage bit,
HasPhotoInWorkStorage bit,
HasPhotoInMaterialStorage bit,
HasText bit GO
http://msdn.microsoft.com/en-us/library/ms190273(SQL.90).aspx
Contrary to what most are posting, this is NOT an IDE thing. It is a language thing. The #region is a C# statement.
On VS 2012 and VS 2015 install WebEssentials plugin and you will able to do so.
Also, if you have two subsequent words in regular text and you want to avoid a line break between them, you can use the ~ character.
For example:
As we can see in Fig.~\ref{BlaBla}, there is nothing interesting to see. A~better place..
This can ensure that you don't have a line starting with a figure number (without the Fig. part) or with an uppercase A.
You can use menu Search -> Replace... (Ctrl + H).
It has a regular expression feature for replacing. You can use a regex that matches #region as well as whatever else is on the line, and replace it with empty space.
This question is old but I wanted to add an alternative to the accepted answer which didn't exist at the time.
Image Mapster is a jQuery plugin that I wrote to solve some of the shortcomings of Map Hilight (and it was initially an extension of that plugin, though it's since been almost completely rewritten). Initially, this was just the ability to maintain selection state for areas, fix browser compatibility problems. Since its initial release a few months ago, though, I have added a lot of features including the ability to use an alternate image as the source for the highlights.
It also has the ability to identify areas as "masks," meaning you can create areas with "holes", and additionally create complex groupings of areas. For example, area A could cause another area B to be highlighted, but area B itself would not respond to mouse events.
There are a few examples on the web site that show most of the features. The github repository also has more examples and complete documentation.
This error can also be caused by having zero methods tagged with the OperationContract attribute. This was my problem when building a new service and testing it a long the way.
I was working on same. Check below statement. Worked for me!!
SELECT * FROM [Schema].[Table] WHERE [Column] LIKE '%' + @Parameter + '%'
USING PURE JAVASCRIPT: I know it's late but may be for the future people it can help:
In the HTML part:
<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>
In the Javascipt Controller:
function reply_click()
{
alert(event.srcElement.id);
}
This way we don't have to bind the 'id' of the Element at the time of calling the javascript function.
Go to your mysql bin directory and install mysql service again:
c:
cd \mysql\bin
mysqld-nt.exe --install
or if mysqld-nt.exe is missing (depending on version):
mysqld.exe --install
Then go to services, start the service and set it to automatic start.
I checked and it worked for me.
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1" style="margin-top:100px;"><!--style with margin-top according to your need-->
<ul class="nav navbar-nav navbar-right">
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
My option was this:
Create a subroutine that takes in the message and automates the process of sending it to both console and log file.
setlocal
set logfile=logfile.log
call :screenandlog "%DATE% %TIME% This message goes to the screen and to the log"
goto :eof
:screenandlog
set message=%~1
echo %message% & echo %message% >> %logfile%
exit /b
If you add a variable to the message, be sure to remove the quotes in it before sending it to the subroutine or it can screw your batch. Of course this only works for echoing.
This works also for any kind of value:
$a = true;
echo $a // outputs: 1
echo value_To_String( $a ) // outputs: true
code:
function valueToString( $value ){
return ( !is_bool( $value ) ? $value : ($value ? 'true' : 'false' ) );
}
Apple recommends for stylistic purposes.If you write this code:
@property (nonatomic,assign) BOOL working;
Then you can not use [object isWorking].
It will show an error. But if you use below code means
@property (assign,getter=isWorking) BOOL working;
So you can use [object isWorking] .
You can try the pipe functionality in sh.py:
import sh
print sh.grep(sh.ps("-ax"), "process_name")
Preface: This comment is intended to address the answer provided by okutane, but because of SO's silly reputation system, I can not post it where it belongs.
Your assertion that one is slower than the other because of the method calls isn't correct. One is slower than the other because of more complicated bounds-checking algorithms. You can easily verify this by looking, not at the IL, but at the compiled assembly. For example, on my 4.5 install, accessing an element (via pointer in edx) stored in a two-dimensional array pointed to by ecx with indexes stored in eax and edx looks like so:
sub eax,[ecx+10]
cmp eax,[ecx+08]
jae oops //jump to throw out of bounds exception
sub edx,[ecx+14]
cmp edx,[ecx+0C]
jae oops //jump to throw out of bounds exception
imul eax,[ecx+0C]
add eax,edx
lea edx,[ecx+eax*4+18]
Here, you can see that there's no overhead from method calls. The bounds checking is just very convoluted thanks to the possibility of non-zero indexes, which is a functionality not on offer with jagged arrays. If we remove the sub,cmp,and jmps for the non-zero cases, the code pretty much resolves to (x*y_max+y)*sizeof(ptr)+sizeof(array_header)
. This calculation is about as fast (one multiply could be replaced by a shift, since that's the whole reason we choose bytes to be sized as powers of two bits) as anything else for random access to an element.
Another complication is that there are plenty of cases where a modern compiler will optimize away the nested bounds-checking for element access while iterating over a single-dimension array. The result is code that basically just advances an index pointer over the contiguous memory of the array. Naive iteration over multi-dimensional arrays generally involves an extra layer of nested logic, so a compiler is less likely to optimize the operation. So, even though the bounds-checking overhead of accessing a single element amortizes out to constant runtime with respect to array dimensions and sizes, a simple test-case to measure the difference may take many times longer to execute.
CSS3 allows this sort of thing and it looks like this:
body {
background-image: url(images/bgtop.png), url(images/bg.png);
background-repeat: repeat-x, repeat;
}
The current versions of all the major browsers now support it, however if you need to support IE8 or below, then the best way you can work around it is to have extra divs:
<body>
<div id="bgTopDiv">
content here
</div>
</body>
body{
background-image: url(images/bg.png);
}
#bgTopDiv{
background-image: url(images/bgTop.png);
background-repeat: repeat-x;
}
Historically, Bourne shells didn't have true
and false
as built-in commands. true
was instead simply aliased to :
, and false
to something like let 0
.
:
is slightly better than true
for portability to ancient Bourne-derived shells. As a simple example, consider having neither the !
pipeline operator nor the ||
list operator (as was the case for some ancient Bourne shells). This leaves the else
clause of the if
statement as the only means for branching based on exit status:
if command; then :; else ...; fi
Since if
requires a non-empty then
clause and comments don't count as non-empty, :
serves as a no-op.
Nowadays (that is: in a modern context) you can usually use either :
or true
. Both are specified by POSIX, and some find true
easier to read. However there is one interesting difference: :
is a so-called POSIX special built-in, whereas true
is a regular built-in.
Special built-ins are required to be built into the shell; Regular built-ins are only "typically" built in, but it isn't strictly guaranteed. There usually shouldn't be a regular program named :
with the function of true
in PATH of most systems.
Probably the most crucial difference is that with special built-ins, any variable set by the built-in - even in the environment during simple command evaluation - persists after the command completes, as demonstrated here using ksh93:
$ unset x; ( x=hi :; echo "$x" )
hi
$ ( x=hi true; echo "$x" )
$
Note that Zsh ignores this requirement, as does GNU Bash except when operating in POSIX compatibility mode, but all other major "POSIX sh derived" shells observe this including dash, ksh93, and mksh.
Another difference is that regular built-ins must be compatible with exec
- demonstrated here using Bash:
$ ( exec : )
-bash: exec: :: not found
$ ( exec true )
$
POSIX also explicitly notes that :
may be faster than true
, though this is of course an implementation-specific detail.
Given the fact that you can switch to origin/master
(though in detached state) while having your network cable unplugged, it must be a local representation of the master
branch at origin
.
I had the similar problem with my Eclipse Helios which debugging Junits. My problem was little different as i was able to run Junits successfully but when i was getting ClassNotFoundException while debugging the same JUNITs.
I have tried all sort of different solutions available in Stackoverflow.com and forums elsewhere, but nothing seem to work. After banging my head with these issue for close to two days, finally i figured out the solution to it.
If none of the solutions seem to work, just delete the .metadata folder created in your workspace. This would create an additional overhead of importing the projects and all sorts of configuration you have done, but these will surely solve these issue.
Hope these helps.
Also, you do not have to use nested CASEs. You can use several WHEN-THEN lines and the ELSE line is also optional eventhough I recomend it
CASE
WHEN [condition.1] THEN [expression.1]
WHEN [condition.2] THEN [expression.2]
...
WHEN [condition.n] THEN [expression.n]
ELSE [expression]
END
Here's an example of applying dropshadow to some svg using the 'filter' property. If you want to control the opacity of the dropshadow have a look at this example. The slope
attribute controls how much opacity to give to the dropshadow.
Relevant bits from the example:
<filter id="dropshadow" height="130%">
<feGaussianBlur in="SourceAlpha" stdDeviation="3"/> <!-- stdDeviation is how much to blur -->
<feOffset dx="2" dy="2" result="offsetblur"/> <!-- how much to offset -->
<feComponentTransfer>
<feFuncA type="linear" slope="0.5"/> <!-- slope is the opacity of the shadow -->
</feComponentTransfer>
<feMerge>
<feMergeNode/> <!-- this contains the offset blurred image -->
<feMergeNode in="SourceGraphic"/> <!-- this contains the element that the filter is applied to -->
</feMerge>
</filter>
<circle r="10" style="filter:url(#dropshadow)"/>
Box-shadow is defined to work on CSS boxes (read: rectangles), while svg is a bit more expressive than just rectangles. Read the SVG Primer to learn a bit more about what you can do with SVG filters.
@Airspeed Velocity answer in Swift 2.0:
let str = "iOS Developer Tips encoded in Base64"
print("Original: \(str)")
let base64Encoded = str.dataUsingEncoding(NSUTF8StringEncoding)!.base64EncodedStringWithOptions([])
print("Encoded: \(base64Encoded)")
let base64DecodedData = NSData(base64EncodedString: base64Encoded, options: [])!
var base64DecodedString = String(data: base64DecodedData, encoding: NSUTF8StringEncoding)!
print("Decoded: \(base64DecodedString)")
For a google maps integration I was looking for a way to detect when a div has changed in size. Since google maps always require proper dimensions e.g. width and height in order to render properly.
The solution I came up with is a delegation of an event, in my case a tab click. This could be a window resize of course, the idea remains the same:
if (parent.is(':visible')) {
w = parent.outerWidth(false);
h = w * mapRatio /*9/16*/;
this.map.css({ width: w, height: h });
} else {
this.map.closest('.tab').one('click', function() {
this.activate();
}.bind(this));
}
this.map
in this case is my map div.
Since my parent is invisible on load, the computed width and height are 0 or don't match.
By using .bind(this)
I can delegate the script execution (this.activate
) to an event (click
).
Now I'm confident the same applies for resize events.
$(window).one('resize', function() {
this.div.css({ /*whatever*/ });
}.bind(this));
Hope it helps anyone!
I have created a simple MySQL procedure as given below:
DELIMITER //
CREATE PROCEDURE GetAllListings()
BEGIN
SELECT nid, type, title FROM node where type = 'lms_listing' order by nid desc;
END //
DELIMITER;
Kindly follow this. After the procedure created, you can see the same and execute it.
No. REST has nothing to do with URI naming conventions. If you include these conventions as part of your API, out-of-band, instead of only via hypertext, then your API is not RESTful.
For more information, see http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
With Swift
let commentImageView = UIImageView(frame: CGRectMake(100, 100, 100, 100))
commentImageView.image = UIImage(named: "myimage.png")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
commentImageView.tintColor = UIColor.blackColor()
addSubview(commentImageView)
Similar to Arnav Rao's, but with a different parent:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="toolbarStyle">@style/MyToolbar</item>
</style>
<style name="MyToolbar" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
<item name="android:background">#ff0000</item>
</style>
With this approach, the appearance of the Toolbar is entirely defined in the app styles, so you don't need to place any styling on each toolbar.
For some reason it's actually affected by the color of the border??? When you use the standard color the corners stay rounded but if you change the color even slightly the rounding goes away.
select.regularcolor {
border-color: rgb(169, 169, 169);
}
select.offcolor {
border-color: rgb(170, 170, 170);
}
Yes. Have a look at Wikipedia and Cloanto Implementation of INI File Format (see bottom of page).
You (as in the process that runs b.php
, either you through CLI
or a webserver) need write access to the directory in which the files are located. You are updating the directory content, so access to the file is not enough.
Note that if you use the PHP chmod()
function to set the mode of a file or folder to 777
you should use 0777
to make sure the number is correctly interpreted as an octal number.
Use simple CSS height: 100%; matches the height of the parent and using height: 100vh matches the height of the viewport.
Use vh instead of %;
You will get useful information from here.
SELECT ticker
INTO quotedb
FROM tickerdb;
In your code you don't get the HttpResponse, so you won't see what the server side sends you back.
you need to get the Response similar to the way you get (make) the Request. So
public static bool SendAnSMSMessage(string message)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.pennysms.com/jsonrpc");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{ \"method\": \"send\", " +
" \"params\": [ " +
" \"IPutAGuidHere\", " +
" \"[email protected]\", " +
" \"MyTenDigitNumberWasHere\", " +
" \"" + message + "\" " +
" ] " +
"}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
return true;
}
}
I also notice in the pennysms documentation that they expect a content type of "text/json" and not "application/json". That may not make a difference, but it's worth trying in case it doesn't work.
pointers(ex:char *arr,int *arr) -------> heap
Nope, they can be on the stack or in the data segment. They can point anywhere.
Well, this one liner might qualify (uses Guava Ranges)
ContiguousSet<Integer> integerList = ContiguousSet.create(Range.closedOpen(0, 10), DiscreteDomain.integers());
System.out.println(integerList);
This doesn't create a List<Integer>
, but ContiguousSet
offers much the same functionality, in particular implementing Iterable<Integer>
which allows foreach
implementation in the same way as List<Integer>
.
In older versions (somewhere before Guava 14) you could use this:
ImmutableList<Integer> integerList = Ranges.closedOpen(0, 10).asSet(DiscreteDomains.integers()).asList();
System.out.println(integerList);
Both produce:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
This should work. You need to put in two slashes
str = str.replaceAll("(\\r\\n|\\n)", "<br />");
In this Reference, there is an example which shows
private final String REGEX = "\\d"; // a single digit
I have used two slashes in many of my projects and it seems to work fine!
It seems to depend on the details of the version of od
. On OSX, use this:
od -t x1 -An file |tr -d '\n '
(That's print as type hex bytes, with no address. And whitespace deleted afterwards, of course.)
Put those properties files in src/test/resources
. Files in src/test/resources
are available within Eclipse automatically via eclipse:eclipse
but will not be included in the packaged JAR by Maven.
None of these worked for me. I'm using Mac OS 10.10.5 and Workbench 6.3. What worked for me is Database->Migration Wizard... Flow the steps very carefully
That's my solution
public class MyObject
{
public string value1 { get; set; }
public string value2 { get; set; }
public PropertyInfo[] GetProperties()
{
try
{
return this.GetType().GetProperties();
}
catch (Exception ex)
{
throw ex;
}
}
public PropertyInfo GetByParameterName(string ParameterName)
{
try
{
return this.GetType().GetProperties().FirstOrDefault(x => x.Name == ParameterName);
}
catch (Exception ex)
{
throw ex;
}
}
public static MyObject SetValue(MyObject obj, string parameterName,object parameterValue)
{
try
{
obj.GetType().GetProperties().FirstOrDefault(x => x.Name == parameterName).SetValue(obj, parameterValue);
return obj;
}
catch (Exception ex)
{
throw ex;
}
}
}
If you have the data sorted.. i suggest using the following formula
=IF(OR(A2<>A3,B2<>B3),1,0)
This is faster as it uses less cells to calculate.
long negativeNumber = (long)positiveInt - (long)(int.MaxValue + 1);
Nobody said it had to be any particular negative number.
Here's my code to find controls by Type while controlling how deep we go into the hierarchy (maxDepth == 0 means infinitely deep).
public static class FrameworkElementExtension
{
public static object[] FindControls(
this FrameworkElement f, Type childType, int maxDepth)
{
return RecursiveFindControls(f, childType, 1, maxDepth);
}
private static object[] RecursiveFindControls(
object o, Type childType, int depth, int maxDepth = 0)
{
List<object> list = new List<object>();
var attrs = o.GetType()
.GetCustomAttributes(typeof(ContentPropertyAttribute), true);
if (attrs != null && attrs.Length > 0)
{
string childrenProperty = (attrs[0] as ContentPropertyAttribute).Name;
foreach (var c in (IEnumerable)o.GetType()
.GetProperty(childrenProperty).GetValue(o, null))
{
if (c.GetType().FullName == childType.FullName)
list.Add(c);
if (maxDepth == 0 || depth < maxDepth)
list.AddRange(RecursiveFindControls(
c, childType, depth + 1, maxDepth));
}
}
return list.ToArray();
}
}
Even if the following proposal should not be considered as a final solution you can achieve the goal by doing something like this:
SET SESSION group_concat_max_len = 1000000;
SET @search = 'Text_To_Search';
DROP table IF EXISTS table1;
CREATE TEMPORARY TABLE table1 AS
(SELECT
CONCAT('SELECT \'',TABLE_NAME,'\' as \'table_name\',\'',COLUMN_NAME,'\' as \'column_name\',CONVERT(count(*),char) as \'matches\' FROM `',
TABLE_NAME,'` where `',COLUMN_NAME,'` like \'%',@search,'%\' UNION ') as 'query'
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'db_name' limit 1000000);
set @query = (SELECT GROUP_CONCAT(t1.`query` SEPARATOR '') as 'final_query' from table1 t1 limit 1);
set @query = (SELECT SUBSTRING(@query, 1, length(@query) - 7));
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Please remember that:
Options: group_concat_max_len and limit 1000000 not always are needed, it will depends of your server/IDE configuration. Just in case I added them.
After executing this you will get a 3 column response: [table_name], [column_name], [matches]
Column 'matches' is the number of occurrences in the given table/column.
This query is very fast.
DISCLAIMER: It would be useful only for personal use, in other words please don't use it in a production system, because it is sensitive to SQL Injection attacks given that the search parameter is concatenated with other strings. If you want to create a prod. ready function, then you will need to create a store procedure with a LOOP.
all your code is okay only the things left is just go to the link https://myaccount.google.com/security
and keep scroll down and you will found Allow less secure apps: ON and keep ON, you will find no error.
Try putting a container div (with overflow:auto) around the content and sidebar.
If that doesn't work, do you have any screenshots or example links where the footer isn't displayed properly?
Since someone mentioned efficiency, I've benchmarked the functions given so far out of curiosity:
function startsWith1($str, $char) {
return strpos($str, $char) === 0;
}
function startsWith2($str, $char) {
return stripos($str, $char) === 0;
}
function startsWith3($str, $char) {
return substr($str, 0, 1) === $char;
}
function startsWith4($str, $char){
return $str[0] === $char;
}
function startsWith5($str, $char){
return (bool) preg_match('/^' . $char . '/', $str);
}
function startsWith6($str, $char) {
if (is_null($encoding)) $encoding = mb_internal_encoding();
return mb_substr($str, 0, mb_strlen($char, $encoding), $encoding) === $char;
}
Here are the results on my average DualCore machine with 100.000 runs each
// Testing '_string'
startsWith1 took 0.385906934738
startsWith2 took 0.457293987274
startsWith3 took 0.412894964218
startsWith4 took 0.366240024567 <-- fastest
startsWith5 took 0.642996072769
startsWith6 took 1.39859509468
// Tested "string"
startsWith1 took 0.384965896606
startsWith2 took 0.445554971695
startsWith3 took 0.42377281189
startsWith4 took 0.373164176941 <-- fastest
startsWith5 took 0.630424022675
startsWith6 took 1.40699005127
// Tested 1000 char random string [a-z0-9]
startsWith1 took 0.430691003799
startsWith2 took 4.447286129
startsWith3 took 0.413349866867
startsWith4 took 0.368592977524 <-- fastest
startsWith5 took 0.627470016479
startsWith6 took 1.40957403183
// Tested 1000 char random string [a-z0-9] with '_' prefix
startsWith1 took 0.384054899216
startsWith2 took 4.41522812843
startsWith3 took 0.408898115158
startsWith4 took 0.363884925842 <-- fastest
startsWith5 took 0.638479948044
startsWith6 took 1.41304707527
As you can see, treating the haystack as array to find out the char at the first position is always the fastest solution. It is also always performing at equal speed, regardless of string length. Using strpos
is faster than substr
for short strings but slower for long strings, when the string does not start with the prefix. The difference is irrelevant though. stripos
is incredibly slow with long strings. preg_match
performs mostly the same regardless of string length, but is only mediocre in speed. The mb_substr
solution performs worst, while probably being more reliable though.
Given that these numbers are for 100.000 runs, it should be obvious that we are talking about 0.0000x seconds per call. Picking one over the other for efficiency is a worthless micro-optimization, unless your app is doing startsWith
checking for a living.
No, it doesn't save you memory.
Also note that you don't have to import Math
at all. Everything in java.lang
is imported automatically.
A better example would be something like an ArrayList
import java.util.ArrayList;
....
ArrayList<String> i = new ArrayList<String>();
Note I'm importing the ArrayList
specifically. I could have done
import java.util.*;
But you generally want to avoid large wildcard imports to avoid the problem of collisions between packages.
It is possible to do what you want by using the syntax for generic methods when declaring your doIt()
method (notice the addition of <T>
between static
and void
in the method signature of doIt()
):
class Clazz<T> {
static <T> void doIt(T object) {
// shake that booty
}
}
I got Eclipse editor to accept the above code without the Cannot make a static reference to the non-static type T
error and then expanded it to the following working program (complete with somewhat age-appropriate cultural reference):
public class Clazz<T> {
static <T> void doIt(T object) {
System.out.println("shake that booty '" + object.getClass().toString()
+ "' !!!");
}
private static class KC {
}
private static class SunshineBand {
}
public static void main(String args[]) {
KC kc = new KC();
SunshineBand sunshineBand = new SunshineBand();
Clazz.doIt(kc);
Clazz.doIt(sunshineBand);
}
}
Which prints these lines to the console when I run it:
shake that booty 'class com.eclipseoptions.datamanager.Clazz$KC' !!!
shake that booty 'class com.eclipseoptions.datamanager.Clazz$SunshineBand' !!!
A technique I use to query the MOST RECENT rows in very large tables (100+ million or 1+ billion rows) is limiting the query to "reading" only the most recent "N" percentage of RECENT ROWS. This is real world applications, for example I do this for non-historic Recent Weather Data, or recent News feed searches or Recent GPS location data point data.
This is a huge performance improvement if you know for certain that your rows are in the most recent TOP 5% of the table for example. Such that even if there are indexes on the Tables, it further limits the possibilites to only 5% of rows in tables which have 100+ million or 1+ billion rows. This is especially the case when Older Data will require Physical Disk reads and not only Logical In Memory reads.
This is well more efficient than SELECT TOP | PERCENT | LIMIT as it does not select the rows, but merely limit the portion of the data to be searched.
DECLARE @RowIdTableA BIGINT
DECLARE @RowIdTableB BIGINT
DECLARE @TopPercent FLOAT
-- Given that there is an Sequential Identity Column
-- Limit query to only rows in the most recent TOP 5% of rows
SET @TopPercent = .05
SELECT @RowIdTableA = (MAX(TableAId) - (MAX(TableAId) * @TopPercent)) FROM TableA
SELECT @RowIdTableB = (MAX(TableBId) - (MAX(TableBId) * @TopPercent)) FROM TableB
SELECT *
FROM TableA a
INNER JOIN TableB b ON a.KeyId = b.KeyId
WHERE a.Id > @RowIdTableA AND b.Id > @RowIdTableB AND
a.SomeOtherCriteria = 'Whatever'
Ah, just needed to find the right name for this: "Lazy property evaluation".
I do this a lot too; maybe I'll use that recipe in my code sometime.
My version
$ sqlplus -s username/password@host:port/service <<< "select 1 from dual;"
1
----------
1
EDIT:
For multiline you can use this
$ echo -e "select 1 from dual; \n select 2 from dual;" | sqlplus -s username/password@host:port/service
1
----------
1
2
----------
2
Add MultipleActiveResultSets=true
to the provider part of your connection string. See the example below:
<add name="DbContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=dbName;Persist Security Info=True;User ID=userName;Password=password;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
.toString()
is available, or just add ""
to the end of the int
var x = 3,
toString = x.toString(),
toConcat = x + "";
Angular is simply JavaScript at the core.
If you can't edit this part of code where your dict was defined you can still order it at any point in any way you want, like this:
from collections import OrderedDict
order_of_keys = ["key1", "key2", "key3", "key4", "key5"]
list_of_tuples = [(key, your_dict[key]) for key in order_of_keys]
your_dict = OrderedDict(list_of_tuples)
Here's the magic you want:
autocomplete="new-password"
Chrome intentionally ignores autocomplete="off"
and autocomplete="false"
. However, they put new-password
in as a special clause to stop new password forms from being auto-filled.
I put the above line in my password input, and now I can edit other fields in my form and the password is not auto-filled.
There is another way to do that without cast:
when(a.method(Matchers.<Class<A>>any())).thenReturn(b);
This solution forces the method any()
to return Class<A>
type and not its default value (Object
).
Installing through distributed JDK DMG from the Oracle site auto-updates everything for me. I have seen (in El Capitan) updating through System Preferences > Java
do updates but that do not reflect to command line. Installing through DMG does the job.
Subtract -2
or -3
basis of removing last space also.
public static void main(String[] args) {
String s = "apple car 05";
System.out.println(s.substring(0, s.length() - 2));
}
Output
apple car
Simply type "node NodeJsProject/app.js"
Your program will run :)
There is no inherent ordering to a table. So, the row number itself is a meaningless metric.
However, you can get the row number of a result set by using the ROWNUM psuedocolumn or the ROW_NUMBER()
analytic function, which is more powerful.
As there is no ordering to a table both require an explicit ORDER BY clause in order to work.
select rownum, a.*
from ( select *
from student
where name like '%ram%'
order by branch
) a
or using the analytic query
select row_number() over ( order by branch ) as rnum, a.*
from student
where name like '%ram%'
Your syntax where name is like ...
is incorrect, there's no need for the IS, so I've removed it.
The ORDER BY here relies on a binary sort, so if a branch starts with anything other than B the results may be different, for instance b
is greater than B
.
A)
String str = "a string";
int length = str.length( ); // length == 8
http://download.oracle.com/javase/7/docs/api/java/lang/String.html#length%28%29
edit
If you want to count the number of a specific type of characters in a String
, then a simple method is to iterate through the String
checking each index against your test case.
int charCount = 0;
char temp;
for( int i = 0; i < str.length( ); i++ )
{
temp = str.charAt( i );
if( temp.TestCase )
charCount++;
}
where TestCase
can be isLetter( )
, isDigit( )
, etc.
Or if you just want to count everything but spaces, then do a check in the if
like temp != ' '
B)
String str = "a string";
char atPos0 = str.charAt( 0 ); // atPos0 == 'a'
http://download.oracle.com/javase/7/docs/api/java/lang/String.html#charAt%28int%29
You are able to choose one that you like, but it has to be unique.
Every time I have to enter the SKU I use the App identifier (e.g. de.mycompany.myappname
) because this is already unique.
It has to do with the version of python that you use. Basically it adopts the C behavior: if you divide two integers, the results will be rounded down to an integer. Also keep in mind that Python does the operations from left to right, which plays a role when you typecast.
Example: Since this is a question that always pops in my head when I am doing arithmetic operations (should I convert to float and which number), an example from that aspect is presented:
>>> a = 1/2/3/4/5/4/3
>>> a
0
When we divide integers, not surprisingly it gets lower rounded.
>>> a = 1/2/3/4/5/4/float(3)
>>> a
0.0
If we typecast the last integer to float, we will still get zero, since by the time our number gets divided by the float has already become 0 because of the integer division.
>>> a = 1/2/3/float(4)/5/4/3
>>> a
0.0
Same scenario as above but shifting the float typecast a little closer to the left side.
>>> a = float(1)/2/3/4/5/4/3
>>> a
0.0006944444444444445
Finally, when we typecast the first integer to float, the result is the desired one, since beginning from the first division, i.e. the leftmost one, we use floats.
Extra 1: If you are trying to answer that to improve arithmetic evaluation, you should check this
Extra 2: Please be careful of the following scenario:
>>> a = float(1/2/3/4/5/4/3)
>>> a
0.0
Are you having Tomcat unpack the WAR file? It seems that the files cannot be found on the classpath when a WAR file is loaded and it is not being unpacked.
$('#loginBtn').click(function(e) {
e.preventDefault(); /// it should not have this code or else it wont continue
//....
});
A few days ago I've had an issue with triggers, and I've figured out that ON UPDATE CASCADE
can be useful. Take a look at this example (PostgreSQL):
CREATE TABLE club
(
key SERIAL PRIMARY KEY,
name TEXT UNIQUE
);
CREATE TABLE band
(
key SERIAL PRIMARY KEY,
name TEXT UNIQUE
);
CREATE TABLE concert
(
key SERIAL PRIMARY KEY,
club_name TEXT REFERENCES club(name) ON UPDATE CASCADE,
band_name TEXT REFERENCES band(name) ON UPDATE CASCADE,
concert_date DATE
);
In my issue, I had to define some additional operations (trigger) for updating the concert's table. Those operations had to modify club_name and band_name. I was unable to do it, because of reference. I couldn't modify concert and then deal with club and band tables. I couldn't also do it the other way. ON UPDATE CASCADE
was the key to solve the problem.
Try the following:
<a asp-controller="Users" asp-action="Index"></a>
(Valid for ASP.NET 5 and MVC 6)
Try this code it is already built in c#
int lastDay = DateTime.DaysInMonth (2014, 2);
and the first day is always 1.
Good Luck!
this is the best file upload style I like:
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="input-append">
<div class="uneditable-input span3"><i class="icon-file fileupload-exists"></i> <span class="fileupload-preview"></span></div><span class="btn btn-file"><span class="fileupload-new">Select file</span><span class="fileupload-exists">Change</span><input type="file" /></span><a href="#" class="btn fileupload-exists" data-dismiss="fileupload">Remove</a>
</div>
</div>
you can get demo and more styles at:
http://www.jasny.net/bootstrap/javascript/#fileinput
but using this, you should replace twitter bootstrap with jasny bootstrap files..
regards.
"If I want two columns for anything over 768px, should I apply both classes?"
This should be as simple as:
<div class="row">
<div class="col-sm-6"></div>
<div class="col-sm-6"></div>
</div>
No need to add the col-lg-6
too.
What you should do is to check if activity is finishing before showing alert. For this purpose isFinishing()
method is defined within Activity class.
Here is what you should do:
if(!isFinishing())
{
alert.show();
}
Actually i am getting return value from a another sp into @temp and then it @temp =1 then i want to inc the count of @SelectoneCount by 1 and so on. Please let me know what is the correct syntax.
What's wrong with:
IF @Temp = 1 --Or @Temp = 2 also?
BEGIN
SET @SelectoneCount = @SelectoneCount + 1
END
(Although this does reek of being procedural code - not usually the best way to use SQL)
What I'm guessing is that you need to set those input elements to runat="server".
So you won't be able to access the control
<input type="text" name="email" id="myTextBox" />
But you'll be able to work with
<input type="text" name="email" id="myTextBox" runat="server" />
And read from it by using
string myStringFromTheInput = myTextBox.Value;
As an addition to Frank Heiken's answer, if you wish to use INSERT
statements instead of copy from stdin
, then you should specify the --inserts
flag
pg_dump --host localhost --port 5432 --username postgres --format plain --verbose --file "<abstract_file_path>" --table public.tablename --inserts dbname
Notice that I left out the --ignore-version
flag, because it is deprecated.
There is another solution you can try by using only the css here is the answer i posted in another post: jQuery Accordion change font awesome icon class on click
Similar to activa's answer, here's a function to create an n-dimensional array:
function createArray(length) {
var arr = new Array(length || 0),
i = length;
if (arguments.length > 1) {
var args = Array.prototype.slice.call(arguments, 1);
while(i--) arr[length-1 - i] = createArray.apply(this, args);
}
return arr;
}
createArray(); // [] or new Array()
createArray(2); // new Array(2)
createArray(3, 2); // [new Array(2),
// new Array(2),
// new Array(2)]
Well, I encountered the very same need a few days ago and had to get a variable's name which was pointing to the object itself.
And why was it so necessary?
In short I was building a plug-in for Maya. The core plug-in was built using C++ but the GUI is drawn through Python(as its not processor intensive). Since I, as yet, don't know how to return
multiple values from the plug-in except the default MStatus
, therefore to update a dictionary in Python I had to pass the the name of the variable, pointing to the object implementing the GUI and which contained the dictionary itself, to the plug-in and then use the MGlobal::executePythonCommand()
to update the dictionary from the global scope of Maya.
To do that what I did was something like:
import time
class foo(bar):
def __init__(self):
super(foo, self).__init__()
self.time = time.time() #almost guaranteed to be unique on a single computer
def name(self):
g = globals()
for x in g:
if isinstance(g[x], type(self)):
if g[x].time == self.time:
return x
#or you could:
#return filter(None,[x if g[x].time == self.time else None for x in g if isinstance(g[x], type(self))])
#and return all keys pointing to object itself
I know that it is not the perfect solution in in the globals
many keys could be pointing to the same object e.g.:
a = foo()
b = a
b.name()
>>>b
or
>>>a
and that the approach isn't thread-safe. Correct me if I am wrong.
At least this approach solved my problem by getting the name of any variable in the global scope which pointed to the object itself and pass it over to the plug-in, as argument, for it use internally.
I tried this on int
(the primitive integer class) but the problem is that these primitive classes don't get bypassed (please correct the technical terminology used if its wrong). You could re-implement int
and then do int = foo
but a = 3
will never be an object of foo
but of the primitive. To overcome that you have to a = foo(3)
to get a.name()
to work.
The question is quite old so I feel like I need to give a more up to date response to this question.
Based on MonoDevelop, the best IDE for building C# applications on the Mac, for pretty much any platform is http://xamarin.com/
The syntax for creating a new table is
CREATE TABLE new_table
AS
SELECT *
FROM old_table
This will create a new table named new_table
with whatever columns are in old_table
and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.
SELECT INTO
is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.
For Eclipse users...
Click Run —> Run configuration —> are —> set Alternate JRE for 1.6 or 1.7
I'm late to the party but I wanted to contribute. I'm surprised that nobody suggested exit()
. It's good for testing. I use it all the time and works like charm.
$a ='';
$b ='';
if($a == $b){
echo 'Clark Kent is Superman';
exit();
echo 'Clark Kent was never Superman';
}
The code will stop at exit()
and everything after will not run.
Result
Clark Kent is Superman
It works with foreach()
and while()
as well. It works anywhere you place it really.
foreach($arr as $val)
{
exit();
echo "test";
}
echo "finish";
Result
nothing gets printed here.
Use it with a forloop()
for ($x = 2; $x < 12; $x++) {
echo "Gru has $x minions <br>";
if($x == 4){
exit();
}
}
Result
Gru has 2 minions
Gru has 3 minions
Gru has 4 minions
In a normal case scenario
$a ='Make hot chocolate great again!';
echo $a;
exit();
$b = 'I eat chocolate and make Charlie at the Factory pay for it.';
Result
Make hot chocolate great again!
The FormClosed Event is an Event that fires when the form closes. It is not used to actually close the form. You'll need to remove anything you've added there.
All you should have to do is add the following line to your button's event handler:
this.Close();
You may also combine cut
and paste
:
paste <(cut -f2 file.txt) <(cut -f1 file.txt)
via comments: It's possible to avoid bashisms and remove one instance of cut by doing:
paste file.txt file.txt | cut -f2,3
Try this to read a file:
BufferedReader reader = null;
try {
File file = new File("sample-file.dat");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
There is no direct function to get yesterday's date.
To get yesterday's date, you need to use Calendar
by subtracting -1
.
If you can't rename the original file, you could also use a symlink:
ln -s foo-bar.py foo_bar.py
Then you can just:
from foo_bar import *
If you are willing to part with some money, JNIWrapper is a useful library with a Winpack, you will be able to get file system events on certain files. Unfortunately windows only.
See https://www.teamdev.com/jniwrapper.
Otherwise, resorting to native code is not always a bad thing especially when the best on offer is a polling mechanism as against a native event.
I've noticed that Java file system operations can be slow on some computers and can easily affect the application's performance if not handled well.
[^]
( within [ ] ) is negation in regular expression whereas ^
is "begining of string"
[^a-z]
matches any single character that is not from "a" to "z"
^[a-z]
means string starts with from "a" to "z"
Use single quotation marks ('
):
var val = '@ViewBag.ForSection';
alert(val);
C++ has Automatic variables - not Stack variables.
Automatic variable means that C++ compiler handles memory allocation / free by itself. C++ can automatically handle objects of any class - no matter whether it has dynamically allocated members or not. It's achieved by strong guarantee of C++ that object's destructor will be called automatically when execution is going out of scope where automatic variable was declared. Inside of a C++ object can be a lot of dynamic allocations with new
in constructor, and when such an object is declared as an automatic variable - all dynamic allocations will be performed, and freed then in destructor.
Stack variables in C can't be dynamically allocated. Stack in C can store pointers, or fixed arrays or structs - all of fixed size, and these things are being allocated in memory in linear order. When a C program frees a stack variable - it just moves stack pointer back and nothing more.
Even though C++ programs can use Stack memory segment for storing primitive types, function's args, or other, - it's all decided by C++ compiler, not by program developer. Thus, it is conceptually wrong to equal C++ automatic variables and C stack variables.
<div class="row">
<div class="col-4 alert alert-primary">
1
</div>
<div class="col-8">
<div class="row">
<div class="col-6 alert alert-primary">
2
</div>
<div class="col-6 alert alert-primary">
3
</div>
<div class="col-6 alert alert-primary">
4
</div>
<div class="col-6 alert alert-primary">
5
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-4 alert alert-primary">
6
</div>
<div class="col-4 alert alert-primary">
7
</div>
<div class="col-4 alert alert-primary">
8
</div>
</div>
As others have said, it's a direct child, but it's worth noting that this is different to just leaving a space... a space is for any descendant.
<div>
<span>Some text</span>
</div>
div>span
would match this, but it would not match this:
<div>
<p><span>Some text</span></p>
</div>
To match that, you could do div>p>span
or div span
.
In my case this happened when I used entity and the sql table has default value of datetime == getdate(). so what I did to set a value to this field.
typedef int (*PointerToIntArray)[];
typedef int *ArrayOfIntPointers[];
For our fellow Angular users:
Within a template, Number(x)
and parseInt(x)
throws an error, and +x
has no effect. Valid casting will be x*1
or x/1
.
You could also use the apache library and do this:
StringUtils.split(test, "|");
svg.selectAll("rect")
.attr('x',function(d,i){
// get x coord
console.log(this.getBBox().x, 'or', d3.select(this).attr('x'))
})
.attr('y',function(d,i){
// get y coord
console.log(this.getBBox().y)
})
.attr('dx',function(d,i){
// get dx coord
console.log(parseInt(d3.select(this).attr('dx')))
})
Just showing the answer of Pandincus with "of the shelf" code and some explanation: You need two solutions for this example ( I know it could be done via one also ; ), let the advanced students present it ...
So here is the DDL SQL for the table :
USE [ocms_dev]
GO
CREATE TABLE [dbo].[Role](
[RoleId] [int] IDENTITY(1,1) NOT NULL,
[RoleName] [varchar](50) NULL
) ON [PRIMARY]
So here is the console program producing the dll:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
using System.Data.Common;
using System.Data;
using System.Data.SqlClient;
namespace DynamicEnums
{
class EnumCreator
{
// after running for first time rename this method to Main1
static void Main ()
{
string strAssemblyName = "MyEnums";
bool flagFileExists = System.IO.File.Exists (
AppDomain.CurrentDomain.SetupInformation.ApplicationBase +
strAssemblyName + ".dll"
);
// Get the current application domain for the current thread
AppDomain currentDomain = AppDomain.CurrentDomain;
// Create a dynamic assembly in the current application domain,
// and allow it to be executed and saved to disk.
AssemblyName name = new AssemblyName ( strAssemblyName );
AssemblyBuilder assemblyBuilder =
currentDomain.DefineDynamicAssembly ( name,
AssemblyBuilderAccess.RunAndSave );
// Define a dynamic module in "MyEnums" assembly.
// For a single-module assembly, the module has the same name as
// the assembly.
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule (
name.Name, name.Name + ".dll" );
// Define a public enumeration with the name "MyEnum" and
// an underlying type of Integer.
EnumBuilder myEnum = moduleBuilder.DefineEnum (
"EnumeratedTypes.MyEnum",
TypeAttributes.Public,
typeof ( int )
);
#region GetTheDataFromTheDatabase
DataTable tableData = new DataTable ( "enumSourceDataTable" );
string connectionString = "Integrated Security=SSPI;Persist " +
"Security Info=False;Initial Catalog=ocms_dev;Data " +
"Source=ysg";
using (SqlConnection connection =
new SqlConnection ( connectionString ))
{
SqlCommand command = connection.CreateCommand ();
command.CommandText = string.Format ( "SELECT [RoleId], " +
"[RoleName] FROM [ocms_dev].[dbo].[Role]" );
Console.WriteLine ( "command.CommandText is " +
command.CommandText );
connection.Open ();
tableData.Load ( command.ExecuteReader (
CommandBehavior.CloseConnection
) );
} //eof using
foreach (DataRow dr in tableData.Rows)
{
myEnum.DefineLiteral ( dr[1].ToString (),
Convert.ToInt32 ( dr[0].ToString () ) );
}
#endregion GetTheDataFromTheDatabase
// Create the enum
myEnum.CreateType ();
// Finally, save the assembly
assemblyBuilder.Save ( name.Name + ".dll" );
} //eof Main
} //eof Program
} //eof namespace
Here is the Console programming printing the output ( remember that it has to reference the dll ). Let the advance students present the solution for combining everything in one solution with dynamic loading and checking if there is already build dll.
// add the reference to the newly generated dll
use MyEnums ;
class Program
{
static void Main ()
{
Array values = Enum.GetValues ( typeof ( EnumeratedTypes.MyEnum ) );
foreach (EnumeratedTypes.MyEnum val in values)
{
Console.WriteLine ( String.Format ( "{0}: {1}",
Enum.GetName ( typeof ( EnumeratedTypes.MyEnum ), val ),
val ) );
}
Console.WriteLine ( "Hit enter to exit " );
Console.ReadLine ();
} //eof Main
} //eof Program
mariofertc completely solved this for me here are his steps:
Verify mysql's data directory is empty (before you delete it though, save the err file for your records).
Under the mysql bin path run: mysqld.exe --initialize-insecure
add to my.ini (mysql's configuration file) the following: [mysqld] default_authentication_plugin=mysql_native_password
Then check services (via task manager) to make sure MySql is running, if not - right click MySql and start it.
I'll also note, if you don't have your mysql configuration file in the mysql bin and can't find it via the windows search, you will want to look for it in C:\Program Data\Mysql\ Note that it might be a different name other than my.ini, like a template, as Heesu mentions here: Can't find my.ini (mysql 5.7) Just find the template that matches the version of your mysql via the command mysql --version
var data = [
{
id : "001",
name : "apple",
category : "fruit",
color : "red"
},
{
id : "002",
name : "melon",
category : "fruit",
color : "green"
},
{
id : "003",
name : "banana",
category : "fruit",
color : "yellow"
}
];
for(var i = 0, len = data.length; i < length; i++) {
var temp = '<tr><td>' + data[i].id + '</td>';
temp+= '<td>' + data[i].name+ '</td>';
temp+= '<td>' + data[i].category + '</td>';
temp+= '<td>' + data[i].color + '</td></tr>';
$('table tbody').append(temp));
}
I'm using Eclipse with Cygwin and this worked for me:
Go to Project > Properties > C/C++ General > Preprocessor Includes... > Providers and select "CDT GCC Built-in Compiler Settings Cygwin [Shared]".
it means ONLY one byte will be allocated per character - so if you're using multi-byte charsets, your 1 character won't fit
if you know you have to have at least room enough for 1 character, don't use the BYTE syntax unless you know exactly how much room you'll need to store that byte
when in doubt, use VARCHAR2(1 CHAR)
same thing answered here Difference between BYTE and CHAR in column datatypes
Also, in 12c the max for varchar2 is now 32k, not 4000. If you need more than that, use CLOB
in Oracle, don't use VARCHAR
This is now available out of the box as of October 2017. From the blog post:
This was our #1 feature request - it's been a while coming but it's here now.
The complete documentation is here.
You can work with multiple project folders in Visual Studio Code with multi-root workspaces. This can be very helpful when you are working on several related projects at one time. For example, you might have a repository with a product's documentation which you like to keep current when you update the product source code.
Currently the Insider channel of VSCode gives us this out of the box.
Read more from the blog post.
For those who still struggle with this problem in Xcode8. For me was a duplicate Certificate problem, this is how I solved it:
I read the answer of Nick and then I began my investigation. I checked all the keys and Certificates in my particular case (inside ~/Library/Keychains/System.keychain).
When I opened the file, I found that I had two iPhone Distribution Certificates (that was the certificate that Xcode was requesting me), one with the iOS Distribution private key that I have been using since the beginning, and another iPhone Distribution Certificate which its private Key had a name (iOS Distribution:NAME) that wasn´t familiar for me. I deleted this last certificate, started Xcode again and the problem was gone. xCode wasn´t able to resolve that conflict and that´s why it was giving signing certificate error all the time.
Check your keychains, maybe you have a duplicate certificate.
Define in html:
<input type="hidden" name="image" id="image"/>
In JS:
ajax.jsonRpc("/consulta/dni", 'call', {'document_number': document_number})
.then(function (data) {
if (data.error){
...;
}
else {
$('#image').val(data.image);
}
})
After:
<input type="hidden" name="image" id="image" value="/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8U..."/>
<button type="submit">Submit</button>
You should not add to your list using c
inside the loop, because that can result in very very slow code. Basically when you do c(l, new_element)
, the whole contents of the list are copied. Instead of that, you need to access the elements of the list by index. If you know how long your list is going to be, it's best to initialise it to this size using l <- vector("list", N)
. If you don't you can initialise it to have length equal to some large number (e.g if you have an upper bound on the number of iterations) and then just pick the non-NULL elements after the loop has finished. Anyway, the basic point is that you should have an index to keep track of the list element and add using that eg
i <- 1
while(...) {
l[[i]] <- new_element
i <- i + 1
}
For more info have a look at Patrick Burns' The R Inferno (Chapter 2).
Use this php switcher
You can control php version to any your project you want via vhost config.
Assuming you use Java 5 enums (which is not so certain since you mention old Enumeration
class), you can use the valueOf
method of java.lang.Enum
subclass:
MyEnum e = MyEnum.valueOf("ONE_OF_CONSTANTS");
Background images sure can present data! In fact, this is often recommended where presenting visual icons is more compact and user-friendly than an equivalent list of text blurbs. Any use of image sprites can benefit from this approach.
It is quite common for hotel listings icons to display amenities. Imagine a page which listed 50 hotel and each hotel had 10 amenities. A CSS Sprite would be perfect for this sort of thing -- better user experience because it's faster. But how do you implement ALT tags for these images? Example site.
The answer is that they don't use alt
text at all, but instead use the title
attribute on the containing div.
HTML
<div class="hotwire-fitness" title="Fitness Centre"></div>
CSS
.hotwire-fitness {
float: left;
margin-right: 5px;
background: url(/prostyle/images/new_amenities.png) -71px 0;
width: 21px;
height: 21px;
}
According to the W3C (see links above), the title attribute serves much of the same purpose as the alt attribute
Title
Values of the title attribute may be rendered by user agents in a variety of ways. For instance, visual browsers frequently display the title as a "tool tip" (a short message that appears when the pointing device pauses over an object). Audio user agents may speak the title information in a similar context. For example, setting the attribute on a link allows user agents (visual and non-visual) to tell users about the nature of the linked resource:
alt
The alt attribute is defined in a set of tags (namely, img, area and optionally for input and applet) to allow you to provide a text equivalent for the object.
A text equivalent brings the following benefits to your website and its visitors in the following common situations:
- nowadays, Web browsers are available in a very wide variety of platforms with very different capacities; some cannot display images at all or only a restricted set of type of images; some can be configured to not load images. If your code has the alt attribute set in its images, most of these browsers will display the description you gave instead of the images
- some of your visitors cannot see images, be they blind, color-blind, low-sighted; the alt attribute is of great help for those people that can rely on it to have a good idea of what's on your page
- search engine bots belong to the two above categories: if you want your website to be indexed as well as it deserves, use the alt attribute to make sure that they won't miss important sections of your pages.
Add the hidden titleLabel to the parameter is the best solution.
I generated a array arrUrl which store the NSURL of the mov files in my phone album by enumerate assets block.
After that, I grab on Frame, lets say, get the frame at 3:00 second in the movie file, and generated the image file from the frame.
Next, loop over the arrUrl, and use program generate the button with image in the button, append the button to subview of the self.view.
Because I have to pass the movie Url to playMovie function, I have to assign the button.titleLabel.text with one movie url. and the the button events function, retrieve the url from the buttontitleLable.txt.
-(void)listVideos
{
for(index=0;index<[self.arrUrl count];index++{
UIButton *imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
imageButton.frame = CGRectMake(20,50+60*index,50,50);
NSURL *dUrl = [self.arrUrl objectAtIndex:index];
[imageButton setImage:[[UIImage allow] initWithCGImage:*[self getFrameFromeVideo:dUrl]] forState:UIControlStateNormal];
[imageButton addTarget:self action:@selector(playMovie:) forControlEvents:UIControlEventTouchUpInside];
imageButton.titleLabel.text = [NSString strinfWithFormat:@"%@",dUrl];
imageButton.titleLabel.hidden = YES;
[self.view addSubView:imageButton];
}
}
-(void)playMovie:(id) sender{
UIButton *btn = (UIButton *)sender;
NSURL *movUrl = [NSURL URLWithString:btn.titleLabel.text];
moviePlayer = [[MPMoviePlayerViewController alloc] initWithContentURL:movUrl];
[self presentMoviePlayerViewControllerAnimated:moviePlayer];
}
-(CGIImageRef *)getFrameFromVideo:(NSURL *)mUrl{
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:mUrl option:nil];
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generator.appliesPreferredTrackTransform = YES;
NSError *error =nil;
CMTime = CMTimeMake(3,1);
CGImageRef imageRef = [generator copyCGImageAtTime:time actualTime:nil error:&error];
if(error !=nil) {
NSLog(@"%@",sekf,error);
}
return @imageRef;
}
to change pro-grammatically use :
imgview.setScaleType(ScaleType.FIT_XY);
OR
to change from xml use:
android:scaleType="fitXY"
**input of list of number for array from single line.
String input = sc.nextLine();
String arr[] = input.split(" ");
int new_arr[] = new int[arr.length];
for(int i=0; i<arr.length; i++)
{
new_arr[i] = Integer.parseInt(arr[i]);
}
It's a linefeed character. How you use it would be up to you.
Currently you are catching only RuntimeException
, a sub class of Exception
. But your application may throw other sub-classes of Exception. Catch generic Exception
in addition to RuntimeException
Since many of things have been changed on Threading front, use advanced java API.
Prefer advance java.util.concurrent API for multi-threading like ExecutorService
or ThreadPoolExecutor
.
You can customize your ThreadPoolExecutor to handle exceptions.
Example from oracle documentation page:
Override
protected void afterExecute(Runnable r,
Throwable t)
Method invoked upon completion of execution of the given Runnable. This method is invoked by the thread that executed the task. If non-null, the Throwable is the uncaught RuntimeException or Error that caused execution to terminate abruptly.
Example code:
class ExtendedExecutor extends ThreadPoolExecutor {
// ...
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
if (t == null && r instanceof Future<?>) {
try {
Object result = ((Future<?>) r).get();
} catch (CancellationException ce) {
t = ce;
} catch (ExecutionException ee) {
t = ee.getCause();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt(); // ignore/reset
}
}
if (t != null)
System.out.println(t);
}
}
Usage:
ExtendedExecutor service = new ExtendedExecutor();
I have added one constructor on top of above code as:
public ExtendedExecutor() {
super(1,5,60,TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(100));
}
You can change this constructor to suit your requirement on number of threads.
ExtendedExecutor service = new ExtendedExecutor();
service.submit(<your Callable or Runnable implementation>);
INSERT INTO Table2 SELECT DISTINCT ID,Data = STUFF((SELECT ', ' + AA.Data FROM Table1 AS AA WHERE AA.ID = BB.ID FOR XML PATH(''), TYPE).value('.','nvarchar(max)'), 1, 2, '') FROM Table1 AS BB
GROUP BY ID,Data
ORDER BY ID;
I found a solution for this:
logger = logging.getLogger('my-logger')
logger.propagate = False
# now if you use logger it will not log to console.
This will prevent logging from being send to the upper logger that includes the console logging.
Unicode only define code points, that is, a number which represents a character. How you store these code points in memory depends of the encoding that you are using. UTF-8 is one way of encoding Unicode characters, among many others.
Find Arabic chars and replace them with its UTF-8 encoding. some thing like this:
for (int i = 0; i < urlAsString.length(); i++) {
if (urlAsString.charAt(i) > 255) {
urlAsString = urlAsString.substring(0, i) + URLEncoder.encode(urlAsString.charAt(i)+"", "UTF-8") + urlAsString.substring(i+1);
}
}
encodedURL = urlAsString;
tried to format my answer, but couldn't.Please stackoverflow team, why posting answer is so hard.
neverthless,
answer:
git fetch origin
git status (you'll see result like "Your branch is behind 'origin/master' by 9 commits")
to update to remote changes : git pull
To get a fully independent copy of an object you can use the copy.deepcopy()
function.
For more details about shallow and deep copying please refer to the other answers to this question and the nice explanation in this answer to a related question.
I know this was answered a long time ago, but I've recently spent hours trying to solve a similar problem. The setup is local PC running Debian 8 using Eclipse CDT Neon.2, remote ARM7 board (Olimex) running Debian 7. Tool chain is Linaro 4.9 using gdbserver on the remote board and the Linaro GDB on the local PC. My issue was that the debug session would start and the program would execute, but breakpoints did not work and when manually paused "no source could be found" would result. My compile line options (Linaro gcc) included -ggdb -O0 as many have suggested but still the same problem. Ultimately I tried gdb proper on the remote board and it complained of no symbols. The curious thing was that 'file' reported debug not stripped on the target executable.
I ultimately solved the problem by adding -g to the linker options. I won't claim to fully understand why this helped, but I wanted to pass this on for others just in case it helps. In this case Linux did indeed need -g on the linker options.
string path = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();
This is probably a more "correct" way of getting it.
console.log(typeof json_data !== 'undefined'
? json_data.length : 'There is no spoon.');
...or more simply...
console.log(json_data ? json_data.length : 'json_data is null or undefined');
In the same location where the JVM's stdout is placed. If you have a Tomcat server, this will be the catalina_(date).out
file.
Here is a complete version of code for doing this. I have tested it. The BufferedImage
and Base64
class do the trick mainly. Also some parameter needs to be set correctly.
public class SimpleConvertImage {
public static void main(String[] args) throws IOException{
String dirName="C:\\";
ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
BufferedImage img=ImageIO.read(new File(dirName,"rose.jpg"));
ImageIO.write(img, "jpg", baos);
baos.flush();
String base64String=Base64.encode(baos.toByteArray());
baos.close();
byte[] bytearray = Base64.decode(base64String);
BufferedImage imag=ImageIO.read(new ByteArrayInputStream(bytearray));
ImageIO.write(imag, "jpg", new File(dirName,"snap.jpg"));
}
}
- (UIImage*)imageScale:(CGFloat)scaleFactor cropForSize:(CGSize)targetSize
{
targetSize = !targetSize.width?self.size:targetSize;
UIGraphicsBeginImageContext(targetSize); // this will crop
CGRect thumbnailRect = CGRectZero;
thumbnailRect.size.width = targetSize.width*scaleFactor;
thumbnailRect.size.height = targetSize.height*scaleFactor;
CGFloat xOffset = (targetSize.width- thumbnailRect.size.width)/2;
CGFloat yOffset = (targetSize.height- thumbnailRect.size.height)/2;
thumbnailRect.origin = CGPointMake(xOffset,yOffset);
[self drawInRect:thumbnailRect];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
if(newImage == nil)
{
NSLog(@"could not scale image");
}
UIGraphicsEndImageContext();
return newImage;
}
Below the example of work: Left image - (origin image) ; Right image with scale x2
If you want to scale image but retain its frame(proportions), call method this way:
[yourImage imageScale:2.0f cropForSize:CGSizeZero];
In addition to @JBNizet's answer, my general use case for ifPresent
is to combine .isPresent()
and .get()
:
Old way:
Optional opt = getIntOptional();
if(opt.isPresent()) {
Integer value = opt.get();
// do something with value
}
New way:
Optional opt = getIntOptional();
opt.ifPresent(value -> {
// do something with value
})
This, to me, is more intuitive.
When you say
(a['x']==1) and (a['y']==10)
You are implicitly asking Python to convert (a['x']==1)
and (a['y']==10)
to boolean values.
NumPy arrays (of length greater than 1) and Pandas objects such as Series do not have a boolean value -- in other words, they raise
ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().
when used as a boolean value. That's because its unclear when it should be True or False. Some users might assume they are True if they have non-zero length, like a Python list. Others might desire for it to be True only if all its elements are True. Others might want it to be True if any of its elements are True.
Because there are so many conflicting expectations, the designers of NumPy and Pandas refuse to guess, and instead raise a ValueError.
Instead, you must be explicit, by calling the empty()
, all()
or any()
method to indicate which behavior you desire.
In this case, however, it looks like you do not want boolean evaluation, you want element-wise logical-and. That is what the &
binary operator performs:
(a['x']==1) & (a['y']==10)
returns a boolean array.
By the way, as alexpmil notes,
the parentheses are mandatory since &
has a higher operator precedence than ==
.
Without the parentheses, a['x']==1 & a['y']==10
would be evaluated as a['x'] == (1 & a['y']) == 10
which would in turn be equivalent to the chained comparison (a['x'] == (1 & a['y'])) and ((1 & a['y']) == 10)
. That is an expression of the form Series and Series
.
The use of and
with two Series would again trigger the same ValueError
as above. That's why the parentheses are mandatory.
just found
grep $'\r'
It's using $'\r'
for c-style escape in Bash.
in this article
Banengusk was putting me on the right track. For further reference, I want to post the steps I took to fix my repository corruption. I was lucky enough to find all needed objects either in older packs or in repository backups.
# Unpack last non-corrupted pack
$ mv .git/objects/pack .git/objects/pack.old
$ git unpack-objects -r < .git/objects/pack.old/pack-012066c998b2d171913aeb5bf0719fd4655fa7d0.pack
$ git log
fatal: bad object HEAD
$ cat .git/HEAD
ref: refs/heads/master
$ ls .git/refs/heads/
$ cat .git/packed-refs
# pack-refs with: peeled
aa268a069add6d71e162c4e2455c1b690079c8c1 refs/heads/master
$ git fsck --full
error: HEAD: invalid sha1 pointer aa268a069add6d71e162c4e2455c1b690079c8c1
error: refs/heads/master does not point to a valid object!
missing blob 75405ef0e6f66e48c1ff836786ff110efa33a919
missing blob 27c4611ffbc3c32712a395910a96052a3de67c9b
dangling tree 30473f109d87f4bcde612a2b9a204c3e322cb0dc
# Copy HEAD object from backup of repository
$ cp repobackup/.git/objects/aa/268a069add6d71e162c4e2455c1b690079c8c1 .git/objects/aa
# Now copy all missing objects from backup of repository and run "git fsck --full" afterwards
# Repeat until git fsck --full only reports dangling objects
# Now garbage collect repo
$ git gc
warning: reflog of 'HEAD' references pruned commits
warning: reflog of 'refs/heads/master' references pruned commits
Counting objects: 3992, done.
Delta compression using 2 threads.
fatal: object bf1c4953c0ea4a045bf0975a916b53d247e7ca94 inconsistent object length (6093 vs 415232)
error: failed to run repack
# Check reflogs...
$ git reflog
# ...then clean
$ git reflog expire --expire=0 --all
# Now garbage collect again
$ git gc
Counting objects: 3992, done.
Delta compression using 2 threads.
Compressing objects: 100% (3970/3970), done.
Writing objects: 100% (3992/3992), done.
Total 3992 (delta 2060), reused 0 (delta 0)
Removing duplicate objects: 100% (256/256), done.
# Done!
These instructions worked for a Windows 8 with a msysgit/TortoiseGit installation, but should be applicable for other types of git installations on Windows.
;C:\msysgit\bin\;C:\msysgit\mingw\bin\
PHP is a normal sripting language similar to bash or python or perl. So a script with shebang works, at least on linux.
Example PHP file:
#!/usr/bin/env php
<?php
echo("Hello World!\n")
?>
How to run it:
$ chmod 755 hello.php # do this only once
$ ./hello.php
The other methods work fine, but you can also use the good old django.shortcut.redirect
.
The code below was taken from this answer.
In Django 2.x:
from django.shortcuts import redirect
from django.urls import path, include
urlpatterns = [
# this example uses named URL 'hola-home' from app named hola
# for more redirect's usage options: https://docs.djangoproject.com/en/2.1/topics/http/shortcuts/
path('', lambda request: redirect('hola/', permanent=True)),
path('hola/', include('hola.urls')),
]
This worked for me: http://ubuntuforums.org/showthread.php?t=1519176
After installing composer using the command curl -sS https://getcomposer.org/installer | php
just run a sudo apt-get update
then reinstall curl with sudo apt-get install php5-curl
. Then composer's installation process should work so you can finally run php composer.phar install
to get the dependencies listed in your composer.json file.
One could use Where-Object
if ((Get-Service | Where-Object {$_.Name -eq $serviceName}).length -eq 1) {
"Service Exists"
}
You can use clone, and then since each div has a class of car_well you can use insertAfter to insert after the last div.
$("#car2").clone().insertAfter("div.car_well:last");
So it seems that there is no way to reattach a stale detached entity in JPA.
merge()
will push the stale state to the DB,
and overwrite any intervening updates.
refresh()
cannot be called on a detached entity.
lock()
cannot be called on a detached entity,
and even if it could, and it did reattach the entity,
calling 'lock' with argument 'LockMode.NONE'
implying that you are locking, but not locking,
is the most counterintuitive piece of API design I've ever seen.
So you are stuck.
There's an detach()
method, but no attach()
or reattach()
.
An obvious step in the object lifecycle is not available to you.
Judging by the number of similar questions about JPA, it seems that even if JPA does claim to have a coherent model, it most certainly does not match the mental model of most programmers, who have been cursed to waste many hours trying understand how to get JPA to do the simplest things, and end up with cache management code all over their applications.
It seems the only way to do it is discard your stale detached entity and do a find query with the same id, that will hit the L2 or the DB.
Mik
How do they achieve internally that you are able to pass something like x > 5 into a method?
The short answer is that they don't.
Any sort of logical operation on a numpy array returns a boolean array. (i.e. __gt__
, __lt__
, etc all return boolean arrays where the given condition is true).
E.g.
x = np.arange(9).reshape(3,3)
print x > 5
yields:
array([[False, False, False],
[False, False, False],
[ True, True, True]], dtype=bool)
This is the same reason why something like if x > 5:
raises a ValueError if x
is a numpy array. It's an array of True/False values, not a single value.
Furthermore, numpy arrays can be indexed by boolean arrays. E.g. x[x>5]
yields [6 7 8]
, in this case.
Honestly, it's fairly rare that you actually need numpy.where
but it just returns the indicies where a boolean array is True
. Usually you can do what you need with simple boolean indexing.
JSON is just a subset of JavaScript. But eval
evaluates the full JavaScript language and not just the subset that’s JSON.
import { useDebouncedCallback } from 'use-debounce'; - install npm packge for same if not installed
const [searchText, setSearchText] = useState('');
const onSearchTextChange = value => {
setSearchText(value);
};
//call search api
const [debouncedOnSearch] = useDebouncedCallback(searchIssues, 500);
useEffect(() => {
debouncedOnSearch(searchText);
}, [searchText, debouncedOnSearch]);
For all practical purposes, and with no import at all, one can use:
x = float("inf")
More detail on this related question: How can I represent an infinite number in Python?
This is caused by the limited support for the MP4 format within the video tag in Firefox. Support was not added until Firefox 21, and it is still limited to Windows 7 and above. The main reason for the limited support revolves around the royalty fee attached to the mp4 format.
Check out Supported media formats and Media formats supported by the audio and video elements directly from the Mozilla crew or the following blog post for more information:
http://pauljacobson.org/2010/01/22/2010122firefox-and-its-limited-html-5-video-support-html/
What I would do is create a Boolean outside your function that starts out as FALSE and gets set to TRUE when you attach the event. This would serve as some sort of flag for you before you attach the event again. Here's an example of the idea.
// initial load
var attached = false;
// this will only execute code once
doSomething = function()
{
if (!attached)
{
attached = true;
//code
}
}
//attach your function with change event
window.onload = function()
{
var txtbox = document.getElementById('textboxID');
if (window.addEventListener)
{
txtbox.addEventListener('change', doSomething, false);
}
else if(window.attachEvent)
{
txtbox.attachEvent('onchange', doSomething);
}
}
Either use
SELECT IF(field1 IS NULL or field1 = '', 'empty', field1) as field1
from tablename
or
SELECT case when field1 IS NULL or field1 = ''
then 'empty'
else field1
end as field1
from tablename
If you only want to check for null
and not for empty strings then you can also use ifnull()
or coalesce(field1, 'empty')
. But that is not suitable for empty strings.
Styling alert()-boxes ist not possible. You could use a javascript modal overlay instead.
Try \n\n , it will work! :)
public async Task AjudaAsync(IDialogContext context, LuisResult result){
await context.PostAsync("How can I help you? \n\n 1.To Schedule \n\n 2.Consult");
context.Wait(MessageReceived);
}
Expanding upon @aquinas:
Get-something | select -ExpandProperty PropertyName
or
Get-something | select -expand PropertyName
or
Get-something | select -exp PropertyName
I made these suggestions for those that might just be looking for a single-line command to obtain some piece of information and wanted to include a real-world example.
In managing Office 365 via PowerShell, here was an example I used to obtain all of the users/groups that had been added to the "BookInPolicy" list:
Get-CalendarProcessing [email protected] | Select -expand BookInPolicy
Just using "Select BookInPolicy" was cutting off several members, so thank you for this information!
include <string>
For Validating Doubles:
bool validateDouble(const std::string & input) {
int decimals = std::count(input.begin(), input.end(), '.'); // The number of decimals in the string
int negativeSigns = std::count(input.begin(), input.end(), '-'); // The number of negative signs in the string
if (input.size() == decimals + negativeSigns) // Consists of only decimals and negatives or is empty
return false;
else if (1 < decimals || 1 < negativeSigns) // More than 1 decimal or negative sign
return false;
else if (1 == negativeSigns && input[0] != '-') // The negative sign (if there is one) is not the first character
return false;
else if (strspn(input.c_str(), "-.0123456789") != input.size()) // The string contains a character that isn't in "-.0123456789"
return false;
return true;
}
For Validating Ints (With Negatives)
bool validateInt(const std::string & input) {
int negativeSigns = std::count(input.begin(), input.end(), '-'); // The number of negative signs in the string
if (input.size() == negativeSigns) // Consists of only negatives or is empty
return false;
else if (1 < negativeSigns) // More than 1 negative sign
return false;
else if (1 == negativeSigns && input[0] != '-') // The negative sign (if there is one) is not the first character
return false;
else if (strspn(input.c_str(), "-0123456789") != input.size()) // The string contains a character that isn't in "-0123456789"
return false;
return true;
}
For Validating Unsigned Ints
bool validateUnsignedInt(const std::string & input) {
return (input.size() != 0 && strspn(input.c_str(), "0123456789") == input.size()); // The string is not empty and contains characters only in "0123456789"
}
The crontab website gives the real time results display: https://crontab.guru/#5_8_*_*_0
Try This
<label style="position: relative; left:15px;">$</label>
<input type="text" style="text-indent: 15px;">
_x000D_
From Django documentation for url
url(regex, view, kwargs=None, name=None)
This function is an alias todjango.urls.re_path()
. It’s likely to be deprecated in a future release.
Key difference between path
and re_path
is that path
uses route without regex
You can use re_path
for complex regex calls and use just path
for simpler lookups
You may achieve this using pandas as well:
import pandas as pd
pd.to_datetime('Mon Feb 15 2010', format='%a %b %d %Y').strftime('%d/%m/%Y')
Output:
'15/02/2010'
You may apply pandas approach for different datatypes as:
import pandas as pd
import numpy as np
def reformat_date(date_string, old_format, new_format):
return pd.to_datetime(date_string, format=old_format, errors='ignore').strftime(new_format)
date_string = 'Mon Feb 15 2010'
date_list = ['Mon Feb 15 2010', 'Wed Feb 17 2010']
date_array = np.array(date_list)
date_series = pd.Series(date_list)
old_format = '%a %b %d %Y'
new_format = '%d/%m/%Y'
print(reformat_date(date_string, old_format, new_format))
print(reformat_date(date_list, old_format, new_format).values)
print(reformat_date(date_array, old_format, new_format).values)
print(date_series.apply(lambda x: reformat_date(x, old_format, new_format)).values)
Output:
15/02/2010
['15/02/2010' '17/02/2010']
['15/02/2010' '17/02/2010']
['15/02/2010' '17/02/2010']
The two valid mains are int main()
and int main(int, char*[])
. Any thing else may or may not compile. If main
doesn't explicitly return a value, 0 is implicitly returned.
Yes, there are at least 2 solutions for this:
script
directive (http://docs.angularjs.org/api/ng.directive:script) to put your partials in the initially loaded HTML$templateCache
(http://docs.angularjs.org/api/ng.$templateCache) from JavaScript if needed (possibly based on result of $http
call)If you would like to use method (2) to fill in $templateCache
you can do it like this:
$templateCache.put('second.html', '<b>Second</b> template');
Of course the templates content could come from a $http
call:
$http.get('third.html', {cache:$templateCache});
Here is the plunker those techniques: http://plnkr.co/edit/J6Y2dc?p=preview
In the latest version of ggplot2, this can be more easy.
p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()
p+ geom_point() + scale_x_continuous(expand = expansion(mult = c(0, 0))) + scale_y_continuous(expand = expansion(mult = c(0, 0)))
See ?expansion()
for more details.
Let me show you another way that works 100%. I will also add some padding for the example.
<div class = "container">
<div class = "flex-pad-x">
<div class = "flex-pad-y">
<div class = "flex-pad-y">
<div class = "flex-grow-y">
Content Centered
</div>
</div>
</div>
</div>
</div>
.container {
position: fixed;
top: 0px;
left: 0px;
bottom: 0px;
right: 0px;
width: 100%;
height: 100%;
}
.flex-pad-x {
padding: 0px 20px;
height: 100%;
display: flex;
}
.flex-pad-y {
padding: 20px 0px;
width: 100%;
display: flex;
flex-direction: column;
}
.flex-grow-y {
flex-grow: 1;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
As you can see we can achieve this with a few wrappers for control while utilising the flex-grow & flex-direction attribute.
1: When the parent "flex-direction" is a "row", its child "flex-grow" works horizontally. 2: When the parent "flex-direction" is "columns", its child "flex-grow" works vertically.
Hope this helps
Daniel
I prefer to use Daniel X. Moore's {SUPER: SYSTEM}
. This is a discipline that provides benefits such as true instance variables, trait based inheritance, class hierarchies and configuration options. The example below illustrates the use of true instance variables, which I believe is the biggest advantage. If you don't need instance variables and are happy with only public or private variables then there are probably simpler systems.
function Person(I) {
I = I || {};
Object.reverseMerge(I, {
name: "McLovin",
age: 25,
homeState: "Hawaii"
});
return {
introduce: function() {
return "Hi I'm " + I.name + " and I'm " + I.age;
}
};
}
var fogel = Person({
age: "old enough"
});
fogel.introduce(); // "Hi I'm McLovin and I'm old enough"
Wow, that's not really very useful on it's own, but take a look at adding a subclass:
function Ninja(I) {
I = I || {};
Object.reverseMerge(I, {
belt: "black"
});
// Ninja is a subclass of person
return Object.extend(Person(I), {
greetChallenger: function() {
return "In all my " + I.age + " years as a ninja, I've never met a challenger as worthy as you...";
}
});
}
var resig = Ninja({name: "John Resig"});
resig.introduce(); // "Hi I'm John Resig and I'm 25"
Another advantage is the ability to have modules and trait based inheritance.
// The Bindable module
function Bindable() {
var eventCallbacks = {};
return {
bind: function(event, callback) {
eventCallbacks[event] = eventCallbacks[event] || [];
eventCallbacks[event].push(callback);
},
trigger: function(event) {
var callbacks = eventCallbacks[event];
if(callbacks && callbacks.length) {
var self = this;
callbacks.forEach(function(callback) {
callback(self);
});
}
},
};
}
An example of having the person class include the bindable module.
function Person(I) {
I = I || {};
Object.reverseMerge(I, {
name: "McLovin",
age: 25,
homeState: "Hawaii"
});
var self = {
introduce: function() {
return "Hi I'm " + I.name + " and I'm " + I.age;
}
};
// Including the Bindable module
Object.extend(self, Bindable());
return self;
}
var person = Person();
person.bind("eat", function() {
alert(person.introduce() + " and I'm eating!");
});
person.trigger("eat"); // Blasts the alert!
Disclosure: I am Daniel X. Moore and this is my {SUPER: SYSTEM}
. It is the best way to define a class in JavaScript.
A Simple find
can work handy. alias it in your ~/.bashrc
file:
alias ffind find / -type f | xargs grep
Start a new terminal and issue:
ffind 'text-to-find-here'
Do you mean how long is the array itself, or how many customerids are in it?
Because the answer to the first question is easy: 5 (or if you don't want to hard-code it, Ben Stott's answer).
But the answer to the other question cannot be automatically determined. Presumably you have allocated an array of length 5, but will initially have 0 customer IDs in there, and will put them in one at a time, and your question is, "how many customer IDs have I put into the array?"
C can't tell you this. You will need to keep a separate variable, int numCustIds
(for example). Every time you put a customer ID into the array, increment that variable. Then you can tell how many you have put in.
The simple solution is:
1.keep the image file and HTML file in the same folder.
2.code: <img src="Desert.png">
// your image name.
3.keep the folder in D drive.
Keeping the folder on the desktop(which is c drive) you can face the issue of permission.
To prevent the flex items from shrinking, set the flex shrink factor to 0
:
The flex shrink factor determines how much the flex item will shrink relative to the rest of the flex items in the flex container when negative free space is distributed. When omitted, it is set to 1.
.boxcontainer .box {
flex-shrink: 0;
}
* {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
.wrapper {_x000D_
width: 200px;_x000D_
background-color: #EEEEEE;_x000D_
border: 2px solid #DDDDDD;_x000D_
padding: 1rem;_x000D_
}_x000D_
.boxcontainer {_x000D_
position: relative;_x000D_
left: 0;_x000D_
border: 2px solid #BDC3C7;_x000D_
transition: all 0.4s ease;_x000D_
display: flex;_x000D_
}_x000D_
.boxcontainer .box {_x000D_
width: 100%;_x000D_
padding: 1rem;_x000D_
flex-shrink: 0;_x000D_
}_x000D_
.boxcontainer .box:first-child {_x000D_
background-color: #F47983;_x000D_
}_x000D_
.boxcontainer .box:nth-child(2) {_x000D_
background-color: #FABCC1;_x000D_
}_x000D_
#slidetrigger:checked ~ .wrapper .boxcontainer {_x000D_
left: -100%;_x000D_
}_x000D_
#overflowtrigger:checked ~ .wrapper {_x000D_
overflow: hidden;_x000D_
}
_x000D_
<input type="checkbox" id="overflowtrigger" />_x000D_
<label for="overflowtrigger">Hide overflow</label><br />_x000D_
<input type="checkbox" id="slidetrigger" />_x000D_
<label for="slidetrigger">Slide!</label>_x000D_
<div class="wrapper">_x000D_
<div class="boxcontainer">_x000D_
<div class="box">_x000D_
First bunch of content._x000D_
</div>_x000D_
<div class="box">_x000D_
Second load of content._x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
SWIFT 4
Change the size when typing
UITextViewDelegate
func textViewDidChange(_ textView: UITextView) {
yourTextView.translatesAutoresizingMaskIntoConstraints = true
yourTextView.sizeToFit()
yourTextView.isScrollEnabled = false
let calHeight = yourTextView.frame.size.height
yourTextView.frame = CGRect(x: 16, y: 193, width: self.view.frame.size.width - 32, height: calHeight)
}
Change the size when load
func textViewNotasChange(arg : UITextView) {
arg.translatesAutoresizingMaskIntoConstraints = true
arg.sizeToFit()
arg.isScrollEnabled = false
let calHeight = arg.frame.size.height
arg.frame = CGRect(x: 16, y: 40, width: self.view.frame.size.width - 32, height: calHeight)
}
Call the function of the second option like this:
textViewNotasChange(arg: yourTextView)
Based on Olivier Refalo's answer
if [ $# -eq 2 ]
then
echo "Setting tracking for branch " $1 " -> " $2
git branch --set-upstream $1 $2
else
echo "-- Local --"
git for-each-ref --shell --format="[ %(upstream:short) != '' ] && echo -e '\t%(refname:short) <--> %(upstream:short)'" refs/heads | sh
echo "-- Remote --"
REMOTES=$(git remote -v)
if [ "$REMOTES" != '' ]
then
echo $REMOTES
fi
fi
It shows only local with track configured.
Write it on a script called git-track on your path an you will get a git track command
A more elaborated version on https://github.com/albfan/git-showupstream
This works for me:
psql postgresql://myuser:password@myhost/my_db -f myInsertFile.sql
function IsNumeric(num) {
return (num >=0 || num < 0);
}
This works for 0x23 type numbers as well.
To get exact name of control, use:
string controlName = Page.FindControl(Page.Request.Params["__EVENTTARGET"]).ID;
It seems you need DataFrame.var
:
Normalized by N-1 by default. This can be changed using the ddof argument
var1 = credit_card.var()
Sample:
#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
A B C D E
0 8 8 3 7 7
1 0 4 2 5 2
2 2 2 1 0 8
3 4 0 9 6 2
4 4 1 5 3 4
var1 = credit_card.var()
print (var1)
A 8.8
B 10.0
C 10.0
D 7.7
E 7.8
dtype: float64
var2 = credit_card.var(axis=1)
print (var2)
0 4.3
1 3.8
2 9.8
3 12.2
4 2.3
dtype: float64
If need numpy solutions with numpy.var
:
print (np.var(credit_card.values, axis=0))
[ 7.04 8. 8. 6.16 6.24]
print (np.var(credit_card.values, axis=1))
[ 3.44 3.04 7.84 9.76 1.84]
Differences are because by default ddof=1
in pandas
, but you can change it to 0
:
var1 = credit_card.var(ddof=0)
print (var1)
A 7.04
B 8.00
C 8.00
D 6.16
E 6.24
dtype: float64
var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0 3.44
1 3.04
2 7.84
3 9.76
4 1.84
dtype: float64
Sets new value for backgroundPosition
on the carousel
div when a li in the submenu
div is hovered. Removes the backgroundPosition
when hovering ends and resets backgroundPosition
to old value.
$('#submenu li').hover(function() {
if ($('#carousel').data('oldbackgroundPosition')==undefined) {
$('#carousel').data('oldbackgroundPosition', $('#carousel').css('backgroundPosition'));
}
$('#carousel').css('backgroundPosition', [enternewvaluehere]);
},
function() {
var reset = '';
if ($('#carousel').data('oldbackgroundPosition') != undefined) {
reset = $('#carousel').data('oldbackgroundPosition');
$('#carousel').removeData('oldbackgroundPosition');
}
$('#carousel').css('backgroundPosition', reset);
});
You need to give a relative file path of <a href="../index.html">Home</a>
Alternately you can specify a link from the root of your site with
<a href="/pages/en/index.html">Home</a>
..
and .
have special meanings in file paths, ..
means up one directory and .
means current directory.
so <a href="index.html">Home</a>
is the same as <a href="./index.html">Home</a>
Just check the length of files property, which is a FileList object contained on the input element
if( document.getElementById("videoUploadFile").files.length == 0 ){
console.log("no files selected");
}
Old Microsoft Sql Sever (< 2012)
RETURN dateadd(month, 12 * @year + @month - 22801, @day - 1)
That's because you're using a non-blocking
socket and the output buffer is full.
From the send()
man page
When the message does not fit into the send buffer of the socket,
send() normally blocks, unless the socket has been placed in non-block-
ing I/O mode. In non-blocking mode it would return EAGAIN in this
case.
EAGAIN is the error code tied to "Resource temporarily unavailable"
Consider using select()
to get a better control of this behaviours
Use typeof
or instanceof
:
const assert = require('assert');
function myFunction(Date myDate, String myString)
{
assert( typeof(myString) === 'string', 'Error message about incorrect arg type');
assert( myDate instanceof Date, 'Error message about incorrect arg type');
}
When you reference Range like that it's called an unqualified reference because you don't specifically say which sheet the range is on. Unqualified references are handled by the "_Global" object that determines which object you're referring to and that depends on where your code is.
If you're in a standard module, unqualified Range will refer to Activesheet. If you're in a sheet's class module, unqualified Range will refer to that sheet.
inputTemplateContent is a variable that contains a reference to a range, probably a named range. If you look at the RefersTo property of that named range, it likely points to a sheet other than the Activesheet at the time the code executes.
The best way to fix this is to avoid unqualified Range references by specifying the sheet. Like
With ThisWorkbook.Worksheets("Template")
.Range(inputTemplateHeader).Value = NO_ENTRY
.Range(inputTemplateContent).Value = NO_ENTRY
End With
Adjust the workbook and worksheet references to fit your particular situation.
This may be what you are looking for:
body>div {_x000D_
background: #aaa;_x000D_
display: flex;_x000D_
flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
body>div>div {_x000D_
flex-grow: 1;_x000D_
width: 33%;_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
body>div>div:nth-child(even) {_x000D_
background: #23a;_x000D_
}_x000D_
_x000D_
body>div>div:nth-child(odd) {_x000D_
background: #49b;_x000D_
}
_x000D_
<div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
</div>
_x000D_
For a more generic and extensible way check mergedict. It uses singledispatch
and can merge values based on its types.
Example:
from mergedict import MergeDict
class SumDict(MergeDict):
@MergeDict.dispatch(int)
def merge_int(this, other):
return this + other
d2 = SumDict({'a': 1, 'b': 'one'})
d2.merge({'a':2, 'b': 'two'})
assert d2 == {'a': 3, 'b': 'two'}
Simply pass the BSTR directly to the wstring constructor, it is compatible with a wchar_t*:
BSTR btest = SysAllocString(L"Test");
assert(btest != NULL);
std::wstring wtest(btest);
assert(0 == wcscmp(wtest.c_str(), btest));
Converting BSTR to std::string requires a conversion to char* first. That's lossy since BSTR stores a utf-16 encoded Unicode string. Unless you want to encode in utf-8. You'll find helper methods to do this, as well as manipulate the resulting string, in the ICU library.
go to AndroidManifest.xml and change the android:icon="@mipmap/ic_launcher" to android:icon="@mipmap/(your image name)" suppose you have a image named telugu and you want it to be set as your app icon then change android:icon="@mipmap/telugu" and you have to copy and paste your image into mipmap folder thats it its so simple as i said
If you aren't comfortable with using negative margins, check this out.
div {
position: fixed;
left: 50%;
bottom: 20px;
transform: translate(-50%, -50%);
margin: 0 auto;
}
<div>
Your Text
</div>
Especially useful when you don't know the width of the div.
align="center"
has no effect.
Since you have position:absolute
, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.
#manipulate {
position:absolute;
width:300px;
height:300px;
background:#063;
bottom:0px;
right:25%;
left:50%;
margin-left:-150px;
}
The default display
property for a table is display:table;
. The only other useful value is inline-table
. All other display
values are invalid for table elements.
There isn't an auto
option to reset it to default, although if you're working in Javascript, you can set it to an empty string, which will do the trick.
width:auto;
is valid, but isn't the default. The default width for a table is 100%
, whereas width:auto;
will make the element only take up as much width as it needs to.
min-width:auto;
isn't allowed. If you set min-width
, it must have a value, but setting it to zero is probably as good as resetting it to default.
Try this too,
private void getContactList() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if ((cur != null ? cur.getCount() : 0) > 0) {
while (cur != null && cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
if (cur.getInt(cur.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i(TAG, "Name: " + name);
Log.i(TAG, "Phone Number: " + phoneNo);
}
pCur.close();
}
}
}
if(cur!=null){
cur.close();
}
}
If you need more reference means refer this link Read ContactList
The solution depends on a few things.
Is the default value dependent on other information available at creation time? Can you wipe the database with minimal consequences?
If you answered the first question yes, then you want to use Jim's solution
If you answered the second question yes, then you want to use Daniel's solution
If you answered no to both questions, you're probably better off adding and running a new migration.
class AddDefaultMigration < ActiveRecord::Migration
def self.up
change_column :tasks, :status, :string, :default => default_value, :null => false
end
end
:string can be replaced with any type that ActiveRecord::Migration recognizes.
CPU is cheap so the redefinition of Task in Jim's solution isn't going to cause many problems. Especially in a production environment. This migration is proper way of doing it as it is loaded it and called much less often.
This is most easiest way to let NPM do everything for you
npm --add-python-to-path='true' --debug install --global windows-build-tools
This has nothing to do with using PDO, it's just that you are confusing INSERT and UPDATE.
Here's the difference:
INSERT
creates a new row. I'm guessing that you really want to create a new row.UPDATE
changes the values in an existing row, but if this is what you're doing you probably should use a WHERE clause to restrict the change to a specific row, because the default is that it applies to every row.So this will probably do what you want:
$sql = "INSERT INTO `access_users`
(`contact_first_name`,`contact_surname`,`contact_email`,`telephone`)
VALUES (:firstname, :surname, :email, :telephone);
";
Note that I've also changed the order of columns; the order of your columns must match the order of values in your VALUES clause.
MySQL also supports an alternative syntax for INSERT:
$sql = "INSERT INTO `access_users`
SET `contact_first_name` = :firstname,
`contact_surname` = :surname,
`contact_email` = :email,
`telephone` = :telephone
";
This alternative syntax looks a bit more like an UPDATE statement, but it creates a new row like INSERT. The advantage is that it's easier to match up the columns to the correct parameters.
int var1 = int.Parse(ds.Tables[0].Rows[0][3].ToString());
int var2 = int.Parse(ds.Tables[0].Rows[0][4].ToString());
I used a very similar method to @bott, but I modified it a little bit to make there be no need to resize the image:
BufferedImage img = null;
try {
img = ImageIO.read(new File("image.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
Image dimg = img.getScaledInstance(800, 508, Image.SCALE_SMOOTH);
ImageIcon imageIcon = new ImageIcon(dimg);
setContentPane(new JLabel(imageIcon));
Works every time. You can also get the width and height of the jFrame and use that in place of the 800 and 508 respectively.
Arrays can only be passed by reference, actually:
void foo(double (&bar)[10])
{
}
This prevents you from doing things like:
double arr[20];
foo(arr); // won't compile
To be able to pass an arbitrary size array to foo
, make it a template and capture the size of the array at compile time:
template<typename T, size_t N>
void foo(T (&bar)[N])
{
// use N here
}
You should seriously consider using std::vector
, or if you have a compiler that supports c++11, std::array
.
FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.
Some references:
Though you can use any other client that allows automation.
You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).
Combine WinSCP scripting capabilities with Windows Scheduler:
A typical WinSCP script for upload (with SFTP) looks like:
open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close
With FTP, just replace the sftp://
with the ftp://
and remove the -hostkey="..."
switch.
Similarly for download: How to schedule an automatic FTP download on Windows?
WinSCP can even generate a script from an imported FileZilla session.
For details, see the guide to FileZilla automation.
(I'm the author of WinSCP)
Another option, if you are using SFTP, is the psftp.exe
client from PuTTY suite.
The documentation on MSDN about the ItemsSource
of the DataGridComboBoxColumn
says that only static resources, static code or inline collections of combobox items can be bound to the ItemsSource
:
To populate the drop-down list, first set the ItemsSource property for the ComboBox by using one of the following options:
- A static resource. For more information, see StaticResource Markup Extension.
- An x:Static code entity. For more information, see x:Static Markup Extension.
- An inline collection of ComboBoxItem types.
Binding to a DataContext's property is not possible if I understand that correctly.
And indeed: When I make CompanyItems
a static property in ViewModel ...
public static ObservableCollection<CompanyItem> CompanyItems { get; set; }
... add the namespace where the ViewModel is located to the window ...
xmlns:vm="clr-namespace:DataGridComboBoxColumnApp"
... and change the binding to ...
<DataGridComboBoxColumn
ItemsSource="{Binding Source={x:Static vm:ViewModel.CompanyItems}}"
DisplayMemberPath="Name"
SelectedValuePath="ID"
SelectedValueBinding="{Binding CompanyID}" />
... then it works. But having the ItemsSource as a static property might be sometimes OK, but it is not always what I want.
This is what I have used in the past.
html, body {
height: 100%;
overflow: auto;
}
Also in the iframe
add the following style
border: 0; position:fixed; top:0; left:0; right:0; bottom:0; width:100%; height:100%
On Github, <p>
and <br/>
solves the problem.
<p>
I want to this to appear in a new line. Introduces extra line above
or
<br/>
another way
#include <iostream>
int main(){
int rows=4;
int cols=4;
int **arr;
arr = new int*[rows];
for(int i=0;i<rows;i++){
arr[i]=new int[cols];
}
// statements
for(int i=0;i<rows;i++){
delete []arr[i];
}
delete []arr;
return 0;
}
You can use either,
int i = Convert.ToInt32(TextBoxD1.Text);
or
int i = int.Parse(TextBoxD1.Text);
Step by step self explaining commands for update of feature branch with the latest code from origin "develop" branch:
git checkout develop
git pull -p
git checkout feature_branch
git merge develop
git push origin feature_branch
Maybe this repo will help for you:BasePopup
This is my repo, which is used to solve various problems of PopupWindow.
In the case of using the library, if you need to blur the background, just call setBlurBackgroundEnable(true).
See the wiki for more details.(Language in zh-cn)
The problem was that I used ajax to post the message to the server, when I used a direct link to download the file everything worked fine.
I used this other Stackoverflow Q&A material instead, it worked great for me:
For who is searching to do it without creating a background sector, just add those lines to the TextView
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
Also to make it selectable use:
android:textIsSelectable="true"
And in PHPUnit Selenium test it's like this:
$text = $this->byCssSelector('.some-class-nmae')->attribute('innerHTML');
I have handled these in a simple code. You can download a working demo from here
For your case, these very possible. I will take you step by step how you can upload a file to the server using AJAX jquery.
First let's us create an HTML file to add the following form file element as shown below.
<form action="" id="formContent" method="post" enctype="multipart/form-data" >
<input type="file" name="file" required id="upload">
<button class="submitI" >Upload Image</button>
</form>
Secondly create a jquery.js file and add the following code to handle our file submission to the server
$("#formContent").submit(function(e){
e.preventDefault();
var formdata = new FormData(this);
$.ajax({
url: "ajax_upload_image.php",
type: "POST",
data: formdata,
mimeTypes:"multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(){
alert("file successfully submitted");
},error: function(){
alert("okey");
}
});
});
});
There you are done . View more
Based on the Microsoft support KBs, this can occur if TCP/IP is damaged or is not bound to your dial-up adapter.You can try reinstalling or resetting TCP/IP as follows:
Reset TCP/IP to Original Configuration- Using the NetShell utility,
type this command (in CommandLine): netsh int ip reset [file_name.txt]
,
[file_name.txt] is the name of the file where the actions taken by
NetShell are record, for example netsh hint ip reset fixtcpip.txt.
Remove and re-install NIC – Open Controller and select System. Click Hardware tab and select devices. Double-click on Network Adapter and right-click on the NIC, select Uninstall. Restart the computer and the Windows should auto detect the NIC and re-install it.
Hope it could help.
One subtle but significant difference is in the way the two libraries approach scope. Mustache will fall back to parent scope if it can't find a variable within the current context; Handlebars will return a blank string.
This is barely mentioned in the GitHub README, where there's one line for it:
Handlebars deviates from Mustache slightly in that it does not perform recursive lookup by default.
However, as noted there, there is a flag to make Handlebars behave in the same way as Mustache -- but it affects performance.
This has an effect on the way you can use #
variables as conditionals.
For example in Mustache you can do this:
{{#variable}}<span class="text">{{variable}}</span>{{/variable}}
It basically means "if variable exists and is truthy, print a span with the variable in it". But in Handlebars, you would either have to:
{{this}}
instead{{../variable}}
to get back out to relevant scopevariable
value within the parent variable
objectMore details on this, if you want them, here.
It's not possible. You need pull all repository or nothing.
For the point that 'returns the value as soon as you find the first row/record that meets the requirements and NOT iterating other rows', the following code would work:
def pd_iter_func(df):
for row in df.itertuples():
# Define your criteria here
if row.A > 4 and row.B > 3:
return row
It is more efficient than Boolean Indexing
when it comes to a large dataframe.
To make the function above more applicable, one can implements lambda functions:
def pd_iter_func(df: DataFrame, criteria: Callable[[NamedTuple], bool]) -> Optional[NamedTuple]:
for row in df.itertuples():
if criteria(row):
return row
pd_iter_func(df, lambda row: row.A > 4 and row.B > 3)
As mentioned in the answer to the 'mirror' question, pandas.Series.idxmax
would also be a nice choice.
def pd_idxmax_func(df, mask):
return df.loc[mask.idxmax()]
pd_idxmax_func(df, (df.A > 4) & (df.B > 3))