Yes, you can use the CSS feature named @font-face. It has only been officially approved in CSS3, but been proposed and implemented in CSS2 and has been supported in IE for quite a long time.
You declare it in the CSS like this:
@font-face { font-family: Delicious; src: url('Delicious-Roman.otf'); }
@font-face { font-family: Delicious; font-weight: bold; src: url('Delicious-Bold.otf');}
Then, you can just reference it like the other standard fonts:
h3 { font-family: Delicious, sans-serif; }
So, in this case,
<html>
<head>
<style>
@font-face { font-family: JuneBug; src: url('JUNEBUG.TTF'); }
h1 {
font-family: JuneBug
}
</style>
</head>
<body>
<h1>Hey, June</h1>
</body>
</html>
And you just need to put the JUNEBUG.TFF in the same location as the html file.
I downloaded the font from the dafont.com website:
we had similar header issue with Amazon (AWS) S3 presigned Post failing on some browsers.
point was to tell bucket CORS to expose header <ExposeHeader>Access-Control-Allow-Origin</ExposeHeader>
more details in this answer: https://stackoverflow.com/a/37465080/473040
WOFF 2.0, based on the Brotli compression algorithm and other improvements over WOFF 1.0 giving more than 30 % reduction in file size, is supported in Chrome, Opera, and Firefox.
http://en.wikipedia.org/wiki/Web_Open_Font_Format http://en.wikipedia.org/wiki/Brotli
http://sth.name/2014/09/03/Speed-up-webfonts/ has an example on how to use it.
Basically you add a src url to the woff2 file and specify the woff2 format. It is important to have this before the woff-format: the browser will use the first format that it supports.
Multiple variations of a font family can be declared by changing the font-weight and src property of @font-face rule.
/* Regular Weight */
@font-face {
font-family: Montserrat;
src: url("../fonts/Montserrat-Regular.ttf");
}
/* SemiBold (600) Weight */
@font-face {
font-family: Montserrat;
src: url("../fonts/Montserrat-SemiBold.ttf");
font-weight: 600;
}
/* Bold Weight */
@font-face {
font-family: Montserrat;
src: url("../fonts/Montserrat-Bold.ttf");
font-weight: bold;
}
Declared rules can be used by following
/* Regular */
font-family: Montserrat;
/* Semi Bold */
font-family: Montserrat;
font-weght: 600;
/* Bold */
font-family: Montserrat;
font-weight: bold;
I researched a bit into SVG webfonts and font creation, in my eyes if you want to "add" fonts to font-awesome already existing font you need to do the following:
go to inkscape and create a glyph, save it as SVG so you could read the code, make sure to assign it a unicode character which is not currently used so it will not conflict with any of the existing glyphs in the font. this could be hard so i think a better simpler approad would be replacing an existing glyph with your own (just choose one you dont use, copy the first part:
Save the svg then convert it to web-font using any online converter so your webfont would work in all browsers.
once this is done, you should have either an SVG with one of the glyphs replaced in which case youre done. if not you need to create the CSS for your new glyph, in this case try and reuse FAs existing CSS, and only add
>##CSS##
>.FA.NEW-GLYPH:after {
>content:'WHATEVER AVAILABLE UNICODE CHARACTER YOU FOUND'
>(other conditions should be copied from other fonts)
>}
After running into the issue, I found out that my WOFF file was not done properly, I sent a new TTF to FontSquirrel which gave me a proper WOFF that was smooth in Firefox without adding any extra CSS to it.
There is one rule that is set by font-awesome.css
, which you need to override.
You should set overrides in your CSS files rather than inline, but essentially, the icon-ok class is being set to vertical-align: baseline;
by default and which I've corrected here:
<button id="whatever" class="btn btn-large btn-primary" name="Continue" type="submit">
<span>Continue</span>
<i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>
Example here: http://jsfiddle.net/fPXFY/4/ and the output of which is:
I've downsized the font-size of the icon above in this instance to 30px
, as it feels too big at 40px
for the size of the button, but this is purely a personal viewpoint. You could increase the padding on the button to compensate if required:
<button id="whaever" class="btn btn-large btn-primary" style="padding: 20px;" name="Continue" type="submit">
<span>Continue</span>
<i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>
Producing: http://jsfiddle.net/fPXFY/5/ the output of which is:
You can try fontsforweb.com where fonts are working for all browsers, because they are provided in TTF, WOFF and EOT formats together with CSS code ready to be pasted on your page i.e.
@font-face{
font-family: "gothambold1";
src: url('http://fontsforweb.com/public/fonts/5903/gothambold1.eot');
src: local("Gotham-Bold"), url('http://fontsforweb.com/public/fonts/5903/gothambold1.woff') format("woff"), url('http://fontsforweb.com/public/fonts/5903/gothambold1.ttf') format("truetype");
}
.fontsforweb_fontid_5903 {
font-family: "gothambold1";
}
or you can download them zipped in a package with CSS file attached
then just add class to any element to apply that font i.e.
<h2 class="fontsforweb_fontid_5903">This will be written with Gotham Bold font and will work in all browsers</h2>
See it working: http://jsfiddle.net/SD4MP/
function formatNumberCapture () {
$('#input_id').on('keyup', function () {
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
;
});
});
You can try this, it works for me
nil means absence of value while NULL represent No Object,
NSArray *array = @[@"Hello World !", @101,[NSNULL null] ];
Here [NSNULL null] is an object which means no object, at the same time you cannot add nil to indicate absence of object.
you can use both nil and [NSNUll null] for checking too.
For reference and adding to answers citing mefa, it might worth to take a look on the implementation of mefa::rep.data.frame()
in case you don't want to include the whole package:
> data <- data.frame(a=letters[1:3], b=letters[4:6])
> data
a b
1 a d
2 b e
3 c f
> as.data.frame(lapply(data, rep, 2))
a b
1 a d
2 b e
3 c f
4 a d
5 b e
6 c f
The accepted answer will work if you can easily reproduce the issue. However, as a matter of best practice, you should be catching any exceptions (and logging) that are executed within a task. Otherwise, your application will crash if anything unexpected occurs within the task.
Task.Factory.StartNew(x=>
throw new Exception("I didn't account for this");
)
However, if we do this, at least the application does not crash.
Task.Factory.StartNew(x=>
try {
throw new Exception("I didn't account for this");
}
catch(Exception ex) {
//Log ex
}
)
Polymorphism is this:
class Cup {
int capacity
}
class TeaCup : Cup {
string flavour
}
class CoffeeCup : Cup {
string brand
}
Cup c = new CoffeeCup();
public int measure(Cup c) {
return c.capacity
}
you can pass just a Cup instead of a specific instance. This aids in generality because you don't have to provide a specific measure() instance per each cup type
On MDPI devices, the status bar is 25px. We can use this as the base and multiply it by the density (rounded up) to get the status bar height on any device:
int statusBarHeight = Math.ceil(25 * context.getResources().getDisplayMetrics().density);
For reference: ldpi=.75, mdpi=1, hdpi=1.5, xhdpi=2
If you use the -i
option you need to provide an extension for your backups.
If you have:
File1.txt
File2.cfg
The command (note the lack of space between -i
and ''
and the -e
to make it work on new versions of Mac and on GNU):
sed -i'.original' -e 's/old_link/new_link/g' *
Create 2 backup files like:
File1.txt.original
File2.cfg.original
There is no portable way to avoid making backup files because it is impossible to find a mix of sed commands that works on all cases:
sed -i -e ...
- does not work on OS X as it creates -e
backupssed -i'' -e ...
- does not work on OS X 10.6 but works on 10.9+sed -i '' -e ...
- not working on GNUNote Given that there isn't a sed command working on all platforms, you can try to use another command to achieve the same result.
E.g., perl -i -pe's/old_link/new_link/g' *
Just add the following in your connection string:
MultipleActiveResultSets=True;
This provides you with the possibility of adding conditions on the rows and then change all the cells of a specific column corresponding to those rows:
df.loc[(df['issueid'] == '001'), 'industry'] = str('yyy')
About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :
Basically, flatMap
is the equivalent of Promise.then
.
For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay
operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)
Spawning new processes on the server using exec()
or directly on another server using curl doesn't scale all that well at all, if we go for exec you are basically filling your server with long running processes which can be handled by other non web facing servers, and using curl ties up another server unless you build in some sort of load balancing.
I have used Gearman in a few situations and I find it better for this sort of use case. I can use a single job queue server to basically handle queuing of all the jobs needing to be done by the server and spin up worker servers, each of which can run as many instances of the worker process as needed, and scale up the number of worker servers as needed and spin them down when not needed. It also let's me shut down the worker processes entirely when needed and queues the jobs up until the workers come back online.
In 11g you can use the undocumented function wm_concat like this:
select wm_concat(distinct name) as names from demotable group by group_id
as described in the link, it only returns (as I mentioned) 15 results. (fwiw, I checked these results against the 4000 I'm supposed to get, and these 15 are the same as the first 15 of the 4000)
That's because mysql restricts the length of the data returned by group concat to the value set in @@group_concat_max_len as soon as it gets to the that amount it truncates and returns what it's gotten so far.
You can set @@group_concat_max_len in a few different ways. reference The mysql documentation...
If you're happy not not supporting IE or pre-Chromium Edge (which might be fine if you are using this for progressive enhancement), you can use :placeholder-shown
as Berend has said. Note that for Chrome and Safari you actually need a non-empty placeholder for this to work, though a space works.
*,_x000D_
::after,_x000D_
::before {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
label.floating-label {_x000D_
display: block;_x000D_
position: relative;_x000D_
height: 2.2em;_x000D_
margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
label.floating-label input {_x000D_
font-size: 1em;_x000D_
height: 2.2em;_x000D_
padding-top: 0.7em;_x000D_
line-height: 1.5;_x000D_
color: #495057;_x000D_
background-color: #fff;_x000D_
background-clip: padding-box;_x000D_
border: 1px solid #ced4da;_x000D_
border-radius: 0.25rem;_x000D_
transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;_x000D_
}_x000D_
_x000D_
label.floating-label input:focus {_x000D_
color: #495057;_x000D_
background-color: #fff;_x000D_
border-color: #80bdff;_x000D_
outline: 0;_x000D_
box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);_x000D_
}_x000D_
_x000D_
label.floating-label input+span {_x000D_
position: absolute;_x000D_
top: 0em;_x000D_
left: 0;_x000D_
display: block;_x000D_
width: 100%;_x000D_
font-size: 0.66em;_x000D_
line-height: 1.5;_x000D_
color: #495057;_x000D_
border: 1px solid transparent;_x000D_
border-radius: 0.25rem;_x000D_
transition: font-size 0.1s ease-in-out, top 0.1s ease-in-out;_x000D_
}_x000D_
_x000D_
label.floating-label input:placeholder-shown {_x000D_
padding-top: 0;_x000D_
font-size: 1em;_x000D_
}_x000D_
_x000D_
label.floating-label input:placeholder-shown+span {_x000D_
top: 0.3em;_x000D_
font-size: 1em;_x000D_
}
_x000D_
<fieldset>_x000D_
<legend>_x000D_
Floating labels example (no-JS)_x000D_
</legend>_x000D_
<label class="floating-label">_x000D_
<input type="text" placeholder=" ">_x000D_
<span>Username</span>_x000D_
</label>_x000D_
<label class="floating-label">_x000D_
<input type="Password" placeholder=" ">_x000D_
<span>Password</span>_x000D_
</label>_x000D_
</fieldset>_x000D_
<p>_x000D_
Inspired by Bootstrap's <a href="https://getbootstrap.com/docs/4.0/examples/floating-labels/">floating labels</a>._x000D_
</p>
_x000D_
I like to use np.vectorize
for such tasks. Consider the following:
>>> # function which returns True when constraints are satisfied.
>>> func = lambda d: d >= r and d<= (r+dr)
>>>
>>> # Apply constraints element-wise to the dists array.
>>> result = np.vectorize(func)(dists)
>>>
>>> result = np.where(result) # Get output.
You can also use np.argwhere
instead of np.where
for clear output. But that is your call :)
Hope it helps.
In SQL Server, you can use this query:
USE Database_name
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='Table_Name';
And do not forget to replace Database_name
and Table_name
with the exact names of your database and table names.
With pure javascript:
var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i <= buttonsCount; i += 1) {
buttons[i].onclick = function(e) {
alert(this.id);
};
}?
When this is in a python console if you update a module to be able to use it through the console does not help reset, you must use a
import importlib
and
importlib.reload (*module*)
likely to solve your problem
WebElement.click()
click is found to be not working if the page is zoomed in or out.
I had my page zoomed out to 85%.
If you reset the page zooming in browser using (ctrl
+ +
and ctrl
+ -
) to 100%, clicks will start working.
Issue was found with chrome version 86.0.4240.111
For all of you who believe the myth that temp variables are in memory only
First, the table variable is NOT necessarily memory resident. Under memory pressure, the pages belonging to a table variable can be pushed out to tempdb.
Read the article here: TempDB:: Table variable vs local temporary table
-L
returns true if the "file" exists and is a symbolic link (the linked file may or may not exist). You want -f
(returns true if file exists and is a regular file) or maybe just -e
(returns true if file exists regardless of type).
According to the GNU manpage, -h
is identical to -L
, but according to the BSD manpage, it should not be used:
-h file
True if file exists and is a symbolic link. This operator is retained for compatibility with previous versions of this program. Do not rely on its existence; use -L instead.
Align vertically is difficult because text descent and ascent happened, lots of guys used Paint.getTextBounds() to retrieve the TextWidth and TextHeight, but it doesn't make the text center very much. Here we can use Paint.measureText() to calculate the TextWidth, the TextHeight we simply do subtracting with descent and ascent, then we got the most approach TextSize, the following work is fairly easy for each other.
// the Paint instance(should be assign as a field of class).
Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setTextSize(getResources().getDimension(R.dimen.btn_textsize));
// the display area.
Rect areaRect = new Rect(0, 0, 240, 60);
// draw the background style (pure color or image)
mPaint.setColor(Color.BLACK);
yourCanvas.drawRect(areaRect, mPaint);
String pageTitle = "????";
RectF bounds = new RectF(areaRect);
// measure text width
bounds.right = mPaint.measureText(pageTitle, 0, pageTitle.length());
// measure text height
bounds.bottom = mPaint.descent() - mPaint.ascent();
bounds.left += (areaRect.width() - bounds.right) / 2.0f;
bounds.top += (areaRect.height() - bounds.bottom) / 2.0f;
mPaint.setColor(Color.WHITE);
yourCanvas.drawText(pageTitle, bounds.left, bounds.top - mPaint.ascent(), mPaint);
By the way, we highly recommend use RectF rather than Rect because the positions need more accurate values, in my experience, RectF done the top&bottom deviation just one pixel on xhdpi device, Rect would be two more.
Do you have Zend, IonCube, or xDebug installed? If so, that is probably where you are getting this error from.
I ran into this a few years ago, and it ended up being Zend putting that limit there, not PHP. Of course removing it will let you go past the 100 iterations, but you will eventually hit the memory limits.
Try this
//field "search";
var pattern = /[?&]search=/;
var URL = location.search;
if(pattern.test(URL))
{
alert("Found :)");
}else{
alert("Not found!");
}
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
_x000D_
<meta charset="utf-8">_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<meta name="description" content="">_x000D_
<meta name="author" content="">_x000D_
_x000D_
<title>3 Col Portfolio - Start Bootstrap Template</title>_x000D_
_x000D_
<!-- Bootstrap Core CSS -->_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->_x000D_
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->_x000D_
<!--[if lt IE 9]>_x000D_
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>_x000D_
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>_x000D_
<![endif]-->_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<!-- Navigation -->_x000D_
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">_x000D_
<div class="container">_x000D_
<!-- Brand and toggle get grouped for better mobile display -->_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">_x000D_
<span class="sr-only">Toggle navigation</span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="#">Start Bootstrap</a>_x000D_
</div>_x000D_
<!-- Collect the nav links, forms, and other content for toggling -->_x000D_
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
<ul class="nav navbar-nav">_x000D_
<li>_x000D_
<a href="#">About</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">Services</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">Contact</a>_x000D_
</li>_x000D_
</ul>_x000D_
<form class="navbar-form navbar-right">_x000D_
<div class="input-group">_x000D_
<input type="text" name="keyword" placeholder="search..." class="form-control">_x000D_
<span class="input-group-btn">_x000D_
<button class="btn btn-default">Go</button>_x000D_
</span>_x000D_
</div>_x000D_
</form>_x000D_
</div>_x000D_
<!-- /.navbar-collapse -->_x000D_
</div>_x000D_
<!-- /.container -->_x000D_
</nav>_x000D_
_x000D_
<!-- Page Content -->_x000D_
<div class="container">_x000D_
_x000D_
<!-- Page Header -->_x000D_
<div class="row">_x000D_
<div class="col-lg-12">_x000D_
<h1 class="page-header">Page Heading_x000D_
<small>Secondary Text</small>_x000D_
</h1>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
_x000D_
<!-- Projects Row -->_x000D_
<div class="row">_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
_x000D_
<!-- Projects Row -->_x000D_
<div class="row">_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
_x000D_
<!-- Projects Row -->_x000D_
<div class="row">_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
_x000D_
<!-- Projects Row -->_x000D_
<div class="row">_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
<div class="col-md-3 portfolio-item">_x000D_
<a href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
</a>_x000D_
<h3>_x000D_
<a href="#">Project Name</a>_x000D_
</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
_x000D_
<hr>_x000D_
_x000D_
<!-- Pagination -->_x000D_
<div class="row text-center">_x000D_
<div class="col-lg-12">_x000D_
<ul class="pagination">_x000D_
<li>_x000D_
<a href="#">«</a>_x000D_
</li>_x000D_
<li class="active">_x000D_
<a href="#">1</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">2</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">3</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">4</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">5</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">»</a>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
</div>_x000D_
<!-- Footer -->_x000D_
<footer>_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col-lg-4 col-md-4 col-sm-4">_x000D_
<h3>About</h3>_x000D_
<ul>_x000D_
<li>_x000D_
<i class="glyphicon glyphicon-home"></i> Your company address here_x000D_
</li>_x000D_
<li>_x000D_
<i class="glyphicon glyphicon-earphone"></i> 0982.808.065_x000D_
</li>_x000D_
<li>_x000D_
<i class="glyphicon glyphicon-envelope"></i> [email protected]_x000D_
</li>_x000D_
<li>_x000D_
<i class="glyphicon glyphicon-flag"></i> <a href="#">Fan page</a>_x000D_
</li>_x000D_
<li>_x000D_
<i class="glyphicon glyphicon-time"></i> 08:00-18:00 Monday to Friday_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
<div class="col-lg-4 col-md-4 col-sm-4">_x000D_
<h3>Support</h3>_x000D_
<ul>_x000D_
<li>_x000D_
<a href="#" class="link">Terms of Service</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#" class="link">Privacy policy</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#" class="link">Warranty commitment</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#" class="link">Site map</a>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
<div class="col-lg-4 col-md-4 col-sm-4">_x000D_
<h3>Other</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod_x000D_
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo_x000D_
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse_x000D_
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non_x000D_
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.row -->_x000D_
</footer>_x000D_
_x000D_
<!-- /.container -->_x000D_
_x000D_
<!-- jQuery -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<!-- Bootstrap Core JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
$(document).ready(function() {
$(document)[0].oncontextmenu = function() { return false; }
$(document).mousedown(function(e) {
if( e.button == 2 ) {
alert('Sorry, this functionality is disabled!');
return false;
} else {
return true;
}
});
});
If you want to disable it only on image click the instead of $(document).mousedown
use $("#yourimage").mousedown
A previous answer using LPAD()
is optimal. However, in the event you want to do special or advanced processing, here is a method that allows more iterative control over the padding. Also serves as an example using other constructs to achieve the same thing.
UPDATE
mytable
SET
mycolumn = CONCAT(
REPEAT(
"0",
8 - LENGTH(mycolumn)
),
mycolumn
)
WHERE
LENGTH(mycolumn) < 8;
Create a folder ${USER_HOME}/.mvn
and put a file called maven.config
in it.
The content should be:
-Dmaven.wagon.http.ssl.insecure=true
-Dmaven.wagon.http.ssl.allowall=true
-Dmaven.wagon.http.ssl.ignore.validity.dates=true
Hope this helps.
You can use \n
for new line and \t
for tabs. Also, extra spaces/tabs are just copied the way you write them in Strings.xml
so just give a couple of spaces where ever you want them.
A better way to reach this would probably be using padding/margin in your view xml and splitting up your long text in different strings in your string.xml
In HTML5, using an a
element without an href
attribute is valid. It is considered to be a "placeholder hyperlink."
Example:
<a>previous</a>
Look for "placeholder hyperlink" on the w3c anchor tag reference page: https://www.w3.org/TR/2016/REC-html51-20161101/textlevel-semantics.html#the-a-element.
And it is also mentioned on the wiki here: https://www.w3.org/wiki/Elements/a
A placeholder link is for cases where you want to use an anchor element, but not have it navigate anywhere. This comes in handy for marking up the current page in a navigation menu or breadcrumb trail. (The old approach would have been to either use a span tag or an anchor tag with a class named "active" or "current" to style it and JavaScript to cancel navigation.)
A placeholder link is also useful in cases where you want to dynamically set the destination of the link via JavaScript at runtime. You simply set the value of the href attribute, and the anchor tag becomes clickable.
See also:
Generally, instances of classes that deal with I/O should be closed after you're finished with them. So at the end of your code you could add in.close()
.
If you're OK with a JavaScript solution, there's a jQuery plug-in to do this in a cross-browser fashion - see http://azgtech.wordpress.com/2009/07/26/text-overflow-ellipsis-for-firefox-via-jquery/
To avoid the error, use extract string:
<string name="travels_tours_pvt_ltd"><![CDATA[Travels & Tours (Pvt) Ltd.]]></string>
Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML.
Adding a value of selected
to the item we want to appear as a header forces it to show in the first place as a placeholder.
Something like:
<option selected disabled>Choose here</option>
The complete markup should be along these lines:
<select>
<option selected disabled>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
You can take a look at this fiddle, and here's the result:
If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden
attribute like so:
<select>
<option selected disabled hidden>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
Check the fiddle here and the screenshot below.
Here is the solution:
<select>
<option style="display:none;" selected>Select language</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
Here's a detailed explanation about the calculation of MaxClients and MaxRequestsPerChild
ServerLimit 16
StartServers 2
MaxClients 200
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
First of all, whenever an apache is started, it will start 2 child processes which is determined by StartServers
parameter. Then each process will start 25 threads determined by ThreadsPerChild
parameter so this means 2 process can service only 50 concurrent connections/clients i.e. 25x2=50. Now if more concurrent users comes, then another child process will start, that can service another 25 users. But how many child processes can be started is controlled by ServerLimit
parameter, this means that in the configuration above, I can have 16 child processes in total, with each child process can handle 25 thread, in total handling 16x25=400 concurrent users. But if number defined in MaxClients
is less which is 200 here, then this means that after 8 child processes, no extra process will start since we have defined an upper cap of MaxClients
. This also means that if I set MaxClients
to 1000, after 16 child processes and 400 connections, no extra process will start and we cannot service more than 400 concurrent clients even if we have increase the MaxClient
parameter. In this case, we need to also increase ServerLimit
to 1000/25 i.e. MaxClients/ThreadsPerChild=40
So this is the optmized configuration to server 1000 clients
<IfModule mpm_worker_module>
ServerLimit 40
StartServers 2
MaxClients 1000
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
MaxRequestsPerChild 0
</IfModule>
VSCode will never refresh the file if you have changes in that file that are not saved to disk. However, if the file is open and does not have changes, it will replace with the changes on disk, that is true.
There is currently no way to disable this behaviour.
It's not necessary to query the object first, you can attach it to the context by its id. Like this:
var employer = new Employ { Id = 1 };
ctx.Employ.Attach(employer);
ctx.Employ.Remove(employer);
ctx.SaveChanges();
Alternatively, you can set the attached entry's state to deleted :
var employer = new Employ { Id = 1 };
ctx.Entry(employer).State = EntityState.Deleted;
ctx.SaveChanges();
Use FirstOrDefault insted of SingleOrDefault..
SingleOrDefault returns a SINGLE element or null if no element is found. If 2 elements are found in your Enumerable then it throws the exception you are seeing
FirstOrDefault returns the FIRST element it finds or null if no element is found. so if there are 2 elements that match your predicate the second one is ignored
public int GetPackage(int id,int emp)
{
int getpackages=Convert.ToInt32(EmployerSubscriptionPackage.GetAllData().Where(x
=> x.SubscriptionPackageID ==`enter code here` id && x.EmployerID==emp ).FirstOrDefault().ID);
return getpackages;
}
1. var EmployerId = Convert.ToInt32(Session["EmployerId"]);
var getpackage = GetPackage(employerSubscription.ID, EmployerId);
Edit: The bitset stuff below is maybe an interesting read, but the answer itself is a bit dated. Some of this functionality is changing around in 2.x. Also Slawek points out in another answer that the terms
query is an easy way to DRY up the search in this case. Refactored at the end for current best practices. —nz
You'll probably want a Bool Query (or more likely Filter alongside another query), with a should
clause.
The bool query has three main properties: must
, should
, and must_not
. Each of these accepts another query, or array of queries. The clause names are fairly self-explanatory; in your case, the should
clause may specify a list filters, a match against any one of which will return the document you're looking for.
From the docs:
In a boolean query with no
must
clauses, one or moreshould
clauses must match a document. The minimum number of should clauses to match can be set using theminimum_should_match
parameter.
Here's an example of what that Bool query might look like in isolation:
{
"bool": {
"should": [
{ "term": { "tag": "c" }},
{ "term": { "tag": "d" }}
]
}
}
And here's another example of that Bool query as a filter within a more general-purpose Filtered Query:
{
"filtered": {
"query": {
"match": { "title": "hello world" }
},
"filter": {
"bool": {
"should": [
{ "term": { "tag": "c" }},
{ "term": { "tag": "d" }}
]
}
}
}
}
Whether you use Bool as a query (e.g., to influence the score of matches), or as a filter (e.g., to reduce the hits that are then being scored or post-filtered) is subjective, depending on your requirements.
It is generally preferable to use Bool in favor of an Or Filter, unless you have a reason to use And/Or/Not (such reasons do exist). The Elasticsearch blog has more information about the different implementations of each, and good examples of when you might prefer Bool over And/Or/Not, and vice-versa.
Elasticsearch blog: All About Elasticsearch Filter Bitsets
Update with a refactored query...
Now, with all of that out of the way, the terms
query is a DRYer version of all of the above. It does the right thing with respect to the type of query under the hood, it behaves the same as the bool
+ should
using the minimum_should_match
options, and overall is a bit more terse.
Here's that last query refactored a bit:
{
"filtered": {
"query": {
"match": { "title": "hello world" }
},
"filter": {
"terms": {
"tag": [ "c", "d" ],
"minimum_should_match": 1
}
}
}
}
This question has been an active area of research in the last years. The main idea is to do a preprocessing on the graph once, to speed up all following queries. With this additional information itineraries can be computed very fast. Still, Dijkstra's Algorithm is the basis for all optimisations.
Arachnid described the usage of bidirectional search and edge pruning based on hierarchical information. These speedup techniques work quite well, but the most recent algorithms outperform these techniques by all means. With current algorithms a shortest paths can be computed in considerable less time than one millisecond on a continental road network. A fast implementation of the unmodified algorithm of Dijkstra needs about 10 seconds.
The article Engineering Fast Route Planning Algorithms gives an overview of the progress of research in that field. See the references of that paper for further information.
The fastest known algorithms do not use information about the hierarchical status of the road in the data, i.e. if it is a highway or a local road. Instead, they compute in a preprocessing step an own hierarchy that optimised to speed up route planning. This precomputation can then be used to prune the search: Far away from start and destination slow roads need not be considered during Dijkstra's Algorithm. The benefits are very good performance and a correctness guarantee for the result.
The first optimised route planning algorithms dealt only with static road networks, that means an edge in the graph has a fixed cost value. This not true in practice, since we want to take dynamic information like traffic jams or vehicle dependent restrictrions into account. Latest algorithms can also deal with such issues, but there are still problems to solve and the research is going on.
If you need the shortest path distances to compute a solution for the TSP, then you are probably interested in matrices that contain all distances between your sources and destinations. For this you could consider Computing Many-to-Many Shortest Paths Using Highway Hierarchies. Note, that this has been improved by newer approaches in the last 2 years.
What you may actually want to use is an Iterable
that can return a fresh Iterator
multiple times by calling iterator()
.
//A function that needs to iterate multiple times can be given one Iterable:
public void func(Iterable<Type> ible) {
Iterator<Type> it = ible.iterator(); //Gets an iterator
while (it.hasNext()) {
it.next();
}
it = ible.iterator(); //Gets a NEW iterator, also from the beginning
while (it.hasNext()) {
it.next();
}
}
You must define what the iterator()
method does just once beforehand:
void main() {
LinkedList<String> list; //This could be any type of object that has an iterator
//Define an Iterable that knows how to retrieve a fresh iterator
Iterable<Type> ible = new Iterable<Type>() {
@Override
public Iterator<Type> iterator() {
return list.listIterator(); //Define how to get a fresh iterator from any object
}
};
//Now with a single instance of an Iterable,
func(ible); //you can iterate through it multiple times.
}
Ask Hans suggested, you can use Roslyn to dynamically create classes.
Full source:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace RoslynDemo1
{
class Program
{
static void Main(string[] args)
{
var fields = new List<Field>()
{
new Field("EmployeeID","int"),
new Field("EmployeeName","String"),
new Field("Designation","String")
};
var employeeClass = CreateClass(fields, "Employee");
dynamic employee1 = Activator.CreateInstance(employeeClass);
employee1.EmployeeID = 4213;
employee1.EmployeeName = "Wendy Tailor";
employee1.Designation = "Engineering Manager";
dynamic employee2 = Activator.CreateInstance(employeeClass);
employee2.EmployeeID = 3510;
employee2.EmployeeName = "John Gibson";
employee2.Designation = "Software Engineer";
Console.WriteLine($"{employee1.EmployeeName}");
Console.WriteLine($"{employee2.EmployeeName}");
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
public static Type CreateClass(List<Field> fields, string newClassName, string newNamespace = "Magic")
{
var fieldsCode = fields
.Select(field => $"public {field.FieldType} {field.FieldName};")
.ToString(Environment.NewLine);
var classCode = $@"
using System;
namespace {newNamespace}
{{
public class {newClassName}
{{
public {newClassName}()
{{
}}
{fieldsCode}
}}
}}
".Trim();
classCode = FormatUsingRoslyn(classCode);
var assemblies = new[]
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
};
/*
var assemblies = AppDomain
.CurrentDomain
.GetAssemblies()
.Where(a => !string.IsNullOrEmpty(a.Location))
.Select(a => MetadataReference.CreateFromFile(a.Location))
.ToArray();
*/
var syntaxTree = CSharpSyntaxTree.ParseText(classCode);
var compilation = CSharpCompilation
.Create(newNamespace)
.AddSyntaxTrees(syntaxTree)
.AddReferences(assemblies)
.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using (var ms = new MemoryStream())
{
var result = compilation.Emit(ms);
//compilation.Emit($"C:\\Temp\\{newNamespace}.dll");
if (result.Success)
{
ms.Seek(0, SeekOrigin.Begin);
Assembly assembly = Assembly.Load(ms.ToArray());
var newTypeFullName = $"{newNamespace}.{newClassName}";
var type = assembly.GetType(newTypeFullName);
return type;
}
else
{
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
foreach (Diagnostic diagnostic in failures)
{
Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
}
return null;
}
}
}
public static string FormatUsingRoslyn(string csCode)
{
var tree = CSharpSyntaxTree.ParseText(csCode);
var root = tree.GetRoot().NormalizeWhitespace();
var result = root.ToFullString();
return result;
}
}
public class Field
{
public string FieldName;
public string FieldType;
public Field(string fieldName, string fieldType)
{
FieldName = fieldName;
FieldType = fieldType;
}
}
public static class Extensions
{
public static string ToString(this IEnumerable<string> list, string separator)
{
string result = string.Join(separator, list);
return result;
}
}
}
The concept of POD and the type trait std::is_pod
will be deprecated in C++20. See this question for further information.
It works:
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
Just a bit more helpful, enable and disable
$(window).on('beforeunload.myPluginName', false); // or use function() instead of false
$(window).off('beforeunload.myPluginName');
$timeFirst = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;
You will then be able to use the seconds to find minutes, hours, days, etc.
The fluent way:
public static String fileNameWithOutExt (String fileName) {
return Optional.of(fileName.lastIndexOf(".")).filter(i-> i >= 0)
.map(i-> fileName.substring(0, i)).orElse(fileName);
}
Your ProcExit label is your place where you release all the resources whether an error happened or not. For instance:
Public Sub SubA()
On Error Goto ProcError
Connection.Open
Open File for Writing
SomePreciousResource.GrabIt
ProcExit:
Connection.Close
Connection = Nothing
Close File
SomePreciousResource.Release
Exit Sub
ProcError:
MsgBox Err.Description
Resume ProcExit
End Sub
Sometimes it happen what you copy paste code from another project fro example you copy
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="256dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@android:color/white"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:itemTextColor="@color/colorDrawerItems"
app:menu="@menu/activity_main_drawer" />
Unfortunately Android studio not always show dependency error, but what happen is that class NavigationView
is missing because implementation 'com.android.support:design
not added to the project
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
var validNavigation = false;
function endSession() {
// Browser or broswer tab is closed
// Do sth here ...
alert("bye");
}
function wireUpEvents() {
/*
* For a list of events that triggers onbeforeunload on IE
* check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
*/
window.onbeforeunload = function() {
if (!validNavigation) {
var ref="load";
$.ajax({
type: 'get',
async: false,
url: 'logout.php',
data:
{
ref:ref
},
success:function(data)
{
console.log(data);
}
});
endSession();
}
}
// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
}
// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();
});
</script>
This is used for when logged in user close the browser or browser tab it will automatically logout the user account...
Above answers are pretty sufficient. Additional to the onChange
, if you upload a file using drag and drop events, you can get the file in drop
event by accessing eventArgs.dataTransfer.files
.
You can remove the reference using null
.
Let's say You have class A
:
A a = new A();
a=null;
last statement will remove the reference of the object a
and that object will be "garbage collected" by JVM.
It is one of the easiest ways to do this.
Lumisoft.net has both IMAP client and server code that you can use.
I've used it to download email from Gmail. The object model isn't the best, but it is workable, and seems to be rather flexible and stable.
Here is the partial result of my spike to use it. It fetches the first 10 headers with envelopes, and then fetches the full message:
using (var client = new IMAP_Client())
{
client.Connect(_hostname, _port, _useSsl);
client.Authenticate(_username, _password);
client.SelectFolder("INBOX");
var sequence = new IMAP_SequenceSet();
sequence.Parse("0:10");
var fetchItems = client.FetchMessages(sequence, IMAP_FetchItem_Flags.Envelope | IMAP_FetchItlags.UID,
false, true);
foreach (var fetchItem in fetchItems)
{
Console.Out.WriteLine("message.UID = {0}", fetchItem.UID);
Console.Out.WriteLine("message.Envelope.From = {0}", fetchItem.Envelope.From);
Console.Out.WriteLine("message.Envelope.To = {0}", fetchItem.Envelope.To);
Console.Out.WriteLine("message.Envelope.Subject = {0}", fetchItem.Envelope.Subject);
Console.Out.WriteLine("message.Envelope.MessageID = {0}", fetchItem.Envelope.MessageID);
}
Console.Out.WriteLine("Fetching bodies");
foreach (var fetchItem in client.FetchMessages(sequence, IMAP_FetchItem_Flags.All, false, true)
{
var email = LumiSoft.Net.Mail.Mail_Message.ParseFromByte(fetchItem.MessageData);
Console.Out.WriteLine("email.BodyText = {0}", email.BodyText);
}
}
I had the similar issue using Flurl.Http:
Flurl.Http.FlurlHttpException: Call failed. Cannot send a content-body with this verb-type. GET http://******:8301/api/v1/agents/**** ---> System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type.
The problem was I used .WithHeader("Content-Type", "application/json")
when creating IFlurlRequest.
java.lang.String.split
splits on regular expressions, and .
in a regular expression means "any character".
Try temp.split("\\.")
.
Both will work but xhtml standard requires you to specify the type
too:
<script type="text/javascript">..</script>
<!ELEMENT SCRIPT - - %Script; -- script statements -->
<!ATTLIST SCRIPT
charset %Charset; #IMPLIED -- char encoding of linked resource --
type %ContentType; #REQUIRED -- content type of script language --
src %URI; #IMPLIED -- URI for an external script --
defer (defer) #IMPLIED -- UA may defer execution of script --
>
type = content-type [CI] This attribute specifies the scripting language of the element's contents and overrides the default scripting language. The scripting language is specified as a content type (e.g., "text/javascript"). Authors must supply a value for this attribute. There is no default value for this attribute.
Notices the emphasis above.
http://www.w3.org/TR/html4/interact/scripts.html
Note: As of HTML5 (far away), the type
attribute is not required and is default.
You can achieve it using custom log4j appender.
MaxNumberOfDays - possibility to set amount of days of rotated log files.
CompressBackups - possibility to archive old logs with zip extension.
package com.example.package;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Optional;
import java.util.TimeZone;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class CustomLog4jAppender extends FileAppender {
private static final int TOP_OF_TROUBLE = -1;
private static final int TOP_OF_MINUTE = 0;
private static final int TOP_OF_HOUR = 1;
private static final int HALF_DAY = 2;
private static final int TOP_OF_DAY = 3;
private static final int TOP_OF_WEEK = 4;
private static final int TOP_OF_MONTH = 5;
private String datePattern = "'.'yyyy-MM-dd";
private String compressBackups = "false";
private String maxNumberOfDays = "7";
private String scheduledFilename;
private long nextCheck = System.currentTimeMillis() - 1;
private Date now = new Date();
private SimpleDateFormat sdf;
private RollingCalendar rc = new RollingCalendar();
private static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT");
public CustomLog4jAppender() {
}
public CustomLog4jAppender(Layout layout, String filename, String datePattern) throws IOException {
super(layout, filename, true);
this.datePattern = datePattern;
activateOptions();
}
public void setDatePattern(String pattern) {
datePattern = pattern;
}
public String getDatePattern() {
return datePattern;
}
@Override
public void activateOptions() {
super.activateOptions();
if (datePattern != null && fileName != null) {
now.setTime(System.currentTimeMillis());
sdf = new SimpleDateFormat(datePattern);
int type = computeCheckPeriod();
printPeriodicity(type);
rc.setType(type);
File file = new File(fileName);
scheduledFilename = fileName + sdf.format(new Date(file.lastModified()));
} else {
LogLog.error("Either File or DatePattern options are not set for appender [" + name + "].");
}
}
private void printPeriodicity(int type) {
String appender = "Log4J Appender: ";
switch (type) {
case TOP_OF_MINUTE:
LogLog.debug(appender + name + " to be rolled every minute.");
break;
case TOP_OF_HOUR:
LogLog.debug(appender + name + " to be rolled on top of every hour.");
break;
case HALF_DAY:
LogLog.debug(appender + name + " to be rolled at midday and midnight.");
break;
case TOP_OF_DAY:
LogLog.debug(appender + name + " to be rolled at midnight.");
break;
case TOP_OF_WEEK:
LogLog.debug(appender + name + " to be rolled at start of week.");
break;
case TOP_OF_MONTH:
LogLog.debug(appender + name + " to be rolled at start of every month.");
break;
default:
LogLog.warn("Unknown periodicity for appender [" + name + "].");
}
}
private int computeCheckPeriod() {
RollingCalendar rollingCalendar = new RollingCalendar(gmtTimeZone, Locale.ENGLISH);
Date epoch = new Date(0);
if (datePattern != null) {
for (int i = TOP_OF_MINUTE; i <= TOP_OF_MONTH; i++) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(datePattern);
simpleDateFormat.setTimeZone(gmtTimeZone);
String r0 = simpleDateFormat.format(epoch);
rollingCalendar.setType(i);
Date next = new Date(rollingCalendar.getNextCheckMillis(epoch));
String r1 = simpleDateFormat.format(next);
if (!r0.equals(r1)) {
return i;
}
}
}
return TOP_OF_TROUBLE;
}
private void rollOver() throws IOException {
if (datePattern == null) {
errorHandler.error("Missing DatePattern option in rollOver().");
return;
}
String datedFilename = fileName + sdf.format(now);
if (scheduledFilename.equals(datedFilename)) {
return;
}
this.closeFile();
File target = new File(scheduledFilename);
if (target.exists()) {
Files.delete(target.toPath());
}
File file = new File(fileName);
boolean result = file.renameTo(target);
if (result) {
LogLog.debug(fileName + " -> " + scheduledFilename);
} else {
LogLog.error("Failed to rename [" + fileName + "] to [" + scheduledFilename + "].");
}
try {
this.setFile(fileName, false, this.bufferedIO, this.bufferSize);
} catch (IOException e) {
errorHandler.error("setFile(" + fileName + ", false) call failed.");
}
scheduledFilename = datedFilename;
}
@Override
protected void subAppend(LoggingEvent event) {
long n = System.currentTimeMillis();
if (n >= nextCheck) {
now.setTime(n);
nextCheck = rc.getNextCheckMillis(now);
try {
cleanupAndRollOver();
} catch (IOException ioe) {
LogLog.error("cleanupAndRollover() failed.", ioe);
}
}
super.subAppend(event);
}
public String getCompressBackups() {
return compressBackups;
}
public void setCompressBackups(String compressBackups) {
this.compressBackups = compressBackups;
}
public String getMaxNumberOfDays() {
return maxNumberOfDays;
}
public void setMaxNumberOfDays(String maxNumberOfDays) {
this.maxNumberOfDays = maxNumberOfDays;
}
protected void cleanupAndRollOver() throws IOException {
File file = new File(fileName);
Calendar cal = Calendar.getInstance();
int maxDays = 7;
try {
maxDays = Integer.parseInt(getMaxNumberOfDays());
} catch (Exception e) {
// just leave it at 7.
}
cal.add(Calendar.DATE, -maxDays);
Date cutoffDate = cal.getTime();
if (file.getParentFile().exists()) {
File[] files = file.getParentFile().listFiles(new StartsWithFileFilter(file.getName(), false));
int nameLength = file.getName().length();
for (File value : Optional.ofNullable(files).orElse(new File[0])) {
String datePart;
try {
datePart = value.getName().substring(nameLength);
Date date = sdf.parse(datePart);
if (date.before(cutoffDate)) {
Files.delete(value.toPath());
} else if (getCompressBackups().equalsIgnoreCase("YES") || getCompressBackups().equalsIgnoreCase("TRUE")) {
zipAndDelete(value);
}
} catch (Exception pe) {
// This isn't a file we should touch (it isn't named correctly)
}
}
}
rollOver();
}
private void zipAndDelete(File file) throws IOException {
if (!file.getName().endsWith(".zip")) {
File zipFile = new File(file.getParent(), file.getName() + ".zip");
try (FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos)) {
ZipEntry zipEntry = new ZipEntry(file.getName());
zos.putNextEntry(zipEntry);
byte[] buffer = new byte[4096];
while (true) {
int bytesRead = fis.read(buffer);
if (bytesRead == -1) {
break;
} else {
zos.write(buffer, 0, bytesRead);
}
}
zos.closeEntry();
}
Files.delete(file.toPath());
}
}
class StartsWithFileFilter implements FileFilter {
private String startsWith;
private boolean inclDirs;
StartsWithFileFilter(String startsWith, boolean includeDirectories) {
super();
this.startsWith = startsWith.toUpperCase();
inclDirs = includeDirectories;
}
public boolean accept(File pathname) {
if (!inclDirs && pathname.isDirectory()) {
return false;
} else {
return pathname.getName().toUpperCase().startsWith(startsWith);
}
}
}
class RollingCalendar extends GregorianCalendar {
private static final long serialVersionUID = -3560331770601814177L;
int type = CustomLog4jAppender.TOP_OF_TROUBLE;
RollingCalendar() {
super();
}
RollingCalendar(TimeZone tz, Locale locale) {
super(tz, locale);
}
void setType(int type) {
this.type = type;
}
long getNextCheckMillis(Date now) {
return getNextCheckDate(now).getTime();
}
Date getNextCheckDate(Date now) {
this.setTime(now);
switch (type) {
case CustomLog4jAppender.TOP_OF_MINUTE:
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
this.add(Calendar.MINUTE, 1);
break;
case CustomLog4jAppender.TOP_OF_HOUR:
this.set(Calendar.MINUTE, 0);
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
this.add(Calendar.HOUR_OF_DAY, 1);
break;
case CustomLog4jAppender.HALF_DAY:
this.set(Calendar.MINUTE, 0);
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
int hour = get(Calendar.HOUR_OF_DAY);
if (hour < 12) {
this.set(Calendar.HOUR_OF_DAY, 12);
} else {
this.set(Calendar.HOUR_OF_DAY, 0);
this.add(Calendar.DAY_OF_MONTH, 1);
}
break;
case CustomLog4jAppender.TOP_OF_DAY:
this.set(Calendar.HOUR_OF_DAY, 0);
this.set(Calendar.MINUTE, 0);
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
this.add(Calendar.DATE, 1);
break;
case CustomLog4jAppender.TOP_OF_WEEK:
this.set(Calendar.DAY_OF_WEEK, getFirstDayOfWeek());
this.set(Calendar.HOUR_OF_DAY, 0);
this.set(Calendar.MINUTE, 0);
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
this.add(Calendar.WEEK_OF_YEAR, 1);
break;
case CustomLog4jAppender.TOP_OF_MONTH:
this.set(Calendar.DATE, 1);
this.set(Calendar.HOUR_OF_DAY, 0);
this.set(Calendar.MINUTE, 0);
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
this.add(Calendar.MONTH, 1);
break;
default:
throw new IllegalStateException("Unknown periodicity type.");
}
return getTime();
}
}
}
And use this properties in your log4j config file:
log4j.appender.[appenderName]=com.example.package.CustomLog4jAppender
log4j.appender.[appenderName].File=/logs/app-daily.log
log4j.appender.[appenderName].Append=true
log4j.appender.[appenderName].encoding=UTF-8
log4j.appender.[appenderName].layout=org.apache.log4j.EnhancedPatternLayout
log4j.appender.[appenderName].layout.ConversionPattern=%-5.5p %d %C{1.} - %m%n
log4j.appender.[appenderName].DatePattern='.'yyyy-MM-dd
log4j.appender.[appenderName].MaxNumberOfDays=7
log4j.appender.[appenderName].CompressBackups=true
Adding an item to the list:
List< ? extends X > doesn't allow to add anything, except for null
into the list.
List< ? super X > allows to add anything that is-a X (X or its subtype), or null.
Getting an item from the list:
Object
.Some examples:
List<? extends Number> list1 = new ArrayList<Integer>();
list1.add(null); //OK
Number n = list1.get(0); //OK
Serializable s = list1.get(0); //OK
Object o = list1.get(0); //OK
list1.add(2.3); //ERROR
list1.add(5); //ERROR
list1.add(new Object()); //ERROR
Integer i = list1.get(0); //ERROR
List<? super Number> list2 = new ArrayList<Number>();
list2.add(null); //OK
list2.add(2.3); //OK
list2.add(5); //OK
Object o = list2.get(0); //OK
list2.add(new Object()); //ERROR
Number n = list2.get(0); //ERROR
Serializable s = list2.get(0); //ERROR
Integer i = list2.get(0); //ERROR
// Environment.GetFolderPath
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // Current User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); // All User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles); // Program Files
Environment.GetFolderPath(Environment.SpecialFolder.Cookies); // Internet Cookie
Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Logical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); // Physical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.Favorites); // Favorites
Environment.GetFolderPath(Environment.SpecialFolder.History); // Internet History
Environment.GetFolderPath(Environment.SpecialFolder.InternetCache); // Internet Cache
Environment.GetFolderPath(Environment.SpecialFolder.MyComputer); // "My Computer" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // "My Documents" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyMusic); // "My Music" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); // "My Pictures" Folder
Environment.GetFolderPath(Environment.SpecialFolder.Personal); // "My Document" Folder
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); // Program files Folder
Environment.GetFolderPath(Environment.SpecialFolder.Programs); // Programs Folder
Environment.GetFolderPath(Environment.SpecialFolder.Recent); // Recent Folder
Environment.GetFolderPath(Environment.SpecialFolder.SendTo); // "Sent to" Folder
Environment.GetFolderPath(Environment.SpecialFolder.StartMenu); // Start Menu
Environment.GetFolderPath(Environment.SpecialFolder.Startup); // Startup
Environment.GetFolderPath(Environment.SpecialFolder.System); // System Folder
Environment.GetFolderPath(Environment.SpecialFolder.Templates); // Document Templates
Thanks to all the investigations of Lance, I could find a solution to my problem. It possibly had to do with my ISP.
To summarize:
I unchecked the "Automatically detect settings" in the Local Area Network Settings (found in "Internet Options" > Connections > LAN Settings.
Now the sites are correctly marked as Internet sites (instead of Intranet sites).
It was now the third time I googled myself to this SO post as I always forget how to mock an @Value field. Though the accepted answer is correct, I always need some time to get the "setField" call right, so at least for myself I paste an example snippet here:
Production class:
@Value("#{myProps[‘some.default.url']}")
private String defaultUrl;
Test class:
import org.springframework.test.util.ReflectionTestUtils;
ReflectionTestUtils.setField(instanceUnderTest, "defaultUrl", "http://foo");
// Note: Don't use MyClassUnderTest.class, use the instance you are testing itself
// Note: Don't use the referenced string "#{myProps[‘some.default.url']}",
// but simply the FIELDs name ("defaultUrl")
Also, using the StringBuilder.AppendLine method.
Here's my basic 'Howdy World' Python daemon that I start with, when I'm developing a new daemon application.
#!/usr/bin/python
import time
from daemon import runner
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = '/dev/tty'
self.stderr_path = '/dev/tty'
self.pidfile_path = '/tmp/foo.pid'
self.pidfile_timeout = 5
def run(self):
while True:
print("Howdy! Gig'em! Whoop!")
time.sleep(10)
app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()
Note that you'll need the python-daemon
library. You can install it by:
pip install python-daemon
Then just start it with ./howdy.py start
, and stop it with ./howdy.py stop
.
Using
calls Dispose()
after the using
-block is left, even if the code throws an exception.
So you usually use using
for classes that require cleaning up after them, like IO.
So, this using block:
using (MyClass mine = new MyClass())
{
mine.Action();
}
would do the same as:
MyClass mine = new MyClass();
try
{
mine.Action();
}
finally
{
if (mine != null)
mine.Dispose();
}
Using using
is way shorter and easier to read.
Instead of using a separate CTE to get the total, you can use a window function without the "partition by" clause.
If you are using:
count(*)
to get the count for a group, you can use:
sum(count(*)) over ()
to get the total count.
For example:
select Grade, 100. * count(*) / sum(count(*)) over ()
from table
group by Grade;
It tends to be faster in my experience, but I think it might internally use a temp table in some cases (I've seen "Worktable" when running with "set statistics io on").
EDIT: I'm not sure if my example query is what you are looking for, I was just illustrating how the windowing functions work.
I couldn't get access to remote machines unless I had UAC disabled.
That has to be done locally, either from control panel or running the following through cmd:
reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f
While UAC is enabled, make sure you run cmd as administrator.
You should try this :
pip install tkinter
I hope this would solve the issue.
$('#checkbox').on('change', function(){
$('p').css('color', this.checked ? '#09f' : '');
});
$('#checkbox').on('change', function(){_x000D_
$('p').css('color', this.checked ? '#09f' : '');_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>_x000D_
<input id="checkbox" type="checkbox" /> _x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do_x000D_
eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
</p>_x000D_
<p>_x000D_
Ut enim ad minim veniam, quis nostrud exercitation ullamco_x000D_
laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure_x000D_
dolor in reprehenderit in voluptate velit esse cillum dolore eu_x000D_
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non_x000D_
proident, sunt in culpa qui officia deserunt mollit anim id est_x000D_
laborum._x000D_
</p>
_x000D_
You can't. bash only does integers; you must delegate to a tool such as bc
.
The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5
. From the comment you put this needed to be declared elsewhere in your code
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
The error was because you are trying to execute a method that does not exist.
PS C:\Users\Matt> $md5 | gm
TypeName: System.Security.Cryptography.MD5CryptoServiceProvider
Name MemberType Definition
---- ---------- ----------
Clear Method void Clear()
ComputeHash Method byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...
The .ComputeHash()
of $md5.ComputeHash()
was the null valued expression. Typing in gibberish would create the same effect.
PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PowerShell by default allows this to happen as defined its StrictMode
When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.
Another option is the Objects.equals
utility method.
Objects.equals( thisEnum , thatEnum )
Objects.equals
for null-safetyequals operator == instead of .equals()
Which operator is the one I should be using?
A third option is the static equals
method found on the Objects
utility class added to Java 7 and later.
Here’s an example using the Month
enum.
boolean areEqual = Objects.equals( Month.FEBRUARY , Month.JUNE ) ; // Returns `false`.
I find a couple benefits to this method:
true
false
NullPointerException
What is the logic used by Objects.equals
?
See for yourself, from the Java 10 source code of OpenJDK:
return (a == b) || (a != null && a.equals(b));
Swift 4:
First create an outlet for your UIImageView
@IBOutlet var infoImage: UIImageView!
Then use the image property in UIImageView
infoImage.image = UIImage(named: "icons8-info-white")
If you want formated number then use
SELECT TO_CHAR(number, 'fmt')
FROM DUAL;
SELECT TO_CHAR('123', 999.99)
FROM DUAL;
Result 123.00
Here is my solutions; It is my getView() in BaseAdapter subclass:
public View getView(int position, View convertView, ViewGroup parent)
{
if(convertView==null)
{
convertView=inflater.inflate(R.layout.list_view, parent,false);
System.out.println("In");
}
convertView.setMinimumHeight(100);
return convertView;
}
Here i have set ListItem's minimum height to 100;
Do the following:
private float xAccel, yAccel, zAccel;
private float xPreviousAccel, yPreviousAccel, zPreviousAccel;
private boolean firstUpdate = true;
private final float shakeThreshold = 1.5f;
private boolean shakeInitiated = false;
SensorEventListener mySensorEventListener;
SensorManager mySensorManager;
Put this in onCreate method.
mySensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mySensorManager.registerListener(mySensorEventListener,
mySensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
And now the main part.
private boolean isAccelerationChanged() {
float deltaX = Math.abs(xPreviousAccel - xAccel);
float deltaY = Math.abs(yPreviousAccel - yAccel);
float deltaZ = Math.abs(zPreviousAccel - zAccel);
return (deltaX > shakeThreshold && deltaY > shakeThreshold)
|| (deltaX > shakeThreshold && deltaZ > shakeThreshold)
|| (deltaY > shakeThreshold && deltaZ > shakeThreshold);
}
private void updateAccelParameters(float xNewAccel, float yNewAccel, float zNewAccel) {
if (firstUpdate) {
xPreviousAccel = xNewAccel;
yPreviousAccel = yNewAccel;
zPreviousAccel = zNewAccel;
firstUpdate = false;
}else{
xPreviousAccel = xAccel;
yPreviousAccel = yAccel;
zPreviousAccel = zAccel;
}
xAccel = xNewAccel;
yAccel = yNewAccel;
zAccel = zNewAccel;
}
private void executeShakeAction() {
//this method is called when devices shakes
}
public void onSensorChanged(SensorEvent se) {
updateAccelParameters(se.values[0], se.values[1], se.values[2]);
if ((!shakeInitiated) && isAccelerationChanged()) {
shakeInitiated = true;
}else if ((shakeInitiated) && isAccelerationChanged()){
executeShakeAction();
}else if((shakeInitiated) && (!isAccelerationChanged())){
shakeInitiated = false;
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
//setting the accuracy
}
In practice, I have found that you need to be a bit careful, especially if you are using a bit of xml repeatedly. Suppose, for example, that you have a table that you wish to create a table row for each entry in a list. You've set up some xml:
In my_table_row.xml
:
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" android:id="@+id/myTableRow">
<ImageButton android:src="@android:drawable/ic_menu_delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/rowButton"/>
<TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="TextView" android:id="@+id/rowText"></TextView>
</TableRow>
Then you want to create it once per row with some code. It assume that you have defined a parent TableLayout myTable to attach the Rows to.
for (int i=0; i<numRows; i++) {
/*
* 1. Make the row and attach it to myTable. For some reason this doesn't seem
* to return the TableRow as you might expect from the xml, so you need to
* receive the View it returns and then find the TableRow and other items, as
* per step 2.
*/
LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.my_table_row, myTable, true);
// 2. Get all the things that we need to refer to to alter in any way.
TableRow tr = (TableRow) v.findViewById(R.id.profileTableRow);
ImageButton rowButton = (ImageButton) v.findViewById(R.id.rowButton);
TextView rowText = (TextView) v.findViewById(R.id.rowText);
// 3. Configure them out as you need to
rowText.setText("Text for this row");
rowButton.setId(i); // So that when it is clicked we know which one has been clicked!
rowButton.setOnClickListener(this); // See note below ...
/*
* To ensure that when finding views by id on the next time round this
* loop (or later) gie lots of spurious, unique, ids.
*/
rowText.setId(1000+i);
tr.setId(3000+i);
}
For a clear simple example on handling rowButton.setOnClickListener(this), see Onclicklistener for a programatically created button.
really this belongs as a comment to Nathan's answer, but I'm not allowed to do that yet...
I wanted to maintain the aspect ratio, even if there is too much stuff to fit in the box. His example expands the height, changing the aspect ratio. I found adding
overflow: hidden;
overflow-x: auto;
overflow-y: auto;
to the .element helped. See http://jsfiddle.net/B8FU8/3111/
Short and sweet...
DataTable dataTable = new DataTable();
try
{
using (var adapter = new SqlDataAdapter("StoredProcedureName", ConnectionString))
{
adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
adapter.SelectCommand.Parameters.Add("@ParameterName", SqlDbType.Int).Value = 123;
adapter.Fill(dataTable);
};
}
catch (Exception ex)
{
Logger.Error("Error occured while fetching records from SQL server", ex);
}
For Windows 10:
Import certificate to Trusted Root Certification Authorities for Current User:
certutil -f -user -p oracle -importpfx root "example.pfx"
Import certificate to Trusted People for Current User:
certutil -f -user -p oracle -importpfx TrustedPeople "example.pfx"
Import certificate to Trusted Root Certification Authorities on Local Machine:
certutil -f -user -p oracle -enterprise -importpfx root "example.pfx"
Import certificate to Trusted People on Local Machine:
certutil -f -user -p oracle -enterprise -importpfx TrustedPeople "example.pfx"
On a Mac:
I was running this out of the Maven com.github.eirslett Frontend Plugin when I had the same error.
Eventually I had to:
Install Node.js via the installer download here: http://nodejs.org/
Delete all the node/
and node_modules/
folders from within my maven build structure.
I know that this question is very old but still we often get such requirements. There are many examples however many seems to be too verbose or complex for a simple implimentation.
See this https://jsfiddle.net/vibs2006/rn0fvxuk/ and improve it (if you can). It works on IE, Firefox, Chrome and Edge Browser.
Here is the working code.
_x000D_
function IsNumeric(e) {_x000D_
var IsValidationSuccessful = false;_x000D_
console.log(e.target.value);_x000D_
document.getElementById("info").innerHTML = "You just typed ''" + e.key + "''";_x000D_
//console.log("e.Key Value = "+e.key);_x000D_
switch (e.key)_x000D_
{ _x000D_
case "1":_x000D_
case "2":_x000D_
case "3":_x000D_
case "4":_x000D_
case "5":_x000D_
case "6":_x000D_
case "7":_x000D_
case "8":_x000D_
case "9":_x000D_
case "0":_x000D_
case "Backspace": _x000D_
IsValidationSuccessful = true;_x000D_
break;_x000D_
_x000D_
case "Decimal": //Numpad Decimal in Edge Browser_x000D_
case ".": //Numpad Decimal in Chrome and Firefox _x000D_
case "Del": // Internet Explorer 11 and less Numpad Decimal _x000D_
if (e.target.value.indexOf(".") >= 1) //Checking if already Decimal exists_x000D_
{_x000D_
IsValidationSuccessful = false;_x000D_
}_x000D_
else_x000D_
{_x000D_
IsValidationSuccessful = true;_x000D_
}_x000D_
break;_x000D_
_x000D_
default:_x000D_
IsValidationSuccessful = false;_x000D_
}_x000D_
//debugger;_x000D_
if(IsValidationSuccessful == false){_x000D_
_x000D_
document.getElementById("error").style = "display:Block";_x000D_
}else{_x000D_
document.getElementById("error").style = "display:none";_x000D_
}_x000D_
_x000D_
return IsValidationSuccessful;_x000D_
}
_x000D_
Numeric Value: <input type="number" id="text1" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" /><br />_x000D_
<span id="error" style="color: Red; display: none">* Input digits (0 - 9) and Decimals Only</span><br />_x000D_
<div id="info"></div>
_x000D_
I have the script all.p
set ...
...
list=system('ls -1B *.dat')
plot for [file in list] file w l u 1:2 t file
Here the two last rows are literal, not heuristic. Then i run
$ gnuplot -p all.p
Change *.dat
to the file type you have, or add file types.
Next step: Add to ~/.bashrc this line
alias p='gnuplot -p ~/./all.p'
and put your file all.p
int your home directory and voila. You can plot all files in any directory by typing p and enter.
EDIT I changed the command, because it didn't work. Previously it contained list(i)=word(system(ls -1B *.dat),i)
.
I see only one case that you would allow exposure to your internal members to another assembly and that is for testing purposes.
Saying that there is a way to allow "Friend" assemblies access to internals:
In the AssemblyInfo.cs file of the project you add a line for each assembly.
[assembly: InternalsVisibleTo("name of assembly here")]
this info is available here.
Hope this helps.
You've not shown how you're creating the string 2016-01-12T23:00:00.000Z
, but I assume via .format()
.
Anyway, .set()
is using your local time zone, but the Z
in the time string indicates zero time, otherwise known as UTC.
https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators
So I assume your local timezone is 23 hours from UTC?
saikumar's answer showed how to load the time in as UTC, but the other option is to use a .format()
call that outputs using your local timezone, rather than UTC.
http://momentjs.com/docs/#/get-set/
http://momentjs.com/docs/#/displaying/format/
I had android sdk and android studio installed separately in my system. Android studio had installed its own sdk. After I deleted the stand-alone android sdk, the issue of "“No system image installed for this Target” was gone.
I use outline a css 2 property that simply works. Check this out, is simple and even easy to animate:
.double-border {_x000D_
display: block;_x000D_
clear: both;_x000D_
background: red;_x000D_
border: 5px solid yellow;_x000D_
outline: 5px solid blue;_x000D_
transition: 0.7s all ease-in;_x000D_
height: 50px;_x000D_
width: 50px;_x000D_
}_x000D_
.double-border:hover {_x000D_
background: yellow;_x000D_
outline-color: red;_x000D_
border-color: blue;_x000D_
}
_x000D_
<div class="double-border"></div>
_x000D_
As @Alex McMillan mentioned, use state to dictate what should be rendered in the dom.
In the example below I have an input field and I want to add a second one when the user clicks the button, the onClick event handler calls handleAddSecondInput( ) which changes inputLinkClicked to true. I am using a ternary operator to check for the truthy state, which renders the second input field
class HealthConditions extends React.Component {
constructor(props) {
super(props);
this.state = {
inputLinkClicked: false
}
}
handleAddSecondInput() {
this.setState({
inputLinkClicked: true
})
}
render() {
return(
<main id="wrapper" className="" data-reset-cookie-tab>
<div id="content" role="main">
<div className="inner-block">
<H1Heading title="Tell us about any disabilities, illnesses or ongoing conditions"/>
<InputField label="Name of condition"
InputType="text"
InputId="id-condition"
InputName="condition"
/>
{
this.state.inputLinkClicked?
<InputField label=""
InputType="text"
InputId="id-condition2"
InputName="condition2"
/>
:
<div></div>
}
<button
type="button"
className="make-button-link"
data-add-button=""
href="#"
onClick={this.handleAddSecondInput}
>
Add a condition
</button>
<FormButton buttonLabel="Next"
handleSubmit={this.handleSubmit}
linkto={
this.state.illnessOrDisability === 'true' ?
"/404"
:
"/add-your-details"
}
/>
<BackLink backLink="/add-your-details" />
</div>
</div>
</main>
);
}
}
Try this:
;WITH CTE
AS
(
SELECT DISTINCT
M1.Product_ID Group_ID,
M1.Product_ID
FROM matches M1
LEFT JOIN matches M2
ON M1.Product_Id = M2.matching_Product_Id
WHERE M2.matching_Product_Id IS NULL
UNION ALL
SELECT
C.Group_ID,
M.matching_Product_Id
FROM CTE C
JOIN matches M
ON C.Product_ID = M.Product_ID
)
SELECT * FROM CTE ORDER BY Group_ID
You can use OPTION(MAXRECURSION n)
to control recursion depth.
SYSDATE
and GETDATE
perform identically.
SYSDATE
is compatible with Oracle syntax, and GETDATE
is compatible with Microsoft SQL Server syntax.
This helped me
sudo pip3 install --upgrade --target=/home/<username>/.local/lib/python3.6/site-packages numpy
By turning them into integers instead:
percent = (int(pyc) / int(tpy)) * 100;
In python 3, the input()
function returns a string. Always. This is a change from Python 2; the raw_input()
function was renamed to input()
.
"copysign" is defined by IEEE 754, and part of the C99 specification. That's why it's in Python. The function cannot be implemented in full by abs(x) * sign(y) because of how it's supposed to handle NaN values.
>>> import math
>>> math.copysign(1, float("nan"))
1.0
>>> math.copysign(1, float("-nan"))
-1.0
>>> math.copysign(float("nan"), 1)
nan
>>> math.copysign(float("nan"), -1)
nan
>>> float("nan") * -1
nan
>>> float("nan") * 1
nan
>>>
That makes copysign() a more useful function than sign().
As to specific reasons why IEEE's signbit(x) is not available in standard Python, I don't know. I can make assumptions, but it would be guessing.
The math module itself uses copysign(1, x) as a way to check if x is negative or non-negative. For most cases dealing with mathematical functions that seems more useful than having a sign(x) which returns 1, 0, or -1 because there's one less case to consider. For example, the following is from Python's math module:
static double
m_atan2(double y, double x)
{
if (Py_IS_NAN(x) || Py_IS_NAN(y))
return Py_NAN;
if (Py_IS_INFINITY(y)) {
if (Py_IS_INFINITY(x)) {
if (copysign(1., x) == 1.)
/* atan2(+-inf, +inf) == +-pi/4 */
return copysign(0.25*Py_MATH_PI, y);
else
/* atan2(+-inf, -inf) == +-pi*3/4 */
return copysign(0.75*Py_MATH_PI, y);
}
/* atan2(+-inf, x) == +-pi/2 for finite x */
return copysign(0.5*Py_MATH_PI, y);
There you can clearly see that copysign() is a more effective function than a three-valued sign() function.
You wrote:
If I were a python designer, I would been the other way around: no cmp() builtin, but a sign()
That means you don't know that cmp() is used for things besides numbers. cmp("This", "That") cannot be implemented with a sign() function.
Edit to collate my additional answers elsewhere:
You base your justifications on how abs() and sign() are often seen together. As the C standard library does not contain a 'sign(x)' function of any sort, I don't know how you justify your views. There's an abs(int) and fabs(double) and fabsf(float) and fabsl(long) but no mention of sign. There is "copysign()" and "signbit()" but those only apply to IEEE 754 numbers.
With complex numbers, what would sign(-3+4j) return in Python, were it to be implemented? abs(-3+4j) return 5.0. That's a clear example of how abs() can be used in places where sign() makes no sense.
Suppose sign(x) were added to Python, as a complement to abs(x). If 'x' is an instance of a user-defined class which implements the __abs__(self) method then abs(x) will call x.__abs__(). In order to work correctly, to handle abs(x) in the same way then Python will have to gain a sign(x) slot.
This is excessive for a relatively unneeded function. Besides, why should sign(x) exist and nonnegative(x) and nonpositive(x) not exist? My snippet from Python's math module implementation shows how copybit(x, y) can be used to implement nonnegative(), which a simple sign(x) cannot do.
Python should support have better support for IEEE 754/C99 math function. That would add a signbit(x) function, which would do what you want in the case of floats. It would not work for integers or complex numbers, much less strings, and it wouldn't have the name you are looking for.
You ask "why", and the answer is "sign(x) isn't useful." You assert that it is useful. Yet your comments show that you do not know enough to be able to make that assertion, which means you would have to show convincing evidence of its need. Saying that NumPy implements it is not convincing enough. You would need to show cases of how existing code would be improved with a sign function.
And that it outside the scope of StackOverflow. Take it instead to one of the Python lists.
concept = concept.encode('ascii', 'ignore')
concept = MySQLdb.escape_string(concept.decode('latin1').encode('utf8').rstrip())
I do this, I am not sure if that is a good approach but it works everytime !!
Assuming you have a char[fixed_size] rather than a char*, you can use a single, creative macro to do it all at once with a <<cout<<like
ordering ("rather %s the disjointed %s\n", "than", "printf style format"). If you are working with embedded systems, this method will also allow you to leave out malloc and the large *printf
family of functions like snprintf()
(This keeps dietlibc from complaining about *printf too)
#include <unistd.h> //for the write example
//note: you should check if offset==sizeof(buf) after use
#define strcpyALL(buf, offset, ...) do{ \
char *bp=(char*)(buf+offset); /*so we can add to the end of a string*/ \
const char *s, \
*a[] = { __VA_ARGS__,NULL}, \
**ss=a; \
while((s=*ss++)) \
while((*s)&&(++offset<(int)sizeof(buf))) \
*bp++=*s++; \
if (offset!=sizeof(buf))*bp=0; \
}while(0)
char buf[256];
int len=0;
strcpyALL(buf,len,
"The config file is in:\n\t",getenv("HOME"),"/.config/",argv[0],"/config.rc\n"
);
if (len<sizeof(buf))
write(1,buf,len); //outputs our message to stdout
else
write(2,"error\n",6);
//but we can keep adding on because we kept track of the length
//this allows printf-like buffering to minimize number of syscalls to write
//set len back to 0 if you don't want this behavior
strcpyALL(buf,len,"Thanks for using ",argv[0],"!\n");
if (len<sizeof(buf))
write(1,buf,len); //outputs both messages
else
write(2,"error\n",6);
Here is some weak adobe documentation on different flash 9 wmode settings.
A note of caution on wmode transparent is here in the adobe bug trac.
And new for flash 10, are two new wmodes: gpu and direct. Please refer to Adobe Knowledge Base about wmode.
You do this using the modulus operator, %
n % k == 0
evaluates true if and only if n
is an exact multiple of k
. In elementary maths this is known as the remainder from a division.
In your current approach you perform a division and the result will be either
It's just the wrong way to go about testing divisibility.
Edit your C:\Windows\System32\drivers\etc\hosts
file
Make sure there is an entry that looks like this:
127.0.0.1 localhost
If there is an entry like
:: localhost
Comment it out to look like this
\#:: localhost
This should fix your problem, I've had this problem in the past.
check http://www.tech-archive.net/Archive/VB/microsoft.public.vb.database.ado/2005-08/msg00056.html
one needs to use something like
cmd.CommandText = "BEGIN foo@v; END;"
worked for me in vb.net, c#
As nobody has mentioned I will add it (even if it is a stupid mistake). In case you are on Windows 10 you don't usually need to restart, but
-> Make sure to CLOSE any open properties pages of the "services"-window in case you have just installed the service (and still have opened the properties page of the old service).
I'm talking about this window:
After closing all services windows and re-trying -> it worked. In contrast to the OP I got Error 1053
basically immediately (without windows waiting on anything)
push()
adds a new element to the end of an array.
pop()
removes an element from the end of an array.
unshift()
adds a new element to the beginning of an array.
shift()
removes an element from the beginning of an array.
To remove first element from an array arr
, use arr.shift()
To remove last element from an array arr
, use arr.pop()
Please put the pages in localhost and try
From the official documentation regarding the Formatter class:
The constructor takes two optional arguments: a message format string and a date format string.
So change
# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")
to
# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s",
"%Y-%m-%d %H:%M:%S")
# simple binary tree
# in this implementation, a node is inserted between an existing node and the root
class BinaryTree():
def __init__(self,rootid):
self.left = None
self.right = None
self.rootid = rootid
def getLeftChild(self):
return self.left
def getRightChild(self):
return self.right
def setNodeValue(self,value):
self.rootid = value
def getNodeValue(self):
return self.rootid
def insertRight(self,newNode):
if self.right == None:
self.right = BinaryTree(newNode)
else:
tree = BinaryTree(newNode)
tree.right = self.right
self.right = tree
def insertLeft(self,newNode):
if self.left == None:
self.left = BinaryTree(newNode)
else:
tree = BinaryTree(newNode)
tree.left = self.left
self.left = tree
def printTree(tree):
if tree != None:
printTree(tree.getLeftChild())
print(tree.getNodeValue())
printTree(tree.getRightChild())
# test tree
def testTree():
myTree = BinaryTree("Maud")
myTree.insertLeft("Bob")
myTree.insertRight("Tony")
myTree.insertRight("Steven")
printTree(myTree)
Read more about it Here:-This is a very simple implementation of a binary tree.
This is a nice tutorial with questions in between
Your byte array is too small. Each pixel takes up 4 bytes, not just 1, so multiply your size * 4 so that the array is big enough.
If you are fine with modifying the original set (which you may want to do in some cases), you can use set.update()
:
S.update(T)
The return value is None
, but S
will be updated to be the union of the original S
and T
.
There is a new NuGet package that contains the System.Windows.Interactivity.dll that is compatible with:
To install Expression.Blend.Sdk, run the following command in the Package Manager Console
PM> Install-Package Expression.Blend.Sdk
Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application.....
with filename = GetFileName(Range("A1"))
Function GetFileName(rngNamedCell As Range) As String
Dim strSaveDirectory As String: strSaveDirectory = ""
Dim strFileName As String: strFileName = ""
Dim strTestPath As String: strTestPath = ""
Dim strFileBaseName As String: strFileBaseName = ""
Dim strFilePath As String: strFilePath = ""
Dim intFileCounterIndex As Integer: intFileCounterIndex = 1
' Get the users desktop directory.
strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
Debug.Print "Saving to: " & strSaveDirectory
' Base file name
strFileBaseName = Trim(rngNamedCell.Value)
Debug.Print "File Name will contain: " & strFileBaseName
' Loop until we find a free file number
Do
If intFileCounterIndex > 1 Then
' Build test path base on current counter exists.
strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
Else
' Build test path base just on base name to see if it exists.
strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
End If
If (Dir(strTestPath) = "") Then
' This file path does not currently exist. Use that.
strFileName = strTestPath
Else
' Increase the counter as we have not found a free file yet.
intFileCounterIndex = intFileCounterIndex + 1
End If
Loop Until strFileName <> ""
' Found useable filename
Debug.Print "Free file name: " & strFileName
GetFileName = strFileName
End Function
The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.
In Action
My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.
Sub Testing()
Dim filename As String: filename = GetFileName(Range("o1"))
ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
filename:=filename, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub
Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.
The <button>
element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:
<button type="button">
to override default submission behaviorevent.preventDefault()
in the onSubmit event to prevent form submissionInsert extra type
attribute to your button markup:
<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>
Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:
$(document).ready(function () {
// Listen to click event on the submit button
$('#button').click(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
In this improvement, we listen to the submit event emitted from the <form>
element:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
.serialize()
to serialize your form, but remember to add name
attributes to your input:The name
attribute is required for .serialize()
to work, as per jQuery's documentation:
For a form element's value to be included in the serialized string, the element must have a name attribute.
<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">
And then in your JS:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
// Prevent form submission which refreshes page
e.preventDefault();
// Serialize data
var formData = $(this).serialize();
// Make AJAX request
$.post("process.php", formData).complete(function() {
console.log("Success");
});
});
});
You have to change androidx.constraintlayout.widget.ConstraintLayout
to RelativeLayout
.
This combination of properties helped for me:
display: inline-block;
overflow-wrap: break-word;
word-wrap: break-word;
word-break: normal;
line-break: strict;
hyphens: none;
-webkit-hyphens: none;
-moz-hyphens: none;
A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.
If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).
The Developer Toolbar GCLI and Shift+F2 shortcut were removed in Firefox version 60. To take a screenshot in 60 or newer:
:screenshot
or :screenshot --fullpage
Find out more regarding screenshots and other features
For Firefox versions < 60:
Press Shift+F2 or go to Tools > Web Developer > Developer Toolbar to open a command line. Write:
screenshot
and press Enter in order to take a screenshot.
To fully answer the question, you can even save the whole page, not only the visible part of it:
screenshot --fullpage
And to copy the screenshot to clipboard, use --clipboard
option:
screenshot --clipboard --fullpage
Firefox 18 changes the way arguments are passed to commands, you have to add "--" before them.
You can find some documentation and the full list of commands here.
PS. The screenshots are saved into the downloads directory by default.
First there is an elevator class. It has a direction (up, down, stand, maintenance), a current floor and a list of floor requests sorted in the direction. It receives request from this elevator.
Then there is a bank. It contains the elevators and receives the requests from the floors. These are scheduled to all active elevators (not in maintenance).
The scheduling will be like:
Each elevator has a set of states.
There are additional signals:
EDIT: Some elevators don't start at bottom/first_floor esp. in case of skyscrapers.
min_floor & max_floor are two additional attributes for Elevator.
You can try using Scanner if you are using JDK5 or higher.
Scanner scan = new Scanner(file);
scan.useDelimiter("\\Z");
String content = scan.next();
Or you can also use Guava
String data = Files.toString(new File("path.txt"), Charsets.UTF8);
I have no doubt on @Grant answer. But I face few issues sometimes such as if the column name is similar to any reserved keyword of postgresql such as natural in this case similar SQL is difficult to run from the command line as "\natural\" will be needed in Query field. So my approach is to write the SQL in separate file and run the SQL file from command line. This has another advantage too. If you have to change the query for a large script you do not need to touch the script file or command. Only change the SQL file like this
psql -h localhost -d database -U postgres -p 5432 -a -q -f /path/to/the/file.sql
In your example propertyInfo.GetValue(this, null)
should work. Consider altering GetNamesAndTypesAndValues()
as follows:
public void GetNamesAndTypesAndValues()
{
foreach (PropertyInfo propertyInfo in allClassProperties)
{
Console.WriteLine("{0} [type = {1}] [value = {2}]",
propertyInfo.Name,
propertyInfo.PropertyType,
propertyInfo.GetValue(this, null));
}
}
is it still actual?
As I can see you wrote <target depends="build-subprojects,build-project" name="build"/>
, then you wrote <target name="build-subprojects"/>
(it does nothing). Could it be a reason?
Does this <echo message="${ant.project.name}: ${ant.file}"/>
print appropriate message? If no then target is not running.
Take a look at the next link http://www.sqaforums.com/showflat.php?Number=623277
Select the block of code that you want indented.
Right-click (or, on Mac, Ctrl-click).
Structure → Re-indent
Yes, set the cell as a RANGE object one time and then use that RANGE object in your code:
Sub RangeExample()
Dim MyRNG As Range
Set MyRNG = Sheets("Sheet1").Cells(23, 4)
Debug.Print MyRNG.Value
End Sub
Alternately you can simply store the value of that cell in memory and reference the actual value, if that's all you really need. That variable can be Long or Double or Single if numeric, or String:
Sub ValueExample()
Dim MyVal As String
MyVal = Sheets("Sheet1").Cells(23, 4).Value
Debug.Print MyVal
End Sub
In this part of your code:
if(tmp[j] > 57 && tmp[j] < 48)
isDigit = 0;
else
isDigit = 1;
Your if
condition will always be false, resulting in isDigit
always being set to 1
. You are probably wanting:
if(tmp[j] > '9' || tmp[j] < '0')
isDigit = 0;
else
isDigit = 1;
But. this can be simplified to:
isDigit = isdigit(tmp[j]);
However, the logic of your loop seems kind of misguided:
int isDigit = 0;
int j=0;
while(j<strlen(tmp) && isDigit == 0){
isDigit = isdigit(tmp[j]);
j++;
}
As tmp
is not a constant, it is uncertain whether the compiler will optimize the length calculation out of each iteration.
As @andlrc suggests in a comment, you can instead just check for digits, since the terminating NUL will fail the check anyway.
while (isdigit(tmp[j])) ++j;
if you want to set value than you can do the same in some function on click or on some event fire.
also you can get value using ViewChild
using local variable like this
<input type='text' id='loginInput' #abc/>
and get value like this
this.abc.nativeElement.value
okay got it , you have to use ngAfterViewInit
method of angualr2 for the same like this
ngAfterViewInit(){
document.getElementById('loginInput').value = '123344565';
}
ngAfterViewInit
will not throw any error because it will render after template loading
You can't do it the way you're trying to... can you perhaps do something like this:
List<Answer> answers = new ArrayList<Answer>();
for(int i=0; i < 4; i++){
Answer temp = new Answer();
//do whatever initialization you need here
answers.add(temp);
}
import cv2
img=cv2.imread('my_test.jpg')
img_info = img.shape
print("Image height :",img_info[0])
print("Image Width :", img_info[1])
print("Image channels :", img_info[2])
My_test.jpg link ---> https://i.pinimg.com/originals/8b/ca/f5/8bcaf5e60433070b3210431e9d2a9cd9.jpg
Here a working example to use slf4j as façade with log4j in the backend:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>xxx</groupId>
<artifactId>xxx</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.30</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.30</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.13.3</version>
</dependency>
</dependencies>
</project>
src/main/resources/log4j.properties
# Root logger option
log4j.rootLogger=DEBUG, stdout
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
src/main/java/Main.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Main {
private static final Logger logger = LoggerFactory.getLogger(Main.class);
/**
* Default private constructor.
*/
private Main() {
}
/**
* Main method.
*
* @param args Arguments passed to the execution of the application
*/
public static void main(final String[] args) {
logger.info("Message to log");
}
}
Use HH
for 24 hour hours format:
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
Or the tt
format specifier for the AM/PM
part:
DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt")
Take a look at the custom Date and Time format strings documentation.
This might be more desirable, that is use float instead
SELECT fullName, CAST(totalBal as float) totalBal FROM client_info ORDER BY totalBal DESC
var http = require('http');
var url = require('url');
var fs = require('fs');
var neededstats = [];
http.createServer(function(req, res) {
if (req.url == '/index.html' || req.url == '/') {
fs.readFile('./index.html', function(err, data) {
res.end(data);
});
} else {
var p = __dirname + '/' + req.params.filepath;
fs.stat(p, function(err, stats) {
if (err) {
throw err;
}
neededstats.push(stats.mtime);
neededstats.push(stats.size);
res.send(neededstats);
});
}
}).listen(8080, '0.0.0.0');
console.log('Server running.');
I have not tested your code but other things works
If you want to get the path info from request url
var url_parts = url.parse(req.url);
console.log(url_parts);
console.log(url_parts.pathname);
1.If you are getting the URL parameters still not able to read the file just correct your file path in my example. If you place index.html in same directory as server code it would work...
2.if you have big folder structure that you want to host using node then I would advise you to use some framework like expressjs
If you want raw solution to file path
var http = require("http");
var url = require("url");
function start() {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
source : http://www.nodebeginner.org/
The urls are different.
http://localhost/AccountSvc/DataInquiry.asmx
vs.
/acctinqsvc/portfolioinquiry.asmx
Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.
You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx
, and specify the desired method/operation in the SOAPAction header.
The SOAPAction header values are different.
http://localhost/AccountSvc/DataInquiry.asmx/ + methodName
vs.
http://tempuri.org/GetMyName
You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl
There should be a <soap:operation>
tag underneath the <wsdl:operation>
tag that matches the operation you are attempting to execute, which appears to be GetMyName
.
There is no XML declaration in the request body that includes your SOAP XML.
You specify text/xml
in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii
, but there's no telling if you aren't specifying them!
The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8
Hope that helps!
My problem (and so solution) was yet different from those described above.
I wasn't using models.py
file, but created a models
directory and created the my_model.py
file there, where I put my model. Django couldn't find my model so it wrote that there are no migrations to apply.
My solution was: in the my_app/models/__init__.py
file I added this line:
from .my_model import MyModel
I needed this answer too, but I found the answers, while informative, a little hard to follow and replicate for other languages. Here is the simplest expression I came up with for a single column out of the CSV line. I am not splitting. I'm building a regex to match a column out of the CSV so I'm not splitting the line:
("([^"]*)"|[^,]*)(,|$)
This matches a single column from the CSV line. The first portion "([^"]*)"
of the expression is to match a quoted entry, the second part [^,]*
is to match a non-quoted entry. Then either followed by a ,
or end of line $
.
And the accompanying debuggex to test out the expression.
Looking at the Jasmine source code sheds more light on the issue.
toBe
is very simple and just uses the identity/strict equality operator, ===
:
function(actual, expected) {
return {
pass: actual === expected
};
}
toEqual
, on the other hand, is nearly 150 lines long and has special handling for built in objects like String
, Number
, Boolean
, Date
, Error
, Element
and RegExp
. For other objects it recursively compares properties.
This is very different from the behavior of the equality operator, ==
. For example:
var simpleObject = {foo: 'bar'};
expect(simpleObject).toEqual({foo: 'bar'}); //true
simpleObject == {foo: 'bar'}; //false
var castableObject = {toString: function(){return 'bar'}};
expect(castableObject).toEqual('bar'); //false
castableObject == 'bar'; //true
If you really don't want to change your structure, or at least create a copy of it containing the same data (e.g. make a class property with a setter and getter that read from/write to that string behind the scenes), then you can use a regular expression to check if an item is in that "list" at any given time, and if not, append it to the "list" as a separate element.
if not re.match("\b{}\b".format(348521), some_list[0]): some_list.append(348521)
This is probably faster than converting it to a set every time you want to check if an item is in it. But using set
as others have suggested here is a million times better.
There's an even simpler answer if you want to delete ALL your tables. You just go to your folder containing the database (which may be called mydatabase.db) and right-click the .db file and push "delete." Old fashioned way, sure-fire to work.
If you want to do this solely using javascript, I would do the following. Give the span an id attribute (so that it can easily be retrieved from the DOM) and place all the content in an attribute named 'content':
<span id='myDataId' style='text-overflow: ellipsis; overflow : hidden;
white-space: nowrap; width: 71;' content='{$myData}'>${myData}</span>
Then, in your javascript, you can do the following after the element has been inserted into the DOM.
var elemInnerText, elemContent;
elemInnerText = document.getElementById("myDataId").innerText;
elemContent = document.getElementById("myDataId").getAttribute('content')
if(elemInnerText.length <= elemContent.length)
{
document.getElementById("myDataId").setAttribute('title', elemContent);
}
Of course, if you're using javascript to insert the span into the DOM, you could just keep the content in a variable before inserting it. This way you don't need a content attribute on the span.
There are more elegant solutions than this if you want to use jQuery.
A facade should not be described as a class which contains a lot of other classes. It is in fact a interface to this classes and should make the usage of the classes easier otherwise the facade class is useless.
The easy way and fast way to do this is:
three = [sum(i) for i in zip(first,second)] # [7,9,11,13,15]
Alternatively, you can use numpy sum:
from numpy import sum
three = sum([first,second], axis=0) # array([7,9,11,13,15])
If you have a huge number of objects, this can (at times) be much faster:
try:
orgs[0]
# If you get here, it exists...
except IndexError:
# Doesn't exist!
On a project I'm working on with a huge database, not orgs
is 400+ ms and orgs.count()
is 250ms. In my most common use cases (those where there are results), this technique often gets that down to under 20ms. (One case I found, it was 6.)
Could be much longer, of course, depending on how far the database has to look to find a result. Or even faster, if it finds one quickly; YMMV.
EDIT: This will often be slower than orgs.count()
if the result isn't found, particularly if the condition you're filtering on is a rare one; as a result, it's particularly useful in view functions where you need to make sure the view exists or throw Http404. (Where, one would hope, people are asking for URLs that exist more often than not.)
Try UISegmentedControl. It behaves similarly to radio buttons -- presents an array of choices and lets the user pick 1.
You should have gradle-wrapper.properties inside gradle/wrapper folder. Make sure you are using the right distributionURL, and the latest one. It should look something like this :
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Just googled it, and found here a handy function that is useful for converting stdClass object to array recursively.
<?php
function object_to_array($object) {
if (is_object($object)) {
return array_map(__FUNCTION__, get_object_vars($object));
} else if (is_array($object)) {
return array_map(__FUNCTION__, $object);
} else {
return $object;
}
}
?>
EDIT: I updated this answer with content from linked source (which is also changed now), thanks to mason81 for suggesting me.
In MySQL if You don't want to change the collation and want to perform case sensitive search then just use binary keyword like this:
SELECT * FROM table_name WHERE binary username=@search_parameter and binary password=@search_parameter
toString
is a method, so you should add parenthesis ()
to make the function call.
> a = [1,2,3]
[ 1, 2, 3 ]
> a.toString()
'1,2,3'
Besides, if you want to use strings as keys, then you should consider using a Object
instead of Array
, and use JSON.stringify
to return a string.
> var aa = {}
> aa['a'] = 'aaa'
> JSON.stringify(aa)
'{"a":"aaa","b":"bbb"}'
I did this research the last week and I ended up with the same 2 libraries. As I'm using Spring 3 (that adopts Jackson in its default Json view 'JacksonJsonView') it was more natural for me to do the same. The 2 lib are pretty much the same... at the end they simply map to a json file! :)
Anyway as you said Jackson has a + in performance and that's very important for me. The project is also quite active as you can see from their web page and that's a very good sign as well.
public static void Do(Stream in)
{
_ms = new MemoryStream();
byte[] buffer = new byte[65536];
while ((int read = input.Read(buffer, 0, buffer.Length))>=0)
_ms.Write (buffer, 0, read);
}
What are you trying to accomplish? You can access characters in a string just like an array:
$s = 'abcd';
echo $s[0];
prints 'a'
I am assuming that you are making a web app because you refer to Apache and Node. Quick answer - Is it possible - YES. Is it recommended - NO. Node bundles it's own webserver and most websites run on port 80. I am also assuming that there is currently no Apache plugin which is supported by Nodejs and I am not sure if creating a virtual host is the best way to implement this. These are the questions that should be answered by developers who maintain Nodejs like the good folks at Joyent.
Instead of ports, it would be better to evaluate Node's tech stack which is completely different from most others and which is why I love it but it also involves a few compromises that you should be aware of in advance.
Your example looks similar to a CMS or a sharing web app and there are hundreds of out of the box apps available that will run just fine on Apache. Even if you do not like any readymade solution, you could write a webapp in PHP / Java / Python or mix n match it with a couple of ready made apps and they are all designed and supported to run behind a single instance of Apache.
It's time to pause and think about what I just said.
Now you are ready to decide on which techstack you are going to use. If your website will never use any out of the thousands of ready made apps that require Apache, then go for Node otherwise you must first eliminate the assumptions that I have stated earlier.
In the end, your choice of techstack is way more important than any individual component.
I completely agree with @Straseus that it is relatively trivial to use node.js file system api for handling uploads and downloads but think more about what you want from your website in the long run and then choose your techstack.
Learning Node's framework is easier than learning other frameworks but it is not a panacea. With a slightly more effort (which may be a worthwhile endeavor in itself), you can learn any other framework too. We all learn from each other and you will be more productive if you are working as a small team than if you are working alone and your backend technical skills will also develop faster. Therefore, do not discount the skills of other members of your team so cheaply.
This post is about a year old and chances are that you have already decided but I hope that my rant will help the next person who is going through a similar decision.
Thanks for reading.
Yet another method is using the LOOP instruction:
mov cx, 3
myloop:
; Your loop content
loop myloop
The loop instruction automatically decrements cx, and only jumps if cx != 0. There are also LOOPE, and LOOPNE variants, if you want to do some additional check for your loop to break out early.
If you want to modify cx during your loop, make sure to push it onto the stack before the loop content, and pop it off after:
mov cx, 3
myloop:
push cx
; Your loop content
pop cx
loop myloop
To complete Sunit's answer, you can use a selector, not to the text string but to the textColorHint. You must add this attribute on your editText:
android:textColorHint="@color/text_hint_selector"
And your text_hint_selector should be:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:color="@android:color/transparent" />
<item android:color="@color/hint_color" />
</selector>
I know that my answer is kind of overlapping with some of the other answer, but this is a complete solution that has some advantages. This works on Tomcat 8:
This means that you only have to restart the tomcat once, and after updated war files can be deployed without a problem.
Step 1: In the server.xml file, find the connector entry and replace it with:
<Connector
port="8080"
protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
<Connector
port="80"
protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
Step 2:
Define contexts within the <Host ...>
tag:
<Context path="/" docBase="CAS">
<WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>
<Context path="/ROOT" docBase="ROOT">
<WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>
<Context path="/manager" docBase="manager" privileged="true">
<WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>
<Context path="/host-manager" docBase="host-manager" privileged="true">
<WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>
Note that I addressed all apps in the webapp folder. The first effectively switch the root and the main app from position. ROOT is now on http://example.com/ROOT
and the the main application is on http://example.com/
. The webapps that are password protected require the privileged="true"
attribute.
When you deploy a CAS.war file that matches with the root (<Context path="/" docBase="CAS">
you have to reload that one in the admin panel as it does not refresh with the deployment.
Do not include the <Context path="/CAS" docBase="CAS">
in your contexts as it disables the manager option to deploy war files. This means that you can access the app in two ways: http://example.com/
and http://example.com/APP/
Step 3:
In order to prevent unwanted access to the root and manager folder, add a valve
to those context tags like this:
<Context path="/manager" docBase="manager" privileged="true">
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
addConnectorPort="true"
allow="143\.21\.2\.\d+;8080|127\.0\.0\.1;8080|::1;8080|0:0:0:0:0:0:0:1;8080"/>
</Context>
This essentially limits access to the admin web app folder to people from my own domain (fake IP address) and localhost when they use the default port 8080 and maintains the ability to dynamically deploy the war files through the web interface.
If you want to use this for multiple apps that are using different IP addresses, you can add the IP address to the connector (address="143.21.2.1"
).
If you want to run multiple web apps from the root, you can duplicate the Service tag (use a different name for the second) and change the docbase of the <Context path="/" docBase="CAS">
to for example <Context path="/" docBase="ICR">
.
PyPNG - lightweight PNG decoder/encoder
Although the question hints at JPG, I hope my answer will be useful to some people.
Here's how to read and write PNG pixels using PyPNG module:
import png, array
point = (2, 10) # coordinates of pixel to be painted red
reader = png.Reader(filename='image.png')
w, h, pixels, metadata = reader.read_flat()
pixel_byte_width = 4 if metadata['alpha'] else 3
pixel_position = point[0] + point[1] * w
new_pixel_value = (255, 0, 0, 0) if metadata['alpha'] else (255, 0, 0)
pixels[
pixel_position * pixel_byte_width :
(pixel_position + 1) * pixel_byte_width] = array.array('B', new_pixel_value)
output = open('image-with-red-dot.png', 'wb')
writer = png.Writer(w, h, **metadata)
writer.write_array(output, pixels)
output.close()
PyPNG is a single pure Python module less than 4000 lines long, including tests and comments.
PIL is a more comprehensive imaging library, but it's also significantly heavier.
It depends mostly on how much the repository is used. With one user checking in once a day and a branch/merge/etc operation once a week you probably don't need to run it more than once a year.
With several dozen developers working on several dozen projects each checking in 2-3 times a day, you might want to run it nightly.
It won't hurt to run it more frequently than needed, though.
What I'd do is run it now, then a week from now take a measurement of disk utilization, run it again, and measure disk utilization again. If it drops 5% in size, then run it once a week. If it drops more, then run it more frequently. If it drops less, then run it less frequently.
string name = "the_name_you_know";
Control ctn = this.Controls[name];
ctn.Text = "Example...";
Since question was regarding clunkiness of property checking, and one regular usecase for that being validation of function argument options objects, thought I'd mention a library-free short way of testing existence of multiple properties. Disclaimer: It does require ECMAScript 5 (but IMO anyone still using IE8 deserves a broken web).
function f(opts) {
if(!["req1","req2"].every(opts.hasOwnProperty, opts)) {
throw new Error("IllegalArgumentException");
}
alert("ok");
}
f({req1: 123}); // error
f({req1: 123, req2: 456}); // ok
Seems you are using MSSQL, then, if I remember correctly, it is done like this:
UPDATE [Sales_Lead].[dbo].[Sales_Import] SET [AccountNumber] =
RetrieveAccountNumber.AccountNumber
FROM RetrieveAccountNumber
WHERE [Sales_Lead].[dbo].[Sales_Import].LeadID = RetrieveAccountNumber.LeadID
The answer of Pardeep Jain can be useful for static data, but what if we have an array in JSON?
For example, we have i values and get the value of id field
alert(obj[i].id); //works!
But what if we need key with spaces?
In this case, the following construction can help (without point between [] blocks):
alert(obj[i]["No. of interfaces"]); //works too!
Try just:
powershell.exe -noexit D:\Work\SQLExecutor.ps1 -gettedServerName "MY-PC"
You didn't say what's currently your .gitignore
, but a .gitignore
with the following contents in your root directory should do the trick.
.metadata
build
From tom, on http://www.php.net/manual/en/function.uniqid.php
$r = unpack('v*', fread(fopen('/dev/random', 'r'),16));
$uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
$r[1], $r[2], $r[3], $r[4] & 0x0fff | 0x4000,
$r[5] & 0x3fff | 0x8000, $r[6], $r[7], $r[8])
Please check your Laravel .env
file also. Make sure DB_CONNECTION=mysql
, otherwise it won't work with MySQL. It tried to load something else.
I found myself using the HttpClient library to query RESTful APIs as the code is very straightforward and fully async'ed.
(Edit: Adding JSON from question for clarity)
{
"agent": {
"name": "Agent Name",
"version": 1
},
"username": "Username",
"password": "User Password",
"token": "xxxxxx"
}
With two classes representing the JSON-Structure you posted that may look like this:
public class Credentials
{
[JsonProperty("agent")]
public Agent Agent { get; set; }
[JsonProperty("username")]
public string Username { get; set; }
[JsonProperty("password")]
public string Password { get; set; }
[JsonProperty("token")]
public string Token { get; set; }
}
public class Agent
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("version")]
public int Version { get; set; }
}
you could have a method like this, which would do your POST request:
var payload = new Credentials {
Agent = new Agent {
Name = "Agent Name",
Version = 1
},
Username = "Username",
Password = "User Password",
Token = "xxxxx"
};
// Serialize our concrete class into a JSON String
var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(payload));
// Wrap our JSON inside a StringContent which then can be used by the HttpClient class
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");
using (var httpClient = new HttpClient()) {
// Do the actual request and await the response
var httpResponse = await httpClient.PostAsync("http://localhost/api/path", httpContent);
// If the response contains content we want to read it!
if (httpResponse.Content != null) {
var responseContent = await httpResponse.Content.ReadAsStringAsync();
// From here on you could deserialize the ResponseContent back again to a concrete C# type using Json.Net
}
}
(gdb) maintenance info sections
Exec file:
`/path/to/app.out', file type elf32-littlearm.
0x0000->0x0360 at 0x00008000: .intvecs ALLOC LOAD READONLY DATA HAS_CONTENTS
This is from comment by phihag above, deserves a separate answer. This works but info proc
does not on the arm-none-eabi-gdb v7.4.1.20130913-cvs from the gcc-arm-none-eabi Ubuntu package.
To answer the question:
What is the fastest way to stream live video using JavaScript? Is WebSockets over TCP a fast enough protocol to stream a video of, say, 30fps?
Yes, Websocket can be used to transmit over 30 fps and even 60 fps.
The main issue with Websocket is that it is low-level and you have to deal with may other issues than just transmitting video chunks. All in all it's a great transport for video and also audio.
Spaces only
[Note: If necessary save profile with a new name as the default profile cannot be overwritten.]
Before version 3.6:
Window->Preferences->Editors->Text Editors->Insert spaces for tabs
Version 3.6 and later:
Note that the default text editor is used as the basis for many non-Java editors in Eclipse. It's astonishing that this setting wasn't available until 3.3.
Spaces only
Follow the same instructions for HTML, but select CSS Files instead of HTML Files.
By default, JSP files follow the formatting preferences for HTML Files.
XML files spacing is configured in Preferences.
From a quick glance on MDN I think you may need to include the .js
at the end of your file name so the import would read
import './course.js'
instead of import './course'
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
This link was exactly what I was searching for .
Let me summarize the answers for others' benefit (for python and notepad++)
1) Ctrl+K on multiple lines (i.e. selected region) allows you to block comment.
Also note that pressing the combination multiple times allows you to add multiple "#"s (sometimes I use that while testing to differentiate from other comments)
2) Ctrl+Shift+K (on the commented region) allows you to perform block uncomment
3) Ctrl+Shift+K on an uncommented selected region does not comment it
4) Ctrl+Q allows you to block comment/uncomment in a toggled mode (meaning, you cannot add multiple '#'s like in 1) )
Hope this helps another wandering soul.
Question - how would you develop a hack of keyboard combinations to comment/uncomment if there were no shortcuts? Just curious. I've no clue hence asking.
If you want all the ancestors rather than just the immediate ones, use inspect.getmro:
import inspect
print inspect.getmro(cls)
Usefully, this gives you all ancestor classes in the "method resolution order" -- i.e. the order in which the ancestors will be checked when resolving a method (or, actually, any other attribute -- methods and other attributes live in the same namespace in Python, after all;-).
Rounding a double is usually not what one wants. Instead, use String.format()
to represent it in the desired format.
ID is an attribute, you can set it with the attr function:
$(element).attr('id', 'newID');
I'm not sure what you mean about adding IDs since an element can only have one identifier and this identifier must be unique.
You must link an event in your onClick. Additionally, the click function must receive the event. See the example
export default function Component(props) {
function clickEvent (event, variable){
console.log(variable);
}
return (
<div>
<IconButton
key="close"
aria-label="Close"
color="inherit"
onClick={e => clickEvent(e, 10)}
>
</div>
)
}
I think this means that module.exports
in your ./app/routes
module is not assigned to be a function so therefore require('./app/routes')
does not resolve to a function so therefore, you cannot call it as a function like this require('./app/routes')(app, passport)
.
Show us ./app/routes
if you want us to comment further on that.
It should look something like this;
module.exports = function(app, passport) {
// code here
}
You are exporting a function that can then be called like require('./app/routes')(app, passport)
.
One other reason a similar error could occur is if you have a circular module dependency where module A is trying to require(B)
and module B is trying to require(A)
. When this happens, it will be detected by the require()
sub-system and one of them will come back as null
and thus trying to call that as a function will not work. The fix in that case is to remove the circular dependency, usually by breaking common code into a third module that both can separately load though the specifics of fixing a circular dependency are unique for each situation.
yum update
helped me out. After I had
wget: symbol lookup error: wget: undefined symbol: psl_latest
I think you want to MODIFY
the column as described for the ALTER TABLE
command. It might be something like this:
ALTER TABLE users MODIFY id INTEGER NOT NULL AUTO_INCREMENT;
Before running above ensure that id
column has a Primary index.
<WebView ref={'webview'} automaticallyAdjustContentInsets={false} source={require('../Assets/aboutus.html')} />
This worked for me :) I have html text aboutus file.
In earlier versions session factory was created as below:
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
The method buildSessionFactory is deprecated from the hibernate 4 release and it is replaced with the new API. If you are using the hibernate 4.3.0 and above, your code has to be like:
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
applySettings(configuration.getProperties());
SessionFactory factory = configuration.buildSessionFactory(builder.build());
if your files contain headers and you want remove them in the output file, you can use:
for f in `ls *.txt`; do sed '2,$!d' $f >> 0.out; done
@this.ViewContext.RouteData.Values["controller"].ToString();
The locks are always taken at DB level:-
Oracle official Document:- To avoid conflicts during a transaction, a DBMS uses locks, mechanisms for blocking access by others to the data that is being accessed by the transaction. (Note that in auto-commit mode, where each statement is a transaction, locks are held for only one statement.) After a lock is set, it remains in force until the transaction is committed or rolled back. For example, a DBMS could lock a row of a table until updates to it have been committed. The effect of this lock would be to prevent a user from getting a dirty read, that is, reading a value before it is made permanent. (Accessing an updated value that has not been committed is considered a dirty read because it is possible for that value to be rolled back to its previous value. If you read a value that is later rolled back, you will have read an invalid value.)
How locks are set is determined by what is called a transaction isolation level, which can range from not supporting transactions at all to supporting transactions that enforce very strict access rules.
One example of a transaction isolation level is TRANSACTION_READ_COMMITTED, which will not allow a value to be accessed until after it has been committed. In other words, if the transaction isolation level is set to TRANSACTION_READ_COMMITTED, the DBMS does not allow dirty reads to occur. The interface Connection includes five values that represent the transaction isolation levels you can use in JDBC.
Well, you can just sort the files first, and diff the sorted files.
sort file1 > file1.sorted
sort file2 > file2.sorted
diff file1.sorted file2.sorted
You can also filter the output to report lines in file2 which are absent from file1:
diff -u file1.sorted file2.sorted | grep "^+"
As indicated in comments, you in fact do not need to sort the files. Instead, you can use a process substitution and say:
diff <(sort file1) <(sort file2)
OnClientClick="SomeMethod()"
event of that BUTTON, it return by default "true
" so after that function it do postback
for solution use
//use this code in BUTTON ==> OnClientClick="return SomeMethod();"
//and your function like this
<script type="text/javascript">
function SomeMethod(){
// put your code here
return false;
}
</script>
Go into options. You most likely have 'Manual Sort" turned on. You need to go and change to radio button to "ascending > date". You can also right click the row/column, "more sorting options". It took me forever to find this solution...
It happens when you rename the nib file. If you have already, create new nib(meaning copy current nib file contents to new nib), delete old nib file and it will solve your problem.
Edit: With new Xcode starting version 4.6.3, If you rename(with refactor feature) Controller class, it will rename nib file too and you need not worry about nib loading problem.
Please try
sudo a2enmod rewrite
or use correct apache restart command
sudo /etc/init.d/apache2 restart
I've just faced the same problem just after installed Oracle XE 11.2. After reading and consulting a DBA friend, I ran the following command:
C:\>tnsping xe
TNS Ping Utility for 64-bit Windows: Version 11.2.0.2.0 - Production on 11-ENE-2017 14:27:44
Copyright (c) 1997, 2014, Oracle. All rights reserved.
Used parameter files:
C:\oraclexe\app\oracle\product\11.2.0\server\network\admin\sqlnet.ora
Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = myLaptop)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = XE)))
OK (30 msec)
C:\>
As you can see, it takes long time to resolve, so I added an entry to hosts file as follows:
127.0.0.1 localhost
Once done, ran again the same command:
C:\>tnsping xe
TNS Ping Utility for 64-bit Windows: Version 11.2.0.2.0 - Production on 11-ENE-2
017 14:40:29
Copyright (c) 1997, 2014, Oracle. All rights reserved.
Used parameter files:
C:\oraclexe\app\oracle\product\11.2.0\server\network\admin\sqlnet.ora
Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = myLaptop)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SER
VICE_NAME = XE)))
OK (30 msec)
C:\>
As time response radically decreases, I tried my connection on sqldeveloper successfully.
The .git
at the end of the repository name is just a convention. Typically, on git servers repositories are kept in directories named project.git
. The git client and protocol honours this convention by testing for project.git
when only project
is specified.
git://[email protected]/peter/first_app.git
is not a valid git url. git repositories can be identified and accessed via various url schemes specified here. [email protected]:peter/first_app.git
is the ssh
url mentioned on that page.
git
is flexible. It allows you to track your local branch against almost any branch of any repository. While master
(your local default branch) tracking origin/master
(the remote default branch) is a popular situation, it is not universal. Many a times you may not want to do that. This is why the first git push
is so verbose. It tells git what to do with the local master
branch when you do a git pull
or a git push
.
The default for git push
and git pull
is to work with the current branch's remote. This is a better default than origin master. The way git push determines this is explained here.
git
is fairly elegant and comprehensible but there is a learning curve to walk through.
Inkscape is a vector drawing program that exports PNG images. So, you end up editing SVG documents and exporting them to PNGs. Inkscape is good if you're starting from scratch, but wouldn't be ideal if you just want to edit existing PNGs.
Note--Inkscape is open source and available for free on multiple platforms.
I have found the IIS Log files at the following location.
C:\inetpub\logs\LogFiles\
which help to fix my issue.
I am trying to contribute with another solution for the single insertion problem with the pre-9.5 versions of PostgreSQL. The idea is simply to try to perform first the insertion, and in case the record is already present, to update it:
do $$
begin
insert into testtable(id, somedata) values(2,'Joe');
exception when unique_violation then
update testtable set somedata = 'Joe' where id = 2;
end $$;
Note that this solution can be applied only if there are no deletions of rows of the table.
I do not know about the efficiency of this solution, but it seems to me reasonable enough.
Well.. for me it was Telerik JustMock Q3 2013 (13.3.1015.0) that caused the problem. Uninstalled it from VS 2013 and the problem has gone..
see also ASP.NET-MVC4 Code Not Running and http://feedback.telerik.com/Project/105/Feedback/Details/63749-unable-to-debug-asp-net-projects-with-q3-2013
One lost day and many new white hairs... Curse on you Telerik guys! ;)
It would seem that is.nan
doesn't actually have a method for data frames, unlike is.na
. So, let's fix that!
is.nan.data.frame <- function(x)
do.call(cbind, lapply(x, is.nan))
data123[is.nan(data123)] <- 0
Try moving that mysql.bak
directory out of /var/lib/mysql
to say /root/
or something. It seems like mysql is finding that and it may be causing that ERROR 1102 (42000): Incorrect database name 'mysql.bak'
error.
BUILD_NUMBER
is the current build number. You can use it in the command you execute for the job, or just use it in the script your job executes.
See the Jenkins documentation for the full list of available environment variables. The list is also available from within your Jenkins instance at http://hostname/jenkins/env-vars.html.
Looks like you have a typo -- "trustStrore" should be "trustStore", i.e.
System.setProperty("javax.net.ssl.trustStrore", "cacerts.jks");
should be:
System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");
Try formatting the date in the kendo grid as:
columns.Bound(x => x.LastUpdateDate).ClientTemplate("#= kendo.toString(LastUpdateDate, \"MM/dd/yyyy hh:mm tt\") #");
a {
outline: 0;
}
But read this before change it:
There is many solutions found on the web for this, many of which work, but to force this, so that absolutely nothing can highlight/focus once a use the following:
::-moz-focus-inner, :active, :focus {
outline:none;
border:0;
-moz-outline-style: none;
}
This just adds that little bit extra security & seals the deal!
Try to add Space widget after adding view like this:
layout.addView(view)
val space = Space(context)
space.minimumHeight = spaceInterval
layout.addView(space)