This is easily accomplished with jQuery's clone()
function.
So you must create two wrapper divs for the recaptcha. My first form's recaptcha div:
<div id="myrecap">
<?php
require_once('recaptchalib.php');
$publickey = "XXXXXXXXXXX-XXXXXXXXXXX";
echo recaptcha_get_html($publickey);
?>
</div>
The second form's div is empty (different ID). So mine is just:
<div id="myraterecap"></div>
Then the javascript is quite simple:
$(document).ready(function() {
// Duplicate our reCapcha
$('#myraterecap').html($('#myrecap').clone(true,true));
});
Probably don't need the second parameter with a true
value in clone()
, but doesn't hurt to have it... The only issue with this method is if you are submitting your form via ajax, the problem is that you have two elements that have the same name and you must me a bit more clever with the way you capture that correct element's values (the two ids for reCaptcha elements are #recaptcha_response_field
and #recaptcha_challenge_field just in case someone needs them)
Great! Now here is styling available for reCaptcha.. I just use inline styling like:
<div class="g-recaptcha" data-sitekey="XXXXXXXXXXXXXXX" style="transform: scale(1.08); margin-left: 14px;"></div>
whatever you wanna to do small customize in inline styling...
Hope it will help you!!
Please remember that Google also use reCaptcha together with
Canvas fingerprinting
to uniquely recognize User/Browsers without cookies!
For what it's worth, here is a C# sample async implementation based on HttpListener and HttpClient (I use it to be able to connect Chrome in Android devices to IIS Express, that's the only way I found...).
And If you need HTTPS support, it shouldn't require more code, just certificate configuration: Httplistener with HTTPS support
// define http://localhost:5000 and http://127.0.0.1:5000/ to be proxies for http://localhost:53068
using (var server = new ProxyServer("http://localhost:53068", "http://localhost:5000/", "http://127.0.0.1:5000/"))
{
server.Start();
Console.WriteLine("Press ESC to stop server.");
while (true)
{
var key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Escape)
break;
}
server.Stop();
}
....
public class ProxyServer : IDisposable
{
private readonly HttpListener _listener;
private readonly int _targetPort;
private readonly string _targetHost;
private static readonly HttpClient _client = new HttpClient();
public ProxyServer(string targetUrl, params string[] prefixes)
: this(new Uri(targetUrl), prefixes)
{
}
public ProxyServer(Uri targetUrl, params string[] prefixes)
{
if (targetUrl == null)
throw new ArgumentNullException(nameof(targetUrl));
if (prefixes == null)
throw new ArgumentNullException(nameof(prefixes));
if (prefixes.Length == 0)
throw new ArgumentException(null, nameof(prefixes));
RewriteTargetInText = true;
RewriteHost = true;
RewriteReferer = true;
TargetUrl = targetUrl;
_targetHost = targetUrl.Host;
_targetPort = targetUrl.Port;
Prefixes = prefixes;
_listener = new HttpListener();
foreach (var prefix in prefixes)
{
_listener.Prefixes.Add(prefix);
}
}
public Uri TargetUrl { get; }
public string[] Prefixes { get; }
public bool RewriteTargetInText { get; set; }
public bool RewriteHost { get; set; }
public bool RewriteReferer { get; set; } // this can have performance impact...
public void Start()
{
_listener.Start();
_listener.BeginGetContext(ProcessRequest, null);
}
private async void ProcessRequest(IAsyncResult result)
{
if (!_listener.IsListening)
return;
var ctx = _listener.EndGetContext(result);
_listener.BeginGetContext(ProcessRequest, null);
await ProcessRequest(ctx).ConfigureAwait(false);
}
protected virtual async Task ProcessRequest(HttpListenerContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
var url = TargetUrl.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
using (var msg = new HttpRequestMessage(new HttpMethod(context.Request.HttpMethod), url + context.Request.RawUrl))
{
msg.Version = context.Request.ProtocolVersion;
if (context.Request.HasEntityBody)
{
msg.Content = new StreamContent(context.Request.InputStream); // disposed with msg
}
string host = null;
foreach (string headerName in context.Request.Headers)
{
var headerValue = context.Request.Headers[headerName];
if (headerName == "Content-Length" && headerValue == "0") // useless plus don't send if we have no entity body
continue;
bool contentHeader = false;
switch (headerName)
{
// some headers go to content...
case "Allow":
case "Content-Disposition":
case "Content-Encoding":
case "Content-Language":
case "Content-Length":
case "Content-Location":
case "Content-MD5":
case "Content-Range":
case "Content-Type":
case "Expires":
case "Last-Modified":
contentHeader = true;
break;
case "Referer":
if (RewriteReferer && Uri.TryCreate(headerValue, UriKind.Absolute, out var referer)) // if relative, don't handle
{
var builder = new UriBuilder(referer);
builder.Host = TargetUrl.Host;
builder.Port = TargetUrl.Port;
headerValue = builder.ToString();
}
break;
case "Host":
host = headerValue;
if (RewriteHost)
{
headerValue = TargetUrl.Host + ":" + TargetUrl.Port;
}
break;
}
if (contentHeader)
{
msg.Content.Headers.Add(headerName, headerValue);
}
else
{
msg.Headers.Add(headerName, headerValue);
}
}
using (var response = await _client.SendAsync(msg).ConfigureAwait(false))
{
using (var os = context.Response.OutputStream)
{
context.Response.ProtocolVersion = response.Version;
context.Response.StatusCode = (int)response.StatusCode;
context.Response.StatusDescription = response.ReasonPhrase;
foreach (var header in response.Headers)
{
context.Response.Headers.Add(header.Key, string.Join(", ", header.Value));
}
foreach (var header in response.Content.Headers)
{
if (header.Key == "Content-Length") // this will be set automatically at dispose time
continue;
context.Response.Headers.Add(header.Key, string.Join(", ", header.Value));
}
var ct = context.Response.ContentType;
if (RewriteTargetInText && host != null && ct != null &&
(ct.IndexOf("text/html", StringComparison.OrdinalIgnoreCase) >= 0 ||
ct.IndexOf("application/json", StringComparison.OrdinalIgnoreCase) >= 0))
{
using (var ms = new MemoryStream())
{
using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
{
await stream.CopyToAsync(ms).ConfigureAwait(false);
var enc = context.Response.ContentEncoding ?? Encoding.UTF8;
var html = enc.GetString(ms.ToArray());
if (TryReplace(html, "//" + _targetHost + ":" + _targetPort + "/", "//" + host + "/", out var replaced))
{
var bytes = enc.GetBytes(replaced);
using (var ms2 = new MemoryStream(bytes))
{
ms2.Position = 0;
await ms2.CopyToAsync(context.Response.OutputStream).ConfigureAwait(false);
}
}
else
{
ms.Position = 0;
await ms.CopyToAsync(context.Response.OutputStream).ConfigureAwait(false);
}
}
}
}
else
{
using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
{
await stream.CopyToAsync(context.Response.OutputStream).ConfigureAwait(false);
}
}
}
}
}
}
public void Stop() => _listener.Stop();
public override string ToString() => string.Join(", ", Prefixes) + " => " + TargetUrl;
public void Dispose() => ((IDisposable)_listener)?.Dispose();
// out-of-the-box replace doesn't tell if something *was* replaced or not
private static bool TryReplace(string input, string oldValue, string newValue, out string result)
{
if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(oldValue))
{
result = input;
return false;
}
var oldLen = oldValue.Length;
var sb = new StringBuilder(input.Length);
bool changed = false;
var offset = 0;
for (int i = 0; i < input.Length; i++)
{
var c = input[i];
if (offset > 0)
{
if (c == oldValue[offset])
{
offset++;
if (oldLen == offset)
{
changed = true;
sb.Append(newValue);
offset = 0;
}
continue;
}
for (int j = 0; j < offset; j++)
{
sb.Append(input[i - offset + j]);
}
sb.Append(c);
offset = 0;
}
else
{
if (c == oldValue[0])
{
if (oldLen == 1)
{
changed = true;
sb.Append(newValue);
}
else
{
offset = 1;
}
continue;
}
sb.Append(c);
}
}
if (changed)
{
result = sb.ToString();
return true;
}
result = input;
return false;
}
}
'lines' term from your snippet consists of set of strings.
lines = f.readlines()
match = re.findall('[A-Z]+', lines)
You cannot send entire lines into the re.findall('pattern',<string>)
You can try to send line by line
for i in lines:
match = re.findall('[A-Z]+', i)
print match
or to convert the entire lines collection into single line (each line seperated by space)
NEW_LIST=' '.join(lines)
match=re.findall('[A-Z]+' ,NEW_LIST)
print match
This might help you
Try to replace the
padding: 2px 30px 2px 2px;
with
padding: 2px 2px 2px 2px;
It should work.
You can send the FormData object in ajax request using the following code,
$("form#formElement").submit(function(){
var formData = new FormData($(this)[0]);
});
This is very similar to the accepted answer but an actual answer to the question topic. This will submit the form elements automatically in the FormData and you don't need to manually append the data to FormData variable.
The ajax method looks like this,
$("form#formElement").submit(function(){
var formData = new FormData($(this)[0]);
//append some non-form data also
formData.append('other_data',$("#someInputData").val());
$.ajax({
type: "POST",
url: postDataUrl,
data: formData,
processData: false,
contentType: false,
dataType: "json",
success: function(data, textStatus, jqXHR) {
//process data
},
error: function(data, textStatus, jqXHR) {
//process error msg
},
});
You can also manually pass the form element inside the FormData object as a parameter like this
var formElem = $("#formId");
var formdata = new FormData(formElem[0]);
Hope it helps. ;)
Gone through the already posted answers. Just thought it would be better if I add an answer with actual example.
Let' say you have 3 Django models which are related.
class M1(models.Model):
name = models.CharField(max_length=10)
class M2(models.Model):
name = models.CharField(max_length=10)
select_relation = models.ForeignKey(M1, on_delete=models.CASCADE)
prefetch_relation = models.ManyToManyField(to='M3')
class M3(models.Model):
name = models.CharField(max_length=10)
Here you can query M2
model and its relative M1
objects using select_relation
field and M3
objects using prefetch_relation
field.
However as we've mentioned M1
's relation from M2
is a ForeignKey
, it just returns only 1 record for any M2
object. Same thing applies for OneToOneField
as well.
But M3
's relation from M2
is a ManyToManyField
which might return any number of M1
objects.
Consider a case where you have 2 M2
objects m21
, m22
who have same 5 associated M3
objects with IDs 1,2,3,4,5
. When you fetch associated M3
objects for each of those M2
objects, if you use select related, this is how it's going to work.
Steps:
m21
object.M3
objects related to m21
object whose IDs are 1,2,3,4,5
.m22
object and all other M2
objects.As we have same 1,2,3,4,5
IDs for both m21
, m22
objects, if we use select_related option, it's going to query the DB twice for the same IDs which were already fetched.
Instead if you use prefetch_related, when you try to get M2
objects, it will make a note of all the IDs that your objects returned (Note: only the IDs) while querying M2
table and as last step, Django is going to make a query to M3
table with the set of all IDs that your M2
objects have returned. and join them to M2
objects using Python instead of database.
This way you're querying all the M3
objects only once which improves performance.
UPDATE a
SET a.column1 = b.column2
FROM myTable a
INNER JOIN myTable b
on a.myID = b.myID
in order for both "a" and "b" to work, both aliases must be defined
First select the text
To convert lowercase to uppercase, press Ctrl+Shift+U
To convert uppercase to lowercase, press Ctrl+U
The set
statement doesn't treat spaces the way you expect; your variable is really named Pathname[space]
and is equal to [space]C:\Program Files
.
Remove the spaces from both sides of the =
sign, and put the value in double quotes:
set Pathname="C:\Program Files"
Also, if your command prompt is not open to C:\, then using cd
alone can't change drives.
Use
cd /d %Pathname%
or
pushd %Pathname%
instead.
----Ctrl + c then choose Y from the Y/N option provided.
Python sequence slice addresses can be written as a[start:end:step] and any of start, stop or end can be dropped. a[::3]
is every third element of the sequence.
I had a problem like this! I was able to fix it following
Step 1>>from Abraar Arique post, I went into the console>> Went under Style Editor and found Firefox wasn't loading the updated copy of my css file.
I cleared all history and reload the page then my problem was fixed.
Well, you can do css tables instead of html tables. This keeps your html semantically correct, but allows you to use tables for layout purposes.
This seems to make more sense than using float hacks.
<html>
<head>
<style>
#content-wrapper{
display:table;
}
#content{
display:table-row;
}
#content>div{
display:table-cell
}
/*adding some extras for demo purposes*/
#content-wrapper{
width:100%;
height:100%;
top:0px;
left:0px;
position:absolute;
}
#nav{
width:100px;
background:yellow;
}
#body{
background:blue;
}
</style>
</head>
<body>
<div id="content-wrapper">
<div id="content">
<div id="nav">
Left hand content
</div>
<div id="body">
Right hand content
</div>
</div>
</div>
</body>
</html>
It skips all whitespace (spaces, tabs, new lines, etc.) by default. You can either change its behavior, or use a slightly different mechanism. To change its behavior, use the manipulator noskipws
, as follows:
cin >> noskipws >> a[i];
But, since you seem like you want to look at the individual characters, I'd suggest using get
, like this prior to your loop
cin.get( a, n );
Note: get
will stop retrieving chars from the stream if it either finds a newline char (\n
) or after n-1 chars. It stops early so that it can append the null character (\0
) to the array. You can read more about the istream
interface here.
try this ( stringWithFormat has to start with lowercase)
[NSString stringWithFormat:@"%@\n%@",string1,string2];
This will return an MD5 hash for a file on a remote computer:
Invoke-Command -ComputerName RemoteComputerName -ScriptBlock {
$fullPath = Resolve-Path 'c:\Program Files\Internet Explorer\iexplore.exe'
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$file = [System.IO.File]::OpenRead($fullPath)
$hash = [System.BitConverter]::ToString($md5.ComputeHash($file))
$hash -replace "-", ""
$file.Dispose()
}
You have to return a promise instead of a variable. So in your function just return:
return relationsManagerResource.GetParentId(nodeId)
And later resolve the returned promise.
Or you can make another deferred and resolve theParentId
with it.
use lodash
GLOBAL.utils = require('lodash')
var arr1 = ['first' , 'second'];
var arr2 = ['second '];
var result = utils.difference(arr1 , arr2);
console.log ( "result :" + result );
Chrome Extensions don't allow you to have inline JavaScript (documentation).
The same goes for Firefox WebExtensions (documentation).
You are going to have to do something similar to this:
Assign an ID to the link (<a onClick=hellYeah("xxx")>
becomes <a id="link">
), and use addEventListener
to bind the event. Put the following in your popup.js
file:
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('link');
// onClick's logic below:
link.addEventListener('click', function() {
hellYeah('xxx');
});
});
popup.js
should be loaded as a separate script file:
<script src="popup.js"></script>
Is your application running as a 64 or 32bit process? You can check this in the task manager.
It could be, it is running as 32bit, even though the entire system is running on 64bit.
If 32bit, a third party library could be causing this. But first make sure your application is compiling for "Any CPU", as stated in the comments.
Microsoft's Using sp_executesql article recommends using sp_executesql
instead of execute
statement.
Because this stored procedure supports parameter substitution, sp_executesql is more versatile than EXECUTE; and because sp_executesql generates execution plans that are more likely to be reused by SQL Server, sp_executesql is more efficient than EXECUTE.
So, the take away: Do not use execute
statement. Use sp_executesql
.
I'd add Commons NullComparator instead to avoid some problems...
This is for windows environment:
I got the Initial Admin password under C:\Users\Deepak("MyUser").jenkins\secrets\initialAdminPassword
I was able to login with user "admin" and above password. Then under Jenkins> people I edited the password of the user and clicked on apply to reflect the changes.
.timeline {_x000D_
list-style: none;_x000D_
padding: 20px 0 20px;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.timeline:before {_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
position: absolute;_x000D_
content: " ";_x000D_
width: 3px;_x000D_
background-color: #eeeeee;_x000D_
left: 50%;_x000D_
margin-left: -1.5px;_x000D_
}_x000D_
_x000D_
.timeline > li {_x000D_
margin-bottom: 20px;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.timeline > li:before,_x000D_
.timeline > li:after {_x000D_
content: " ";_x000D_
display: table;_x000D_
}_x000D_
_x000D_
.timeline > li:after {_x000D_
clear: both;_x000D_
}_x000D_
_x000D_
.timeline > li:before,_x000D_
.timeline > li:after {_x000D_
content: " ";_x000D_
display: table;_x000D_
}_x000D_
_x000D_
.timeline > li:after {_x000D_
clear: both;_x000D_
}_x000D_
_x000D_
.timeline > li > .timeline-panel {_x000D_
width: 46%;_x000D_
float: left;_x000D_
border: 1px solid #d4d4d4;_x000D_
border-radius: 2px;_x000D_
padding: 20px;_x000D_
position: relative;_x000D_
-webkit-box-shadow: 0 1px 6px rgba(0, 0, 0, 0.175);_x000D_
box-shadow: 0 1px 6px rgba(0, 0, 0, 0.175);_x000D_
}_x000D_
_x000D_
.timeline > li > .timeline-panel:before {_x000D_
position: absolute;_x000D_
top: 26px;_x000D_
right: -15px;_x000D_
display: inline-block;_x000D_
border-top: 15px solid transparent;_x000D_
border-left: 15px solid #ccc;_x000D_
border-right: 0 solid #ccc;_x000D_
border-bottom: 15px solid transparent;_x000D_
content: " ";_x000D_
}_x000D_
_x000D_
.timeline > li > .timeline-panel:after {_x000D_
position: absolute;_x000D_
top: 27px;_x000D_
right: -14px;_x000D_
display: inline-block;_x000D_
border-top: 14px solid transparent;_x000D_
border-left: 14px solid #fff;_x000D_
border-right: 0 solid #fff;_x000D_
border-bottom: 14px solid transparent;_x000D_
content: " ";_x000D_
}_x000D_
_x000D_
.timeline > li > .timeline-badge {_x000D_
color: #fff;_x000D_
width: 50px;_x000D_
height: 50px;_x000D_
line-height: 50px;_x000D_
font-size: 1.4em;_x000D_
text-align: center;_x000D_
position: absolute;_x000D_
top: 16px;_x000D_
left: 50%;_x000D_
margin-left: -25px;_x000D_
background-color: #999999;_x000D_
z-index: 100;_x000D_
border-top-right-radius: 50%;_x000D_
border-top-left-radius: 50%;_x000D_
border-bottom-right-radius: 50%;_x000D_
border-bottom-left-radius: 50%;_x000D_
}_x000D_
_x000D_
.timeline > li.timeline-inverted > .timeline-panel {_x000D_
float: right;_x000D_
}_x000D_
_x000D_
.timeline > li.timeline-inverted > .timeline-panel:before {_x000D_
border-left-width: 0;_x000D_
border-right-width: 15px;_x000D_
left: -15px;_x000D_
right: auto;_x000D_
}_x000D_
_x000D_
.timeline > li.timeline-inverted > .timeline-panel:after {_x000D_
border-left-width: 0;_x000D_
border-right-width: 14px;_x000D_
left: -14px;_x000D_
right: auto;_x000D_
}_x000D_
_x000D_
.timeline-badge.primary {_x000D_
background-color: #2e6da4 !important;_x000D_
}_x000D_
_x000D_
.timeline-badge.success {_x000D_
background-color: #3f903f !important;_x000D_
}_x000D_
_x000D_
.timeline-badge.warning {_x000D_
background-color: #f0ad4e !important;_x000D_
}_x000D_
_x000D_
.timeline-badge.danger {_x000D_
background-color: #d9534f !important;_x000D_
}_x000D_
_x000D_
.timeline-badge.info {_x000D_
background-color: #5bc0de !important;_x000D_
}_x000D_
_x000D_
.timeline-title {_x000D_
margin-top: 0;_x000D_
color: inherit;_x000D_
}_x000D_
_x000D_
.timeline-body > p,_x000D_
.timeline-body > ul {_x000D_
margin-bottom: 0;_x000D_
}_x000D_
_x000D_
.timeline-body > p + p {_x000D_
margin-top: 5px;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="page-header">_x000D_
<h1 id="timeline">Timeline</h1>_x000D_
</div>_x000D_
<ul class="timeline">_x000D_
<li>_x000D_
<div class="timeline-badge"><i class="glyphicon glyphicon-check"></i></div>_x000D_
<div class="timeline-panel">_x000D_
<p><small class="text-muted"><i class="glyphicon glyphicon-time"></i> 11 hours ago via Twitter</small></p>_x000D_
<div class="timeline-heading">_x000D_
<h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
<p><small class="text-muted"><i class="glyphicon glyphicon-time"></i> 11 hours ago via Twitter</small></p>_x000D_
</div>_x000D_
<div class="timeline-body">_x000D_
<p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
</div>_x000D_
</div>_x000D_
</li>_x000D_
<li class="timeline-inverted">_x000D_
<div class="timeline-badge warning"><i class="glyphicon glyphicon-credit-card"></i></div>_x000D_
<div class="timeline-panel">_x000D_
<div class="timeline-heading">_x000D_
<h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
</div>_x000D_
<div class="timeline-body">_x000D_
<p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
<p>Suco de cevadiss, é um leite divinis, qui tem lupuliz, matis, aguis e fermentis. Interagi no mé, cursus quis, vehicula ac nisi. Aenean vel dui dui. Nullam leo erat, aliquet quis tempus a, posuere ut mi. Ut scelerisque neque et turpis posuere_x000D_
pulvinar pellentesque nibh ullamcorper. Pharetra in mattis molestie, volutpat elementum justo. Aenean ut ante turpis. Pellentesque laoreet mé vel lectus scelerisque interdum cursus velit auctor. Lorem ipsum dolor sit amet, consectetur adipiscing_x000D_
elit. Etiam ac mauris lectus, non scelerisque augue. Aenean justo massa.</p>_x000D_
</div>_x000D_
</div>_x000D_
</li>_x000D_
<li>_x000D_
<div class="timeline-badge danger"><i class="glyphicon glyphicon-credit-card"></i></div>_x000D_
<div class="timeline-panel">_x000D_
<div class="timeline-heading">_x000D_
<h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
</div>_x000D_
<div class="timeline-body">_x000D_
<p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
</div>_x000D_
</div>_x000D_
</li>_x000D_
<li class="timeline-inverted">_x000D_
<div class="timeline-panel">_x000D_
<div class="timeline-heading">_x000D_
<h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
</div>_x000D_
<div class="timeline-body">_x000D_
<p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
</div>_x000D_
</div>_x000D_
</li>_x000D_
<li>_x000D_
<div class="timeline-badge info"><i class="glyphicon glyphicon-floppy-disk"></i></div>_x000D_
<div class="timeline-panel">_x000D_
<div class="timeline-heading">_x000D_
<h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
</div>_x000D_
<div class="timeline-body">_x000D_
<p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
<hr>_x000D_
<div class="btn-group">_x000D_
<button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown">_x000D_
<i class="glyphicon glyphicon-cog"></i> <span class="caret"></span>_x000D_
</button>_x000D_
<ul class="dropdown-menu" role="menu">_x000D_
<li><a href="#">Action</a></li>_x000D_
<li><a href="#">Another action</a></li>_x000D_
<li><a href="#">Something else here</a></li>_x000D_
<li class="divider"></li>_x000D_
<li><a href="#">Separated link</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</li>_x000D_
<li>_x000D_
<div class="timeline-panel">_x000D_
<div class="timeline-heading">_x000D_
<h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
</div>_x000D_
<div class="timeline-body">_x000D_
<p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
</div>_x000D_
</div>_x000D_
</li>_x000D_
<li class="timeline-inverted">_x000D_
<div class="timeline-badge success"><i class="glyphicon glyphicon-thumbs-up"></i></div>_x000D_
<div class="timeline-panel">_x000D_
<div class="timeline-heading">_x000D_
<h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
</div>_x000D_
<div class="timeline-body">_x000D_
<p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
</div>_x000D_
</div>_x000D_
</li>_x000D_
</ul>_x000D_
</div>
_x000D_
If possible, you should declare the variables that you need to keep alive that haven't been clear by Garbage Collector or Unload by OS in file .so To do it, you must code by C/C++ and compile to .so lib file and load it in your MainActivity.
<!DOCTYPE html>
<html>
<head>
<script>
var clicks = 0;
function myFunction() {
clicks += 1;
document.getElementById("demo").innerHTML = clicks;
}
</script>
</head>
<body>
<p>Click the button to trigger a function.</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body>
</html>
This should work for you :) Yes var should be used
In Python 3.8 the dirs_exist_ok
keyword argument was added to shutil.copytree()
:
dirs_exist_ok
dictates whether to raise an exception in casedst
or any missing parent directory already exists.
So, the following will work in recent versions of Python, even if the destination directory already exists:
shutil.copytree(src, dest, dirs_exist_ok=True) # 3.8+ only!
One major benefit is that it's more flexible than distutils.dir_util.copy_tree()
as it takes additional arguments on files to ignore, etc. There is also a draft PEP (PEP 632, associated discussion), which suggests that distutils
may be deprecated and then removed in future versions of Python 3.
The method could vary depending on your needs. Here are 3 ways to calculate Luminance:
Luminance (standard for certain colour spaces): (0.2126*R + 0.7152*G + 0.0722*B)
source
Luminance (perceived option 1): (0.299*R + 0.587*G + 0.114*B)
source
Luminance (perceived option 2, slower to calculate): ? sqrt( 0.241*R^2 + 0.691*G^2 + 0.068*B^2 )
sqrt( 0.299*R^2 + 0.587*G^2 + 0.114*B^2 )
(thanks to @MatthewHerbst) source
[Edit: added examples using named css colors sorted with each method.]
This is a very old question, but I found a new solution, so I wrote about it.
First of all, is this way of solution possible while using AutoGenerateColumns?
Yes, that can be done with AttachedProperty as follows.
<DataGrid AutoGenerateColumns="True"
local:DataGridOperation.DateTimeFormatAutoGenerate="yy-MM-dd"
ItemsSource="{Binding}" />
There are two AttachedProperty defined that allow you to specify two formats.
DateTimeFormatAutoGenerate
for DateTime
and TimeSpanFormatAutoGenerate
for TimeSpan
.
class DataGridOperation
{
public static string GetDateTimeFormatAutoGenerate(DependencyObject obj) => (string)obj.GetValue(DateTimeFormatAutoGenerateProperty);
public static void SetDateTimeFormatAutoGenerate(DependencyObject obj, string value) => obj.SetValue(DateTimeFormatAutoGenerateProperty, value);
public static readonly DependencyProperty DateTimeFormatAutoGenerateProperty =
DependencyProperty.RegisterAttached("DateTimeFormatAutoGenerate", typeof(string), typeof(DataGridOperation),
new PropertyMetadata(null, (d, e) => AddEventHandlerOnGenerating<DateTime>(d, e)));
public static string GetTimeSpanFormatAutoGenerate(DependencyObject obj) => (string)obj.GetValue(TimeSpanFormatAutoGenerateProperty);
public static void SetTimeSpanFormatAutoGenerate(DependencyObject obj, string value) => obj.SetValue(TimeSpanFormatAutoGenerateProperty, value);
public static readonly DependencyProperty TimeSpanFormatAutoGenerateProperty =
DependencyProperty.RegisterAttached("TimeSpanFormatAutoGenerate", typeof(string), typeof(DataGridOperation),
new PropertyMetadata(null, (d, e) => AddEventHandlerOnGenerating<TimeSpan>(d, e)));
private static void AddEventHandlerOnGenerating<T>(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is DataGrid dGrid))
return;
if ((e.NewValue is string format))
dGrid.AutoGeneratingColumn += (o, e) => AddFormat_OnGenerating<T>(e, format);
}
private static void AddFormat_OnGenerating<T>(DataGridAutoGeneratingColumnEventArgs e, string format)
{
if (e.PropertyType == typeof(T))
(e.Column as DataGridTextColumn).Binding.StringFormat = format;
}
}
<Window
x:Class="DataGridAutogenerateCustom.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DataGridAutogenerateCustom"
Width="400" Height="250">
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<StackPanel>
<TextBlock Text="DEFAULT FORMAT" />
<DataGrid ItemsSource="{Binding Dates}" />
<TextBlock Margin="0,30,0,0" Text="CUSTOM FORMAT" />
<DataGrid
local:DataGridOperation.DateTimeFormatAutoGenerate="yy-MM-dd"
local:DataGridOperation.TimeSpanFormatAutoGenerate="dd\-hh\-mm\-ss"
ItemsSource="{Binding Dates}" />
</StackPanel>
</Window>
public class MainWindowViewModel
{
public DatePairs[] Dates { get; } = new DatePairs[]
{
new (){StartDate= new (2011,1,1), EndDate= new (2011,2,1) },
new (){StartDate= new (2020,1,1), EndDate= new (2021,1,1) },
};
}
public class DatePairs
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public TimeSpan Span => EndDate - StartDate;
}
It will definitely cost you more space & bandwidth if you want to use base64 encoded images. However if your site has a lot of small images you can decrease the page loading time by encoding your images to base64 and placing them into html. In this way, the client browser wont need to make a lot of connections to the images, but will have them in html.
It's not really a bug, just a difference in implantation by the browser vendors.
As a rule avoid browser sniffing. There is a nifty jQuery fix which is hinted at in the answers.
This is what works for me: $('html:not(:animated),body:not(:animated)').scrollTop()
mysql> CREATE USER 'monty'@'192.168.%.%' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'192.168.%.%'
When you loop in an array like you did, your for variable(in this example i
) is current element of your array.
For example if your ar
is [1,5,10]
, the i
value in each iteration is 1
, 5
, and 10
.
And because your array length is 3, the maximum index you can use is 2. so when i = 5
you get IndexError
.
You should change your code into something like this:
for i in ar:
theSum = theSum + i
Or if you want to use indexes, you should create a range from 0 ro array length - 1
.
for i in range(len(ar)):
theSum = theSum + ar[i]
I agree with Scott Helme's point in another answer here. But in some extreme situations (security issues, API breaking changes...) where you absolutely need the users to update to continue using the app, you could provide a simple versioning API. The API would look like this:
versionCheck API:
Request parameters:
int appVersion
Response
boolean forceUpgrade
boolean recommendUpgrade
When your app starts, you could call this API that pass in the current app version, and check the response of the versioning API call.
If forceUpgrade
is true
, show a popup dialog with options to either let user quit the app, or go to Google Play Store to upgrade the app.
Else if recommendUpgrade
is true
, show the pop-up dialog with options to update or to continue using the app.
Even with this forced upgrade ability in place, you should continue to support older versions, unless absolutely needed.
You are asking a question about two different things:
Meta
inner class in Django models:
This is just a class container with some options (metadata) attached to the model. It defines such things as available permissions, associated database table name, whether the model is abstract or not, singular and plural versions of the name etc.
Short explanation is here: Django docs: Models: Meta options
List of available meta options is here: Django docs: Model Meta options
For latest version of Django: Django docs: Model Meta options
Metaclass in Python:
The best description is here: What are metaclasses in Python?
Use
__DIR__
to get the current path of the script and this should fix your problem.
So:
require_once(__DIR__.'/../class/user.php');
This will prevent cases where you can run a PHP script from a different folder and therefore the relatives paths will not work.
Edit: slash problem fixed
i remember this from reading some articles about performance in unity from internet which awaring javascript users from using it in unity about really massive issues of using javascript in unity instead of C#, it says that C# is almost 4x faster than javascript!
i really appreciate that article b/c it saved my ass when i was about to start gaming, i dont mean that javascript it bad for unity developers , it is good but my advice could be that if you like using javascript, you should use it for simple small gamesNOT FOR BIG PROJECTS because it really can be a damn problem!
You are mixing the 2 different CASE
syntaxes inappropriately.
Use this style (Searched)
CASE
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Or this style (Simple)
CASE u.nnmu
WHEN '0' THEN mu.naziv_mesta
WHEN '1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Not This (Simple but with boolean search predicates)
CASE u.nnmu
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
In MySQL this will end up testing whether u.nnmu
is equal to the value of the boolean expression u.nnmu ='0'
itself. Regardless of whether u.nnmu
is 1
or 0
the result of the case expression itself will be 1
For example if nmu = '0'
then (nnmu ='0'
) evaluates as true
(1) and (nnmu ='1'
) evaluates as false
(0). Substituting these into the case expression gives
SELECT CASE '0'
WHEN 1 THEN '0'
WHEN 0 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
if nmu = '1'
then (nnmu ='0'
) evaluates as false
(0) and (nnmu ='1'
) evaluates as true
(1). Substituting these into the case expression gives
SELECT CASE '1'
WHEN 0 THEN '0'
WHEN 1 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
Working on the same idea as above , but generalizing a bit . Since the backspace should work fine on the input elements , but should not work if the focus is a paragraph or something , since it is there where the page tends to go back to the previous page in history .
$('html').on('keydown' , function(event) {
if(! $(event.target).is('input')) {
console.log(event.which);
//event.preventDefault();
if(event.which == 8) {
// alert('backspace pressed');
return false;
}
}
});
returning false => both event.preventDefault and event.stopPropagation are in effect .
I got same error in my Micro-service, whenever you declare @Value annotation in program i.e @Value("${project.api.key}")
make sure that your application.properties file with same values should not be blank project.api.key= add some values
MostIMP :otherwise it will throw error "Error creating bean with name 'ServiceFTP': Injection of autowired dependencies"
There is no difference between moving and renaming; you should simply call Directory.Move
.
In general, if you're only doing a single operation, you should use the static
methods in the File
and Directory
classes instead of creating FileInfo
and DirectoryInfo
objects.
For more advice when working with files and directories, see here.
function configureDropDownLists(ddl1, ddl2) {_x000D_
var colours = ['Black', 'White', 'Blue'];_x000D_
var shapes = ['Square', 'Circle', 'Triangle'];_x000D_
var names = ['John', 'David', 'Sarah'];_x000D_
_x000D_
switch (ddl1.value) {_x000D_
case 'Colours':_x000D_
ddl2.options.length = 0;_x000D_
for (i = 0; i < colours.length; i++) {_x000D_
createOption(ddl2, colours[i], colours[i]);_x000D_
}_x000D_
break;_x000D_
case 'Shapes':_x000D_
ddl2.options.length = 0;_x000D_
for (i = 0; i < shapes.length; i++) {_x000D_
createOption(ddl2, shapes[i], shapes[i]);_x000D_
}_x000D_
break;_x000D_
case 'Names':_x000D_
ddl2.options.length = 0;_x000D_
for (i = 0; i < names.length; i++) {_x000D_
createOption(ddl2, names[i], names[i]);_x000D_
}_x000D_
break;_x000D_
default:_x000D_
ddl2.options.length = 0;_x000D_
break;_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
function createOption(ddl, text, value) {_x000D_
var opt = document.createElement('option');_x000D_
opt.value = value;_x000D_
opt.text = text;_x000D_
ddl.options.add(opt);_x000D_
}
_x000D_
<select id="ddl" onchange="configureDropDownLists(this,document.getElementById('ddl2'))">_x000D_
<option value=""></option>_x000D_
<option value="Colours">Colours</option>_x000D_
<option value="Shapes">Shapes</option>_x000D_
<option value="Names">Names</option>_x000D_
</select>_x000D_
_x000D_
<select id="ddl2">_x000D_
</select>
_x000D_
if you want to scroll within a particular view/frame (WebElement), what you only need to do is to replace "body" with a particular element that you intend to scroll within. i get that element via "getElementById" in the example below:
self.driver.execute_script('window.scrollTo(0, document.getElementById("page-manager").scrollHeight);')
this is the case on YouTube, for example...
See the first answer to Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++
Then just loop over all the elements in cout << M.at<double>(0,0);
rather than just 0,0
Or better still with the C++ interface:
cv::Mat M;
cout << "M = " << endl << " " << M << endl << endl;
My favorite no-conflict-friendly construct:
jQuery(function($) {
// ...
});
Calling jQuery with a function pointer is a shortcut for $(document).ready(...)
Or as we say in coffeescript:
jQuery ($) ->
# code here
Just running through a Visual Studio Code tutorial and came across a similiar issue.
Replace #include "stdafx.h"
with #include "pch.h"
which is the updated name for the precompiled headers.
In lodash you can use _.includes (which also aliases to _.contains)
You can search the whole array:
_.includes([1, 2, 3], 1); // true
You can search the array from a starting index:
_.includes([1, 2, 3], 1, 1); // false (begins search at index 1)
Search a string:
_.includes('pebbles', 'eb'); // true (string contains eb)
Also works for checking simple arrays of objects:
_.includes({ 'user': 'fred', 'age': 40 }, 'fred'); // true
_.includes({ 'user': 'fred', 'age': false }, false); // true
One thing to note about the last case is it works for primitives like strings, numbers and booleans but cannot search through arrays or objects
_.includes({ 'user': 'fred', 'age': {} }, {}); // false
_.includes({ 'user': [1,2,3], 'age': {} }, 3); // false
If your image is part of the logo why not do this:
<h1><img src="img/logo.png" alt="logo" /> My website name</h1>
Use CSS to style it better.
And it is also best practice to make your logo a hyperlink that take the user back to the home page.
So you could do:
<h1 id="logo"><a href="/"><img src="img/logo.png" alt="logo" /> My website name</a></h1>
UPDATE: as noted by mdsumner, the original code is already vectorised because substr is. Should have been more careful.
And if you want a vectorised version (based on Andrie's code)
substrRight <- function(x, n){
sapply(x, function(xx)
substr(xx, (nchar(xx)-n+1), nchar(xx))
)
}
> substrRight(c("12345","ABCDE"),2)
12345 ABCDE
"45" "DE"
Note that I have changed (nchar(x)-n)
to (nchar(x)-n+1)
to get n
characters.
Use the Character.toString(char)
method.
Its easy to do using Google's Guava library.
e.g. Objects.equal(name, name2) && Objects.equal(age, age2) && ...
More examples:
So this is what I did:
I read the basics about filters here and I figured out that I need to create a custom filter that will be first in the filter chain and will have a try catch to catch all runtime exceptions that might occur there. Then i need to create the json manually and put it in the response.
So here is my custom filter:
public class ExceptionHandlerFilter extends OncePerRequestFilter {
@Override
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
try {
filterChain.doFilter(request, response);
} catch (RuntimeException e) {
// custom error response class used across my project
ErrorResponse errorResponse = new ErrorResponse(e);
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
response.getWriter().write(convertObjectToJson(errorResponse));
}
}
public String convertObjectToJson(Object object) throws JsonProcessingException {
if (object == null) {
return null;
}
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(object);
}
}
And then i added it in the web.xml before the CorsFilter
. And it works!
<filter>
<filter-name>exceptionHandlerFilter</filter-name>
<filter-class>xx.xxxxxx.xxxxx.api.controllers.filters.ExceptionHandlerFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>exceptionHandlerFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
When I needed HTML to PDF conversion earlier this year, I tried the trial of Winnovative HTML to PDF converter (I think ExpertPDF is the same product, too). It worked great so we bought a license at that company. I don't go into it too in depth after that.
<@include>
- The directive tag instructs the JSP compiler to merge contents of the included file into the JSP before creating the generated servlet code. It is the equivalent to cutting and pasting the text from your include page right into your JSP.
<jsp:include>
- The JSP Action tag on the other hand instructs the container to pause the execution of this page, go run the included page, and merge the output from that page into the output from this page.
Depending on your needs, you may either use
<@include>
or<jsp:include>
For newer versions of Laravel, please replace protected $redirectTo = RouteServiceProvider::HOME;
with protected $redirectTo = '/newurl';
and replace newurl
accordingly.
Tested with Laravel version-6
In the SQL Server Management Studio, to find out details of the active transaction, execute following command
DBCC opentran()
You will get the detail of the active transaction, then from the SPID of the active transaction, get the detail about the SPID using following commands
exec sp_who2 <SPID>
exec sp_lock <SPID>
For example, if SPID is 69 then execute the command as
exec sp_who2 69
exec sp_lock 69
Now , you can kill that process using the following command
KILL 69
I hope this helps :)
If performance is a concern, I would use operator.itemgetter
instead of lambda
as built-in functions perform faster than hand-crafted functions. The itemgetter
function seems to perform approximately 20% faster than lambda
based on my testing.
From https://wiki.python.org/moin/PythonSpeed:
Likewise, the builtin functions run faster than hand-built equivalents. For example, map(operator.add, v1, v2) is faster than map(lambda x,y: x+y, v1, v2).
Here is a comparison of sorting speed using lambda
vs itemgetter
.
import random
import operator
# Create a list of 100 dicts with random 8-letter names and random ages from 0 to 100.
l = [{'name': ''.join(random.choices(string.ascii_lowercase, k=8)), 'age': random.randint(0, 100)} for i in range(100)]
# Test the performance with a lambda function sorting on name
%timeit sorted(l, key=lambda x: x['name'])
13 µs ± 388 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# Test the performance with itemgetter sorting on name
%timeit sorted(l, key=operator.itemgetter('name'))
10.7 µs ± 38.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# Check that each technique produces the same sort order
sorted(l, key=lambda x: x['name']) == sorted(l, key=operator.itemgetter('name'))
True
Both techniques sort the list in the same order (verified by execution of the final statement in the code block), but the first one is a little faster.
You can get value (true/false) by these two method
$("input[type='checkbox']").prop("checked");
$("input[type='checkbox']").is(":checked");
I got this issue when I used an ajax call to retrieve data from the database. When the controller returned the array it converted it to a boolean. The problem was that I had "invalid characters" like ú (u with accent).
Using top
instead of margin-top
is another possible solution, if appropriate.
I would join @Nicholas in recommending PyInstaller (with the --onefile
flag), but be warned: do not use the "latest release", PyInstaller 1.3 -- it's years old. Use the "pre-release" 1.4, download it here -- or even better the code from the svn repo -- install SVN and run svn co http://svn.pyinstaller.org/trunk pyinstaller
.
As @Nicholas implies, dynamic libraries cannot be run from the same file as the rest of the executable -- but fortunately they can be packed together with all the rest in a "self-unpacking" executable that will unpack itself into some temporary directory as needed; PyInstaller does a good job at this (and at many other things -- py2exe
is more popular, but pyinstaller
in my opinion is preferable in all other respects).
string result = myList.FirstOrDefault(x => x == myString)
if(result != null)
{
//found
}
Wow this was super annoying! Honestly I don't know what the problem was because I've uploaded many apps to the appstore via Xcode over the past few years but past couple days I tried like 8 different build uploads over span of 12 hours but NONE of them would show up in iTunesConnect as Processing or anywhere else. I eventually tried Application Loader even though I've NEVER had to use that before. The first try timed out "Fetching Apple Connect token" or something. I CMD+Q and tried Application Loader again and the 2nd time the upload finished ... and now my build shows up in iTunesConnect as processing. OMG that was annoying, confusing and a huge waste of time (typical Apple Dev experience I guess).
Anyhow ... thought I would share my results.
To have unique Categories:
var uniqueCategories = repository.GetAllProducts()
.Select(p=>p.Category)
.Distinct();
The jQuery method .data()
updates an internal object managed by jQuery through the use of the method, if I'm correct.
If you'd like to update your data-attributes
with some spread, use --
$('body').attr({ 'data-test': 'text' });
-- otherwise, $('body').attr('data-test', 'text');
will work just fine.
Another way you could accomplish this is using --
$.extend( $('body')[0].dataset, { datum: true } );
-- which restricts any attribute change to HTMLElement.prototype.dataset
, not any additional HTMLElement.prototype.attributes
.
Short explanation looks like:
If you having troubles with interpreting results you could try BM.Sense results analysis service
You can use font-weight:100
or lighter: this is working with i.e. Opera 16 and older, but I do not know why the h1
tags in Firefox are bolder, sorry.
Sorry, the short answer is no. CSS (2.1) will only mark up the elements of a DOM, not their attributes. You'd have to apply a specific class to each input.
Bummer I know, because that would be incredibly useful.
I know you've said you'd prefer CSS over JavaScript, but you should still consider using jQuery. It provides a very clean and elegant way of adding styles to DOM elements based on attributes.
A simple solution to exclude everything but integer numbers
<input
type="number"
min="1"
step="1"
onkeypress="return event.keyCode === 8 || event.charCode >= 48 && event.charCode <= 57">
_x000D_
This is probably desirable for backwards compatibility.
Python3 breaks backwards compatibility, and programs invoking 'python' probably expect python2. You probably have many programs and scripts which you are not even aware of which expect python=python2, and changing this would break those programs and scripts.
The answer you are probably looking for is You should not change this.
You could, however, make a custom alias in your shell. The way you do so depends on the shell, but perhaps you could do alias py=python3
If you are confused about how to start the latest version of python, it is at least the case on Linux that python3
leaves your python2
installation intact (due to the above compatibility reasons); thus you can start python3 with the python3
command.
Create Table:
Create Table EmployeeProfile (
EmpId int,
EmpName varchar(50) not null,
EmpPhoto varbinary(max) not null )
Go
Insert statement:
Insert EmployeeProfile
(EmpId, EmpName, EmpPhoto)
Select 1001, 'Vadivel', BulkColumn
from Openrowset( Bulk 'C:\Image1.jpg', Single_Blob) as EmployeePicture
This Sql Query Working Fine.
Yes!
Here you have another example:
UPDATE prices
SET final_price= CASE
WHEN currency=1 THEN 0.81*final_price
ELSE final_price
END
This works because MySQL doesn't update the row, if there is no change, as mentioned in docs:
If you set a column to the value it currently has, MySQL notices this and does not update it.
>>> 2 == 2.0
True
>>> 2 is 2.0
False
Use ==
While I would have gone with Piotr's answer (because it's all in one line), I was surprised that your sample is closer to your solution than you think. From what you have, you simply assign the model value before you use the Html helper method.
@{Model.RequiredProperty = "default";}
@Html.HiddenFor(model => model.RequiredProperty)
Dont use a foreach then. Use a 'for loop'. Your code is a bit messed up but you could do something like...
for (Int32 i = 0; i < dt_pattern.Rows.Count; i++)
{
double yATmax = ToDouble(dt_pattern.Rows[i+1]["Ampl"].ToString()) + AT;
}
Note you would have to take into account during the last row there will be no 'i+1' so you will have to use an if statement to catch that.
This just in:
n = 8
s = '123'
print s[:n-3] + (s[n-3:], '...')[len(s) > n]
s = '12345678'
print s[:n-3] + (s[n-3:], '...')[len(s) > n]
s = '123456789'
print s[:n-3] + (s[n-3:], '...')[len(s) > n]
s = '123456789012345'
print s[:n-3] + (s[n-3:], '...')[len(s) > n]
123
12345678
12345...
12345...
public class FileUploadExample extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "/uploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(uploadedFile.getAbsolutePath());
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
What's wrong:
The definition of "nonrecursivecountcells" has no parameter named grid. You need to pass the type AND variable name to the function. You only passed the type.
Note if you use the name grid for the parameter, that name has nothing to do with your main() declaration of grid. You could have used any other name as well.
***
Also you can't pass arrays as values.
How to fix:
The easy way to fix this is to pass a pointer to an array to the function "nonrecursivecountcells".
int nonrecursivecountcells(color[ROW_SIZE][COL_SIZE], int, int);
better and type safe ->
int nonrecursivecountcells(color (&grid)[ROW_SIZE][COL_SIZE], int, int);
About scope:
A variable created on the stack comes out of scope when the block it is declared in is terminated. A block is anything within an opening and matching closing brace. For example an if() { }, function() { }, while() {}, ...
Note I said variable and not data. For example you can allocate memory on the heap and that data will still remain valid even outside of the scope. But the variable that originally pointed to it would still come out of scope.
Yes... by the time the regex compiler sees the pattern you've given it, it sees only a single backslash (since Java's lexer has turned the double backwhack into a single one). You need to replace "\\\\"
with "\\\\"
, believe it or not! Java really needs a good raw string syntax.
Please check the query without using a function:
declare @T table(Insurance varchar(max))
insert into @T values ('wezembeek-oppem')
insert into @T values ('roeselare')
insert into @T values ('BRUGGE')
insert into @T values ('louvain-la-neuve')
select (
select upper(T.N.value('.', 'char(1)'))+
lower(stuff(T.N.value('.', 'varchar(max)'), 1, 1, ''))+(CASE WHEN RIGHT(T.N.value('.', 'varchar(max)'), 1)='-' THEN '' ELSE ' ' END)
from X.InsXML.nodes('/N') as T(N)
for xml path(''), type
).value('.', 'varchar(max)') as Insurance
from
(
select cast('<N>'+replace(
replace(
Insurance,
' ', '</N><N>'),
'-', '-</N><N>')+'</N>' as xml) as InsXML
from @T
) as X
My solution for Swift 3. So, I created the function, that hide/unhide view in the right order(when hiding - set alpha to 0 and then isHidden to true; unhiding - first reveal the view and then set it's alpha to 1):
func hide(_ hide: Bool) {
let animations = hide ? { self.alpha = 0 } :
{ self.isHidden = false }
let completion: (Bool) -> Void = hide ? { _ in self.isHidden = true } :
{ _ in UIView.animate(withDuration: duration, animations: { self.alpha = 1 }) }
UIView.animate(withDuration: duration, animations: animations, completion: completion)
}
Maybe you forgot the await before returning your collection
is there a better way?
Well, if you are really looking for a better way, you can probably add another layer of abstraction on top of Rate. Well here is something I just came up with using Nullable Design Pattern.
using System; using System.Collections.Generic; namespace NullObjectPatternTest { public class Program { public static void Main(string[] args) { var items = new List { new Item(RateFactory.Create(20)), new Item(RateFactory.Create(null)) }; PrintPricesForItems(items); } private static void PrintPricesForItems(IEnumerable items) { foreach (var item in items) Console.WriteLine("Item Price: {0:C}", item.GetPrice()); } } public abstract class ItemBase { public abstract Rate Rate { get; } public int GetPrice() { // There is NO need to check if Rate == 0 or Rate == null return 1 * Rate.Value; } } public class Item : ItemBase { private readonly Rate _Rate; public override Rate Rate { get { return _Rate; } } public Item(Rate rate) { _Rate = rate; } } public sealed class RateFactory { public static Rate Create(int? rateValue) { if (!rateValue || rateValue == 0) return new NullRate(); return new Rate(rateValue); } } public class Rate { public int Value { get; set; } public virtual bool HasValue { get { return (Value > 0); } } public Rate(int value) { Value = value; } } public class NullRate : Rate { public override bool HasValue { get { return false; } } public NullRate() : base(0) { } } }
You can do this:
conf.CreateMap<SourceType, DestinationType>()
.ForSourceMember(x => x.SourceProperty, y => y.Ignore());
Or, in latest version of Automapper, you simply want to tell Automapper to not validate the field
conf.CreateMap<SourceType, DestinationType>()
.ForSourceMember(x => x.SourceProperty, y => y.DoNotValidate());
Here is your code. I'm assuming you're using python 3 based on the your use of print()
and input()
:
import random
def main():
#random.seed() --> don't need random.seed()
#Prompts the user to enter the number of tickets they wish to play.
#python 3 version:
tickets = int(input("How many lottery tickets do you want?\n"))
#Creates the dictionaries "winning_numbers" and "guess." Also creates the variable "winnings" for total amount of money won.
winning_numbers = []
winnings = 0
#Generates the winning lotto numbers.
for i in range(tickets * 5):
#del winning_numbers[:] what is this line for?
randNum = random.randint(1,30)
while randNum in winning_numbers:
randNum = random.randint(1,30)
winning_numbers.append(randNum)
print(winning_numbers)
guess = getguess(tickets)
nummatches = checkmatch(winning_numbers, guess)
print("Ticket #"+str(i+1)+": The winning combination was",winning_numbers,".You matched",nummatches,"number(s).\n")
winningRanks = [0, 0, 10, 500, 20000, 1000000]
winnings = sum(winningRanks[:nummatches + 1])
print("You won a total of",winnings,"with",tickets,"tickets.\n")
#Gets the guess from the user.
def getguess(tickets):
guess = []
for i in range(tickets):
bubble = [int(i) for i in input("What numbers do you want to choose for ticket #"+str(i+1)+"?\n").split()]
guess.extend(bubble)
print(bubble)
return guess
#Checks the user's guesses with the winning numbers.
def checkmatch(winning_numbers, guess):
match = 0
for i in range(5):
if guess[i] == winning_numbers[i]:
match += 1
return match
main()
Although the answers are 100% correct, a small suggestion to improve null
case handling of the list itself with Optional:
List<String> listOfStuffFiltered = Optional.ofNullable(listOfStuff)
.orElseGet(Collections::emptyList)
.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
The part Optional.ofNullable(listOfStuff).orElseGet(Collections::emptyList)
will allow you to handle nicely the case when listOfStuff
is null and return an emptyList instead of failing with NullPointerException.
If your argument is positional (ie it doesn't have a "-" or a "--" prefix, just the argument, typically a file name) then you can use the nargs parameter to do this:
parser = argparse.ArgumentParser(description='Foo is a program that does things')
parser.add_argument('filename', nargs='?')
args = parser.parse_args()
if args.filename is not None:
print('The file name is {}'.format(args.filename))
else:
print('Oh well ; No args, no problems')
You have to call close()
on the GZIPOutputStream
before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush()
probably won't help ... though calling finish()
instead of close()
should work. Look at the javadocs.)
Here's the correct code (in Java);
package test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GZipTest {
public static void main(String[] args) throws
FileNotFoundException, IOException {
String name = "/tmp/test";
GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
gz.write(10);
gz.close(); // Remove this to reproduce the reported bug
System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
}
}
(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)
1 - Treat functions as objects.
2 - The apply method is similar to __call __ in Python, which allows you to use an instance of a given class as a function.
Nothing, they are synonymous (Response.Write
is simply a shorter way to express the act of writing to the response output).
If you are curious, the implementation of HttpResponse.Write
looks like this:
public void Write(string s)
{
this._writer.Write(s);
}
And the implementation of HttpResponse.Output
is this:
public TextWriter Output
{
get
{
return this._writer;
}
}
So as you can see, Response.Write
and Response.Output.Write
are truly synonymous expressions.
If anyone is having this exception and is building the query using Scala multi-line strings:
Looks like there is a problem with some JPA drivers in this situation. I'm not sure what is the character Scala uses for LINE END, but when you have a parameter right at the end of the line, the LINE END character seems to be attached to the parameter and so when the driver parses the query, this error comes up. A simple work around is to leave an empty space right after the param at the end:
SELECT * FROM some_table a
WHERE a.col = ?param
AND a.col2 = ?param2
So, just make sure to leave an empty space after param (and param2, if you have a line break there).
Looks like you use %p: Print Pointers
I use this method as a wrapper so that I can send parameters. Also using the variables in the top of the method allows it to be minimized at a higher ratio and allows for some code reuse if making multiple similar calls.
function InfoByDate(sDate, eDate){
var divToBeWorkedOn = "#AjaxPlaceHolder";
var webMethod = "http://MyWebService/Web.asmx/GetInfoByDates";
var parameters = "{'sDate':'" + sDate + "','eDate':'" + eDate + "'}";
$.ajax({
type: "POST",
url: webMethod,
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$(divToBeWorkedOn).html(msg.d);
},
error: function(e){
$(divToBeWorkedOn).html("Unavailable");
}
});
}
I hope that helps.
Please note that this requires the 3.5 framework to expose JSON webmethods that can be consumed in this manner.
Just adding another solution that works for me.. You can simply append it in the marker options:
var marker = new google.maps.Marker({
map: map,
position: position,
// Custom Attributes / Data / Key-Values
store_id: id,
store_address: address,
store_type: type
});
And then retrieve them with:
marker.get('store_id');
marker.get('store_address');
marker.get('store_type');
Use IFERROR(value, value_if_error)
The best way to do this now (2019) is with a flexbox.
Run the snippet below to see what you get.
form {_x000D_
/* This bit sets up the horizontal layout */_x000D_
display:flex;_x000D_
flex-direction:row;_x000D_
_x000D_
/* This bit draws the box around it */_x000D_
border:1px solid grey;_x000D_
_x000D_
/* I've used padding so you can see the edges of the elements. */_x000D_
padding:2px;_x000D_
}_x000D_
_x000D_
input {_x000D_
/* Tell the input to use all the available space */_x000D_
flex-grow:2;_x000D_
/* And hide the input's outline, so the form looks like the outline */_x000D_
border:none;_x000D_
}_x000D_
_x000D_
input:focus {_x000D_
/* removing the input focus blue box. Put this on the form if you like. */_x000D_
outline: none;_x000D_
}_x000D_
_x000D_
button {_x000D_
/* Just a little styling to make it pretty */_x000D_
border:1px solid blue;_x000D_
background:blue;_x000D_
color:white;_x000D_
}
_x000D_
<form>_x000D_
<input />_x000D_
<button>Go</button>_x000D_
</form>
_x000D_
There's limited Flexbox support in IE9, so the button will not be on the right of the form. IE9 has not been supported by Microsoft for some years now, so I'm personally quite comfortable with this.
I've used minimal styling here. I've left in the padding to show the edges of things. You can obviously make this look however you want it to look with rounded corners, drop shadows, etc..
Including the fb:app_id
tag in your HTML HEAD will allow the Facebook scraper to associate the Open Graph entity for that URL with an application. This will allow any admins of that app to view Insights about that URL and any social plugins connected with it.
The fb:admins
tag is similar, but allows you to just specify each user ID that you would like to give the permission to do the above.
You can include either of these tags or both, depending on how many people you want to admin the Insights, etc. A single as fb:admins
is pretty much a minimum requirement. The rest of the Open Graph tags will still be picked up when people share and like your URL, however it may cause problems in the future, so please include one of the above.
fb:admins is specified like this:
<meta property="fb:admins" content="USER_ID"/>
OR
<meta property="fb:admins" content="USER_ID,USER_ID2,USER_ID3"/>
and fb:app_id like this:
<meta property="fb:app_id" content="APPID"/>
//create TreeMap instance
TreeMap treeMap = new TreeMap();
//add key value pairs to TreeMap
treeMap.put("1","One");
treeMap.put("2","Two");
treeMap.put("3","Three");
/*
get Collection of values contained in TreeMap using
Collection values()
*/
Collection c = treeMap.values();
//obtain an Iterator for Collection
Iterator itr = c.iterator();
//iterate through TreeMap values iterator
while(itr.hasNext())
System.out.println(itr.next());
or:
for (Map.Entry<K,V> entry : treeMap.entrySet()) {
V value = entry.getValue();
K key = entry.getKey();
}
or:
// Use iterator to display the keys and associated values
System.out.println("Map Values Before: ");
Set keys = map.keySet();
for (Iterator i = keys.iterator(); i.hasNext();) {
Integer key = (Integer) i.next();
String value = (String) map.get(key);
System.out.println(key + " = " + value);
}
I hope this is what you are looking for.
class Try:
def do_somthing(self):
print 'Hello'
if __name__ == '__main__':
obj_list = []
for obj in range(10):
obj = Try()
obj_list.append(obj)
obj_list[0].do_somthing()
Output:
Hello
Probably best to change the className:
document.getElementById("button").className = 'button_color';
Then you add a buton style to the CSS where you can set the background color and anything else.
SELECT * FROM users WHERE created >= CURDATE();
But I think you mean created < today
to know your php version
php -v
for php 7.3.0
sudo apt-get install php7.3-zip
have you tried eager loading?
@attachments = Job.includes(:attachments).find(1).attachments
You can also do
Pushd "%~dp0"
Which also takes running from a unc path into consideration.
Staying MVVM, I think using either Behaviors from the Blend SDK (System.Windows.Interactivity) or a custom interaction request from Prism could work really well for this sort of situation.
If going the Behavior route, here's the general idea:
public class CloseWindowBehavior : Behavior<Window>
{
public bool CloseTrigger
{
get { return (bool)GetValue(CloseTriggerProperty); }
set { SetValue(CloseTriggerProperty, value); }
}
public static readonly DependencyProperty CloseTriggerProperty =
DependencyProperty.Register("CloseTrigger", typeof(bool), typeof(CloseWindowBehavior), new PropertyMetadata(false, OnCloseTriggerChanged));
private static void OnCloseTriggerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var behavior = d as CloseWindowBehavior;
if (behavior != null)
{
behavior.OnCloseTriggerChanged();
}
}
private void OnCloseTriggerChanged()
{
// when closetrigger is true, close the window
if (this.CloseTrigger)
{
this.AssociatedObject.Close();
}
}
}
Then in your window, you would just bind the CloseTrigger to a boolean value that would be set when you wanted the window to close.
<Window x:Class="TestApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:local="clr-namespace:TestApp"
Title="MainWindow" Height="350" Width="525">
<i:Interaction.Behaviors>
<local:CloseWindowBehavior CloseTrigger="{Binding CloseTrigger}" />
</i:Interaction.Behaviors>
<Grid>
</Grid>
</Window>
Finally, your DataContext/ViewModel would have a property that you'd set when you wanted the window to close like this:
public class MainWindowViewModel : INotifyPropertyChanged
{
private bool closeTrigger;
/// <summary>
/// Gets or Sets if the main window should be closed
/// </summary>
public bool CloseTrigger
{
get { return this.closeTrigger; }
set
{
this.closeTrigger = value;
RaisePropertyChanged(nameof(CloseTrigger));
}
}
public MainWindowViewModel()
{
// just setting for example, close the window
CloseTrigger = true;
}
protected void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
(set your Window.DataContext = new MainWindowViewModel())
Note that you can also determine in pure js in what browser you script is beeing executed through : window.navigator.userAgent
However, that's not a recommended way as it's configurable in the browser settings. More info available there: https://developer.mozilla.org/fr/docs/DOM/window.navigator.userAgent
Alternate solution to doing shallow clone (git clone --depth=1 <URL>
) would be, if remote side supports it, to use --remote
option of git archive:
$ git archive --format=tar --remote=<repository URL> HEAD | tar xf -
Or, if remote repository in question is browse-able using some web interface like gitweb or GitHub, then there is a chance that it has 'snapshot' feature, and you can download latest version (without versioning information) from web interface.
Starting with Visual Studio 2010, crystal reports is no longer installed with Visual Studio. It can be installed separately by downloading the install from SAP crystal reports website. SAP crystal reports provides two installations. The first is SAP Crystal Reports version for visual studio that is installed for working with crystal reports in visual studio. The other is SAP Crystal Reports runtime engine for .NET Framework that is installed when the application is deployed on server machine.
SAP Crystal Reports in Visual Studio 2017 is now planned for Service Pack/Support Pack 21 (as of Apr 04'2017). The current available service/support pack is 19. Service/Support Pack 21 is expected to be released in September 2017.
You can use the MSI to install on the VS PC, it won't integrate into VS so you won't be able to design reports within the VS IDE but your app will compile. There will not be any Templates either so just add the CR Viewer to the Tool bar. Upgrading an exist VS app will simply work.
So in the meantime to edit rpt files you'll need the stand-alone Crystal Reports Designer until Support Pack 21 comes along.
Sources:
https://forums.asp.net/t/2110984.aspx?VS+2017+and+Crystal+Reports https://answers.sap.com/questions/168439/crystal-report-for-vs-2017.html
In case anyone wants the answer of Dirk Vollmar in a C# switch statement:
case "doc": return "application/msword";
case "dot": return "application/msword";
case "docx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
case "dotx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.template";
case "docm": return "application/vnd.ms-word.document.macroEnabled.12";
case "dotm": return "application/vnd.ms-word.template.macroEnabled.12";
case "xls": return "application/vnd.ms-excel";
case "xlt": return "application/vnd.ms-excel";
case "xla": return "application/vnd.ms-excel";
case "xlsx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
case "xltx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.template";
case "xlsm": return "application/vnd.ms-excel.sheet.macroEnabled.12";
case "xltm": return "application/vnd.ms-excel.template.macroEnabled.12";
case "xlam": return "application/vnd.ms-excel.addin.macroEnabled.12";
case "xlsb": return "application/vnd.ms-excel.sheet.binary.macroEnabled.12";
case "ppt": return "application/vnd.ms-powerpoint";
case "pot": return "application/vnd.ms-powerpoint";
case "pps": return "application/vnd.ms-powerpoint";
case "ppa": return "application/vnd.ms-powerpoint";
case "pptx": return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
case "potx": return "application/vnd.openxmlformats-officedocument.presentationml.template";
case "ppsx": return "application/vnd.openxmlformats-officedocument.presentationml.slideshow";
case "ppam": return "application/vnd.ms-powerpoint.addin.macroEnabled.12";
case "pptm": return "application/vnd.ms-powerpoint.presentation.macroEnabled.12";
case "potm": return "application/vnd.ms-powerpoint.template.macroEnabled.12";
case "ppsm": return "application/vnd.ms-powerpoint.slideshow.macroEnabled.12";
case "mdb": return "application/vnd.ms-access";
There seems to be some debate whether using StringBuilder is still needed with current compilers. So I thought I'll give my 2 cents of experience.
I have a JDBC
result set of 10k records (yes, I need all of them in one batch.) Using the + operator takes about 5 minutes on my machine with Java 1.8
. Using stringBuilder.append("")
takes less than a second for the same query.
So the difference is huge. Inside a loop StringBuilder
is much faster.
This is because, in C#, single quotes (''
) denote (or encapsulate) a single character, whereas double quotes (""
) are used for a string of characters. For example:
var myChar = '=';
var myString = "==";
I think you need this ..
Dim n as Integer
For n = 5 to 17
msgbox cells(n,3) '--> sched waste
msgbox cells(n,4) '--> type of treatm
msgbox format(cells(n,5),"dd/MM/yyyy") '--> Lic exp
msgbox cells(n,6) '--> email col
Next
Android comes with a built-in YesNoPreference class that does exactly what you want (a confirm dialog with yes and no options). See the official source code here.
Unfortunately, it is in the com.android.internal.preference
package, which means it is a part of Android's private APIs and you cannot access it from your application (private API classes are subject to change without notice, hence the reason why Google does not let you access them).
Solution: just re-create the class in your application's package by copy/pasting the official source code from the link I provided. I've tried this, and it works fine (there's no reason why it shouldn't).
You can then add it to your preferences.xml
like any other Preference. Example:
<com.example.myapp.YesNoPreference
android:dialogMessage="Are you sure you want to revert all settings to their default values?"
android:key="com.example.myapp.pref_reset_settings_key"
android:summary="Revert all settings to their default values."
android:title="Reset Settings" />
Which looks like this:
scale(..)
works a bit differently. You can use bufferedImage.getScaledInstance(..)
One need to set NavigateItem
checked true whenever item in NavigateView
is clicked
//listen for navigation events
NavigationView navigationView = (NavigationView)findViewById(R.id.navigation);
navigationView.setNavigationItemSelectedListener(this);
// select the correct nav menu item
navigationView.getMenu().findItem(mNavItemId).setChecked(true);
Add NavigationItemSelectedListener
on NavigationView
@Override
public boolean onNavigationItemSelected(final MenuItem menuItem) {
// update highlighted item in the navigation menu
menuItem.setChecked(true);
mNavItemId = menuItem.getItemId();
// allow some time after closing the drawer before performing real navigation
// so the user can see what is happening
mDrawerLayout.closeDrawer(GravityCompat.START);
mDrawerActionHandler.postDelayed(new Runnable() {
@Override
public void run() {
navigate(menuItem.getItemId());
}
}, DRAWER_CLOSE_DELAY_MS);
return true;
}
Use following command to untrack files
git rm --cached <file path>
For those who are still looking for an answer. Here is a recursive approach to get the paths in a dictionary.
import os
def list_files(startpath):
for root, dirs, files in os.walk(startpath):
dir_content = []
for dir in dirs:
go_inside = os.path.join(startpath, dir)
dir_content.append(list_files(go_inside))
files_lst = []
for f in files:
files_lst.append(f)
return {'name': root, 'files': files_lst, 'dirs': dir_content}
The mysql_real_escape_string()
helps you escape special characters such as single quote etc that users may submit to your script. You need to escape such characters because that comes in handy when you want to avoid SQL Injection.
I would sugggest you to check out:
mysql_real_escape_string() versus Prepared Statements
To be on much safer side, you need to go for Prepared Statements instead as demonstrated through above article.
You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.
<resource-ref>
introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.
So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB
name. The container finds that web.xml has a <resource-ref>
element for jdbc/primaryDB
, so it will look into the container-specific configuration, that contains something similar to the following:
<resource-ref>
<res-ref-name>jdbc/primaryDB</res-ref-name>
<jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>
Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer
.
The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.
It worked for me. Go to Tools-> Options -> Debugger -> Native and check the Load DLL exports. Hope this helps
If you want to follow an application that still has to be started then it's certainly possible:
docker run -t -i ubuntu /bin/bash
(change "ubuntu" to your favorite distro, this doesn't have to be the same as in your real system)any
, wlan0
, eth0
, ... choose the new virtual interface docker0
instead.You might have some doubts about running your software in a container, so here are the answers to the questions you probably want to ask:
If you are simply looking for producing a binary executable from a PHP script, then please avoid trying to make your question extremely precise because it will make it appear that you know exactly what you need. Besides, most PHP developer have absolutely zero clue about what a bytecode is.
With that said, the answers is YES. I have just finished compiling a PHP script into a binary. And not just any binary. I have used the CDE application (link to Wayback Machine, the original link is now broken) to turn it into an portable binary that can be distributed with all the dependencies and executed without any issue… and it works beautifully.
All you need is to use phc.
puts false or true
--> prints: false
puts false || true
--> prints: true
this function will join 2 tables with a known join field, but this cannot allow 2 fields with the same name on both tables except the join field, a simple modification would be to save a dictionary with a counter and just add number to the same name filds.
public static DataTable JoinDataTable(DataTable dataTable1, DataTable dataTable2, string joinField)
{
var dt = new DataTable();
var joinTable = from t1 in dataTable1.AsEnumerable()
join t2 in dataTable2.AsEnumerable()
on t1[joinField] equals t2[joinField]
select new { t1, t2 };
foreach (DataColumn col in dataTable1.Columns)
dt.Columns.Add(col.ColumnName, typeof(string));
dt.Columns.Remove(joinField);
foreach (DataColumn col in dataTable2.Columns)
dt.Columns.Add(col.ColumnName, typeof(string));
foreach (var row in joinTable)
{
var newRow = dt.NewRow();
newRow.ItemArray = row.t1.ItemArray.Union(row.t2.ItemArray).ToArray();
dt.Rows.Add(newRow);
}
return dt;
}
update: in the comments, Goerge says " This works on Chrome, Firefox and Edge, but not Safari."
This is the W3C solution. You can use it in 3012!
ul { list-style-type: "*"; } /* Sets the marker to a "star" character */
if ((Control.ModifierKeys & Keys.Shift) != 0)
This will also be true if Ctrl+Shift is down. If you want to check whether Shift alone is pressed,
if (Control.ModifierKeys == Keys.Shift)
If you're in a class that inherits Control
(such as a form), you can remove the Control.
In Java 8 atomic classes have been extended with two interesting functions:
Both are using the updateFunction to perform update of the atomic value. The difference is that the first one returns old value and the second one return the new value. The updateFunction may be implemented to do more complex "compare and set" operations than the standard one. For example it can check that atomic counter doesn't go below zero, normally it would require synchronization, and here the code is lock-free:
public class Counter {
private final AtomicInteger number;
public Counter(int number) {
this.number = new AtomicInteger(number);
}
/** @return true if still can decrease */
public boolean dec() {
// updateAndGet(fn) executed atomically:
return number.updateAndGet(n -> (n > 0) ? n - 1 : n) > 0;
}
}
The code is taken from Java Atomic Example.
testSpace.Style.Add("display", "none");
It is a common misconception that time (a measurable 4th dimension) is different over the world. Timestamp as a moment in time is unique. Date however is influenced how we "see" time but actually it is "time of day".
An example: two people look at the clock at the same moment. The timestamp is the same, right? But one of them is in London and sees 12:00 noon (GMT, timezone offset is 0), and the other is in Belgrade and sees 14:00 (CET, Central Europe, daylight saving now, offset is +2).
Their perception is different but the moment is the same.
You can find more details in this answer.
OK, it's not a duplicate of this question but it is pointless since you are confusing the terms "Timestamp = moment in time (objective)" and "Date[Time] = time of day (subjective)".
Let's look at your original question code broken down like this:
// Get the "original" value from database.
Timestamp momentFromDB = rs.getTimestamp("anytimestampcolumn");
// Turn it into a Joda DateTime with time zone.
DateTime dt = new DateTime(momentFromDB, DateTimeZone.forID("anytimezone"));
// And then turn it back into a timestamp but "with time zone".
Timestamp ts = new Timestamp(dt.getMillis());
I haven't run this code but I am certain it will print true
and the same number of milliseconds each time:
System.out.println("momentFromDB == dt : " + (momentFromDB.getTime() == dt.getTimeInMillis());
System.out.println("momentFromDB == ts : " + (momentFromDB.getTime() == ts.getTime()));
System.out.println("dt == ts : " + (dt.getTimeInMillis() == ts.getTime()));
System.out.println("momentFromDB [ms] : " + momentFromDB.getTime());
System.out.println("ts [ms] : " + ts.getTime());
System.out.println("dt [ms] : " + dt.getTimeInMillis());
But as you said yourself printing them out as strings will result in "different" time because DateTime
applies the time zone. That's why "time" is stored and transferred as Timestamp
objects (which basically wraps a long
) and displayed or entered as Date[Time]
.
In your own answer you are artificially adding an offset and creating a "wrong" time.
If you use that timestamp to create another DateTime
and print it out it will be offset twice.
// Turn it back into a Joda DateTime with time zone.
DateTime dt = new DateTime(ts, DateTimeZone.forID("anytimezone"));
P.S. If you have the time go through the very complex Joda Time source code to see how it holds the time (millis) and how it prints it.
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import org.junit.Before;
import org.junit.Test;
public class WorldTimeTest {
private static final int MILLIS_IN_HOUR = 1000 * 60 * 60;
private static final String ISO_FORMAT_NO_TZ = "yyyy-MM-dd'T'HH:mm:ss.SSS";
private static final String ISO_FORMAT_WITH_TZ = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
private TimeZone londonTimeZone;
private TimeZone newYorkTimeZone;
private TimeZone sydneyTimeZone;
private long nowInMillis;
private Date now;
public static SimpleDateFormat createDateFormat(String pattern, TimeZone timeZone) throws Exception {
SimpleDateFormat result = new SimpleDateFormat(pattern);
// Must explicitly set the time zone with "setCalendar()".
result.setCalendar(Calendar.getInstance(timeZone));
return result;
}
public static SimpleDateFormat createDateFormat(String pattern) throws Exception {
return createDateFormat(pattern, TimeZone.getDefault());
}
public static SimpleDateFormat createDateFormat() throws Exception {
return createDateFormat(ISO_FORMAT_WITH_TZ, TimeZone.getDefault());
}
public void printSystemInfo() throws Exception {
final String[] propertyNames = {
"java.runtime.name", "java.runtime.version", "java.vm.name", "java.vm.version",
"os.name", "os.version", "os.arch",
"user.language", "user.country", "user.script", "user.variant",
"user.language.format", "user.country.format", "user.script.format",
"user.timezone" };
System.out.println();
System.out.println("System Information:");
for (String name : propertyNames) {
if (name == null || name.length() == 0) {
continue;
}
String value = System.getProperty(name);
if (value != null && value.length() > 0) {
System.out.println(" " + name + " = " + value);
}
}
final TimeZone defaultTZ = TimeZone.getDefault();
final int defaultOffset = defaultTZ.getOffset(nowInMillis) / MILLIS_IN_HOUR;
final int userOffset = TimeZone.getTimeZone(System
.getProperty("user.timezone")).getOffset(nowInMillis) / MILLIS_IN_HOUR;
final Locale defaultLocale = Locale.getDefault();
System.out.println(" default.timezone-offset (hours) = " + userOffset);
System.out.println(" default.timezone = " + defaultTZ.getDisplayName());
System.out.println(" default.timezone.id = " + defaultTZ.getID());
System.out.println(" default.timezone-offset (hours) = " + defaultOffset);
System.out.println(" default.locale = "
+ defaultLocale.getLanguage() + "_" + defaultLocale.getCountry()
+ " (" + defaultLocale.getDisplayLanguage()
+ "," + defaultLocale.getDisplayCountry() + ")");
System.out.println(" now = " + nowInMillis + " [ms] or "
+ createDateFormat().format(now));
System.out.println();
}
@Before
public void setUp() throws Exception {
// Remember this moment.
now = new Date();
nowInMillis = now.getTime(); // == System.currentTimeMillis();
// Print out some system information.
printSystemInfo();
// "Europe/London" time zone is DST aware, we'll use fixed offset.
londonTimeZone = TimeZone.getTimeZone("GMT");
// The same applies to "America/New York" time zone ...
newYorkTimeZone = TimeZone.getTimeZone("GMT-5");
// ... and for the "Australia/Sydney" time zone.
sydneyTimeZone = TimeZone.getTimeZone("GMT+10");
}
@Test
public void testDateFormatting() throws Exception {
int londonOffset = londonTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR; // in hours
Calendar londonCalendar = Calendar.getInstance(londonTimeZone);
londonCalendar.setTime(now);
int newYorkOffset = newYorkTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR;
Calendar newYorkCalendar = Calendar.getInstance(newYorkTimeZone);
newYorkCalendar.setTime(now);
int sydneyOffset = sydneyTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR;
Calendar sydneyCalendar = Calendar.getInstance(sydneyTimeZone);
sydneyCalendar.setTime(now);
// Check each time zone offset.
assertThat(londonOffset, equalTo(0));
assertThat(newYorkOffset, equalTo(-5));
assertThat(sydneyOffset, equalTo(10));
// Check that calendars are not equals (due to time zone difference).
assertThat(londonCalendar, not(equalTo(newYorkCalendar)));
assertThat(londonCalendar, not(equalTo(sydneyCalendar)));
// Check if they all point to the same moment in time, in milliseconds.
assertThat(londonCalendar.getTimeInMillis(), equalTo(nowInMillis));
assertThat(newYorkCalendar.getTimeInMillis(), equalTo(nowInMillis));
assertThat(sydneyCalendar.getTimeInMillis(), equalTo(nowInMillis));
// Check if they all point to the same moment in time, as Date.
assertThat(londonCalendar.getTime(), equalTo(now));
assertThat(newYorkCalendar.getTime(), equalTo(now));
assertThat(sydneyCalendar.getTime(), equalTo(now));
// Check if hours are all different (skip local time because
// this test could be executed in those exact time zones).
assertThat(newYorkCalendar.get(Calendar.HOUR_OF_DAY),
not(equalTo(londonCalendar.get(Calendar.HOUR_OF_DAY))));
assertThat(sydneyCalendar.get(Calendar.HOUR_OF_DAY),
not(equalTo(londonCalendar.get(Calendar.HOUR_OF_DAY))));
// Display London time in multiple forms.
SimpleDateFormat dfLondonNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, londonTimeZone);
SimpleDateFormat dfLondonWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, londonTimeZone);
System.out.println("London (" + londonTimeZone.getDisplayName(false, TimeZone.SHORT)
+ ", " + londonOffset + "):");
System.out.println(" time (ISO format w/o TZ) = "
+ dfLondonNoTZ.format(londonCalendar.getTime()));
System.out.println(" time (ISO format w/ TZ) = "
+ dfLondonWithTZ.format(londonCalendar.getTime()));
System.out.println(" time (default format) = "
+ londonCalendar.getTime() + " / " + londonCalendar.toString());
// Using system default time zone.
System.out.println(" time (default TZ) = "
+ createDateFormat(ISO_FORMAT_NO_TZ).format(londonCalendar.getTime())
+ " / " + createDateFormat().format(londonCalendar.getTime()));
// Display New York time in multiple forms.
SimpleDateFormat dfNewYorkNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, newYorkTimeZone);
SimpleDateFormat dfNewYorkWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, newYorkTimeZone);
System.out.println("New York (" + newYorkTimeZone.getDisplayName(false, TimeZone.SHORT)
+ ", " + newYorkOffset + "):");
System.out.println(" time (ISO format w/o TZ) = "
+ dfNewYorkNoTZ.format(newYorkCalendar.getTime()));
System.out.println(" time (ISO format w/ TZ) = "
+ dfNewYorkWithTZ.format(newYorkCalendar.getTime()));
System.out.println(" time (default format) = "
+ newYorkCalendar.getTime() + " / " + newYorkCalendar.toString());
// Using system default time zone.
System.out.println(" time (default TZ) = "
+ createDateFormat(ISO_FORMAT_NO_TZ).format(newYorkCalendar.getTime())
+ " / " + createDateFormat().format(newYorkCalendar.getTime()));
// Display Sydney time in multiple forms.
SimpleDateFormat dfSydneyNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, sydneyTimeZone);
SimpleDateFormat dfSydneyWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, sydneyTimeZone);
System.out.println("Sydney (" + sydneyTimeZone.getDisplayName(false, TimeZone.SHORT)
+ ", " + sydneyOffset + "):");
System.out.println(" time (ISO format w/o TZ) = "
+ dfSydneyNoTZ.format(sydneyCalendar.getTime()));
System.out.println(" time (ISO format w/ TZ) = "
+ dfSydneyWithTZ.format(sydneyCalendar.getTime()));
System.out.println(" time (default format) = "
+ sydneyCalendar.getTime() + " / " + sydneyCalendar.toString());
// Using system default time zone.
System.out.println(" time (default TZ) = "
+ createDateFormat(ISO_FORMAT_NO_TZ).format(sydneyCalendar.getTime())
+ " / " + createDateFormat().format(sydneyCalendar.getTime()));
}
@Test
public void testDateParsing() throws Exception {
// Create date parsers that look for time zone information in a date-time string.
final SimpleDateFormat londonFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, londonTimeZone);
final SimpleDateFormat newYorkFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, newYorkTimeZone);
final SimpleDateFormat sydneyFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, sydneyTimeZone);
// Create date parsers that ignore time zone information in a date-time string.
final SimpleDateFormat londonFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, londonTimeZone);
final SimpleDateFormat newYorkFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, newYorkTimeZone);
final SimpleDateFormat sydneyFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, sydneyTimeZone);
// We are looking for the moment this millenium started, the famous Y2K,
// when at midnight everyone welcomed the New Year 2000, i.e. 2000-01-01 00:00:00.
// Which of these is the right one?
// a) "2000-01-01T00:00:00.000-00:00"
// b) "2000-01-01T00:00:00.000-05:00"
// c) "2000-01-01T00:00:00.000+10:00"
// None of them? All of them?
// For those who guessed it - yes, it is a trick question because we didn't specify
// the "where" part, or what kind of time (local/global) we are looking for.
// The first (a) is the local Y2K moment in London, which is at the same time global.
// The second (b) is the local Y2K moment in New York, but London is already celebrating for 5 hours.
// The third (c) is the local Y2K moment in Sydney, and they started celebrating 15 hours before New York did.
// The point here is that each answer is correct because everyone thinks of that moment in terms of "celebration at midnight".
// The key word here is "midnight"! That moment is actually a "time of day" moment illustrating our perception of time based on the movement of our Sun.
// These are global Y2K moments, i.e. the same moment all over the world, UTC/GMT midnight.
final String MIDNIGHT_GLOBAL = "2000-01-01T00:00:00.000-00:00";
final Date milleniumInLondon = londonFormatTZ.parse(MIDNIGHT_GLOBAL);
final Date milleniumInNewYork = newYorkFormatTZ.parse(MIDNIGHT_GLOBAL);
final Date milleniumInSydney = sydneyFormatTZ.parse(MIDNIGHT_GLOBAL);
// Check if they all point to the same moment in time.
// And that parser ignores its own configured time zone and uses the information from the date-time string.
assertThat(milleniumInNewYork, equalTo(milleniumInLondon));
assertThat(milleniumInSydney, equalTo(milleniumInLondon));
// These are all local Y2K moments, a.k.a. midnight at each location on Earth, with time zone information.
final String MIDNIGHT_LONDON = "2000-01-01T00:00:00.000-00:00";
final String MIDNIGHT_NEW_YORK = "2000-01-01T00:00:00.000-05:00";
final String MIDNIGHT_SYDNEY = "2000-01-01T00:00:00.000+10:00";
final Date midnightInLondonTZ = londonFormatLocal.parse(MIDNIGHT_LONDON);
final Date midnightInNewYorkTZ = newYorkFormatLocal.parse(MIDNIGHT_NEW_YORK);
final Date midnightInSydneyTZ = sydneyFormatLocal.parse(MIDNIGHT_SYDNEY);
// Check if they all point to the same moment in time.
assertThat(midnightInNewYorkTZ, not(equalTo(midnightInLondonTZ)));
assertThat(midnightInSydneyTZ, not(equalTo(midnightInLondonTZ)));
// Check if the time zone offset is correct.
assertThat(midnightInLondonTZ.getTime() - midnightInNewYorkTZ.getTime(),
equalTo((long) newYorkTimeZone.getOffset(milleniumInLondon.getTime())));
assertThat(midnightInLondonTZ.getTime() - midnightInSydneyTZ.getTime(),
equalTo((long) sydneyTimeZone.getOffset(milleniumInLondon.getTime())));
// These are also local Y2K moments, just withouth the time zone information.
final String MIDNIGHT_ANYWHERE = "2000-01-01T00:00:00.000";
final Date midnightInLondon = londonFormatLocal.parse(MIDNIGHT_ANYWHERE);
final Date midnightInNewYork = newYorkFormatLocal.parse(MIDNIGHT_ANYWHERE);
final Date midnightInSydney = sydneyFormatLocal.parse(MIDNIGHT_ANYWHERE);
// Check if these are the same as the local moments with time zone information.
assertThat(midnightInLondon, equalTo(midnightInLondonTZ));
assertThat(midnightInNewYork, equalTo(midnightInNewYorkTZ));
assertThat(midnightInSydney, equalTo(midnightInSydneyTZ));
// Check if they all point to the same moment in time.
assertThat(midnightInNewYork, not(equalTo(midnightInLondon)));
assertThat(midnightInSydney, not(equalTo(midnightInLondon)));
// Check if the time zone offset is correct.
assertThat(midnightInLondon.getTime() - midnightInNewYork.getTime(),
equalTo((long) newYorkTimeZone.getOffset(milleniumInLondon.getTime())));
assertThat(midnightInLondon.getTime() - midnightInSydney.getTime(),
equalTo((long) sydneyTimeZone.getOffset(milleniumInLondon.getTime())));
// Final check - if Y2K moment is in London ..
final String Y2K_LONDON = "2000-01-01T00:00:00.000Z";
// .. New York local time would be still 5 hours in 1999 ..
final String Y2K_NEW_YORK = "1999-12-31T19:00:00.000-05:00";
// .. and Sydney local time would be 10 hours in 2000.
final String Y2K_SYDNEY = "2000-01-01T10:00:00.000+10:00";
final String londonTime = londonFormatTZ.format(milleniumInLondon);
final String newYorkTime = newYorkFormatTZ.format(milleniumInLondon);
final String sydneyTime = sydneyFormatTZ.format(milleniumInLondon);
// WHat do you think, will the test pass?
assertThat(londonTime, equalTo(Y2K_LONDON));
assertThat(newYorkTime, equalTo(Y2K_NEW_YORK));
assertThat(sydneyTime, equalTo(Y2K_SYDNEY));
}
}
Toast duration can be hacked using a thread that runs the toast exclusively. This works (runs the toast for 10 secs, modify sleep and ctr to your liking):
final Toast toast = Toast.makeText(this, "Your Message", Toast.LENGTH_LONG);
Thread t = new Thread(){
public void run(){
int ctr = 0;
try{
while( ctr<10 ){
toast.show();
sleep(1000);
ctr++;
}
} catch (Exception e) {
Log.e("Error", "", e);
}
}
};
t.start();
It can be as simple as that:
const sumValues = obj => Object.values(obj).reduce((a, b) => a + b);
Quoting MDN:
The
Object.values()
method returns an array of a given object's own enumerable property values, in the same order as that provided by afor...in
loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
The
reduce()
method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.
from Array.prototype.reduce()
on MDN
You can use this function like that:
sumValues({a: 4, b: 6, c: -5, d: 0}); // gives 5
Note that this code uses some ECMAScript features which are not supported by some older browsers (like IE). You might need to use Babel to compile your code.
As AnaPana mentioned pathlib is more new and easier in python 3.4 and there is new with_suffix method that can handle this problem easily:
from pathlib import Path
new_filename = Path(mysequence.fasta).with_suffix('.aln')
See Bavarious's answer.
Use xattr
with the -c
flag to "clear" the attributes:
xattr -c yourfile.txt
To recursively remove extended attributes on all files in a directory, combine the -c
"clear" flag with the -r
recursive flag:
xattr -rc /path/to/directory
Have a long path with spaces or special characters?
Open Terminal.app
and start typing xattr -rc
, include a trailing space, and then then drag the file or folder to the Terminal.app
window and it will automatically add the full path with proper escaping.
Another possibility is
var res = /!id-[^!]*/.exec("!"+windowArray.join("!"));
return res && res[0].substr(1);
that IMO may make sense if you can have a special char delimiter (here i used "!"), the array is constant or mostly constant (so the join can be computed once or rarely) and the full string isn't much longer than the prefix searched for.
I tried all the options from above and they didn't work. Then I located the google font (Over the Rainbow) in my folder (new) and used IE conditional below and it worked perfect.
<!--[if IE]>
<style type="text/css">
@font-face {
font-family: "Over the Rainbow";
src: url("../new/over.ttf");
src: local("Over the Rainbow"), url("../new/over.ttf");
}
</style>
<![endif]-->
I hope it will help
Python 2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.pi
3.141592653589793
Check out the Python tutorial on modules and how to use them.
As for the second part of your question, Python comes with batteries included, of course:
>>> math.radians(90)
1.5707963267948966
>>> math.radians(180)
3.141592653589793
The Facebook "Graph API Rate Limiting" docs says that an error with code #4
is an app level rate limit, which is different than user level rate limits. Although it doesn't give any exact numbers, it describes their app level rate-limit as:
This rate limiting is applied globally at the app level. Ads api calls are excluded.
- Rate limiting happens real time on sliding window for past one hour.
- Stats is collected for number of calls and queries made, cpu time spent, memory used for each app.
- There is a limit for each resource multiplied by monthly active users of a given app.
- When the app uses more than its allowed resources the error is thrown.
- Error, Code: 4, Message: Application request limit reached
The docs also give recommendations for avoiding the rate limits. For app level limits, they are:
Recommendations:
- Verify the error code (4) to confirm the throttling type.
- Do not make burst of calls, spread out the calls throughout the day.
- Do smart fetching of data (important data, non duplicated data, etc).
- Real-time insights, make sure API calls are structured in a way that you can read insights for as many as Page posts as possible, with minimum number of requests.
- Don't fetch users feed twice (in the case that two App users have a specific friend in common)
- Don't fetch all user's friends feed in a row if the number of friends is more than 250. Separate the fetches over different days. As an option, fetch first the app user's news feed (me/home) in order to detect which friends are more important to the App user. Then, fetch those friends feeds first.
- Consider to limit/filter the requests by using the following parameters: "since", "until", "limit"
- For page related calls use realtime updates to subscribe to changes in data.
- Field expansion allows ton "join" multiple graph queries into a single call.
- Etags to check if the data querying has changed since the last check.
- For page management developers who does not have massive user base, have the admins of the page to accept the app to increase the number of users.
Finally, the docs give the following informational tips:
- Batching calls will not reduce the number of api calls.
- Making parallel calls will not reduce the number of api calls.
dataGridView1.DataSource = (from S in EE.Stagaire
join F in EE.Filiere on
S.IdFiliere equals F.IdFiliere
where S.Nom.StartsWith("A")
select new
{
ID=S.Id,
Name = S.Nom,
Prénon= S.Prenon,
Email=S.Email,
MoteDePass=S.MoteDePass,
Filiere = F.Filiere1
}).Take(1).ToList();
Swift 4.2
and It will work 100%
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.textField.delegate = self
}
// hide key board when the user touches outside keyboard
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
// user presses return key
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
If you are using tortoise git you can right-click on a file and git a diff by: Right-clicking on the first file and through the tortoisegit submenu select "Diff later" Then on the second file you can also right-click on this, go to the tortoisegit submenu and then select "Diff with yourfilenamehere.txt"
Reference Decoder of CRL,CRT,CSR,NEW CSR,PRIVATE KEY, PUBLIC KEY,RSA,RSA Public Key Parser
RSA Public Key
-----BEGIN RSA PUBLIC KEY-----
-----END RSA PUBLIC KEY-----
Encrypted Private Key
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
-----END RSA PRIVATE KEY-----
CRL
-----BEGIN X509 CRL-----
-----END X509 CRL-----
CRT
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
CSR
-----BEGIN CERTIFICATE REQUEST-----
-----END CERTIFICATE REQUEST-----
NEW CSR
-----BEGIN NEW CERTIFICATE REQUEST-----
-----END NEW CERTIFICATE REQUEST-----
PEM
-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----
PKCS7
-----BEGIN PKCS7-----
-----END PKCS7-----
PRIVATE KEY
-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----
DSA KEY
-----BEGIN DSA PRIVATE KEY-----
-----END DSA PRIVATE KEY-----
Elliptic Curve
-----BEGIN EC PRIVATE KEY-----
-----END EC PRIVATE KEY-----
PGP Private Key
-----BEGIN PGP PRIVATE KEY BLOCK-----
-----END PGP PRIVATE KEY BLOCK-----
PGP Public Key
-----BEGIN PGP PUBLIC KEY BLOCK-----
-----END PGP PUBLIC KEY BLOCK-----
I think this should point you towards the right direction:
import java.beans.*
for (PropertyDescriptor pd : Introspector.getBeanInfo(Foo.class).getPropertyDescriptors()) {
if (pd.getReadMethod() != null && !"class".equals(pd.getName()))
System.out.println(pd.getReadMethod().invoke(foo));
}
Note that you could create BeanInfo or PropertyDescriptor instances yourself, i.e. without using Introspector. However, Introspector does some caching internally which is normally a Good Thing (tm). If you're happy without a cache, you can even go for
// TODO check for non-existing readMethod
Object value = new PropertyDescriptor("name", Person.class).getReadMethod().invoke(person);
However, there are a lot of libraries that extend and simplify the java.beans API. Commons BeanUtils is a well known example. There, you'd simply do:
Object value = PropertyUtils.getProperty(person, "name");
BeanUtils comes with other handy stuff. i.e. on-the-fly value conversion (object to string, string to object) to simplify setting properties from user input.
Try this:
=FORMAT(Cdate(today), "dd-MM-yyyy")
or
=FORMAT(Cdate(today), "MM-dd-yyyy")
or
=FORMAT(Cdate(today), "yyyy-MM-dd")
or
=Report Generation Date: " & FORMAT(Cdate(today), "dd-MM-yyyy")
You should format the date in the same format your customer (internal or external) wants to see the date. For example In one of my servers it is running on American date format (MM-dd-yyyy) and on my reports I must ensure the dates displayed are European (yyyy-MM-dd).
in first.java
Intent i = new Intent(this, second.class);
i.putExtra("uri",uri);
startActivity(i);
in second.java
Bundle bd = getIntent().getExtras();
Uri uri = bd.getParcelable("uri");
Log.e("URI", uri.toString());
try {
Bitmap bitmap = Media.getBitmap(this.getContentResolver(), uri);
imageView.setImageBitmap(bitmap);
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
jQuery.validator.methods.matches = function( value, element, params ) {
var re = new RegExp(params);
// window.console.log(re);
// window.console.log(value);
// window.console.log(re.test( value ));
return this.optional( element ) || re.test( value );
}
rules: {
input_telf: {
required : true,
matches : "^(\\d|\\s)+$",
minlength : 10,
maxlength : 20
}
}
The simplest solution I could find was to delete the parent directory from the working copy (with rm -rf, not svn delete), and then run svn update in the grandparent. Eg, if you deleted a/b/c, rm -rf a/b, cd a, svn up. That brings everything back. Of course, this is only a good solution if you have no other uncommitted changes in the parent directory that you want to keep.
Hopefully this page will be at the top of the results next time I google this question. It would be even better if someone suggested a cleaner method, of course.
Just to add to the other answers, the documentation gives this explanation:
KEY
is normally a synonym forINDEX
. The key attributePRIMARY KEY
can also be specified as justKEY
when given in a column definition. This was implemented for compatibility with other database systems.A
UNIQUE
index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, aUNIQUE
index permits multipleNULL
values for columns that can containNULL
.A
PRIMARY KEY
is a unique index where all key columns must be defined asNOT NULL
. If they are not explicitly declared asNOT NULL
, MySQL declares them so implicitly (and silently). A table can have only onePRIMARY KEY
. The name of aPRIMARY KEY
is alwaysPRIMARY
, which thus cannot be used as the name for any other kind of index.
/src/com/example/MyClass.java
package com.example
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MyClass extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
ImageView iv = (ImageView) findViewById(R.id.imageview1);
iv.setVisibility(View.VISIBLE);
}
});
}
}
/res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:text="Button"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<ImageView
android:src="@drawable/image"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/imageview1"
android:visibility="invisible"
/>
</LinearLayout>
If you want to sort data either in Ascending or Descending order based on particular column, using sequlize js
, use the order
method of sequlize
as follows
// Will order the specified column by descending order
order: sequelize.literal('column_name order')
e.g. order: sequelize.literal('timestamp DESC')
Try the following code to find the optimal camera position
Use print to get the camera positions
def move_view(event):
ax.autoscale(enable=False, axis='both')
koef = 8
zkoef = (ax.get_zbound()[0] - ax.get_zbound()[1]) / koef
xkoef = (ax.get_xbound()[0] - ax.get_xbound()[1]) / koef
ykoef = (ax.get_ybound()[0] - ax.get_ybound()[1]) / koef
## Map an motion to keyboard shortcuts
if event.key == "ctrl+down":
ax.set_ybound(ax.get_ybound()[0] + xkoef, ax.get_ybound()[1] + xkoef)
if event.key == "ctrl+up":
ax.set_ybound(ax.get_ybound()[0] - xkoef, ax.get_ybound()[1] - xkoef)
if event.key == "ctrl+right":
ax.set_xbound(ax.get_xbound()[0] + ykoef, ax.get_xbound()[1] + ykoef)
if event.key == "ctrl+left":
ax.set_xbound(ax.get_xbound()[0] - ykoef, ax.get_xbound()[1] - ykoef)
if event.key == "down":
ax.set_zbound(ax.get_zbound()[0] - zkoef, ax.get_zbound()[1] - zkoef)
if event.key == "up":
ax.set_zbound(ax.get_zbound()[0] + zkoef, ax.get_zbound()[1] + zkoef)
# zoom option
if event.key == "alt+up":
ax.set_xbound(ax.get_xbound()[0]*0.90, ax.get_xbound()[1]*0.90)
ax.set_ybound(ax.get_ybound()[0]*0.90, ax.get_ybound()[1]*0.90)
ax.set_zbound(ax.get_zbound()[0]*0.90, ax.get_zbound()[1]*0.90)
if event.key == "alt+down":
ax.set_xbound(ax.get_xbound()[0]*1.10, ax.get_xbound()[1]*1.10)
ax.set_ybound(ax.get_ybound()[0]*1.10, ax.get_ybound()[1]*1.10)
ax.set_zbound(ax.get_zbound()[0]*1.10, ax.get_zbound()[1]*1.10)
# Rotational movement
elev=ax.elev
azim=ax.azim
if event.key == "shift+up":
elev+=10
if event.key == "shift+down":
elev-=10
if event.key == "shift+right":
azim+=10
if event.key == "shift+left":
azim-=10
ax.view_init(elev= elev, azim = azim)
# print which ever variable you want
ax.figure.canvas.draw()
fig.canvas.mpl_connect("key_press_event", move_view)
plt.show()
float
(and double
) represents binary fractions
decimal
represents decimal fractions
conda activate myEnv
conda list --explicit > myEnvBkp.txt
conda create --name myEnvRestored --file myEnvBkp.txt
I use this:
#define CHECK_BIT(var,pos) ( (((var) & (pos)) > 0 ) ? (1) : (0) )
where "pos" is defined as 2^n (i.g. 1,2,4,8,16,32 ...)
Returns: 1 if true 0 if false
Search your installation of PhpMyAdmin for a file called Documentation.txt. This describes how to create a file called config.inc.php and how you can configure the username and password.
document.getElementsByClassName('btn-pageMenu')
delivers a nodeList. You should use: document.getElementsByClassName('btn-pageMenu')[0].style.display
(if it's the first element from that list you want to change.
If you want to change style.display
for all nodes loop through the list:
var elems = document.getElementsByClassName('btn-pageMenu');
for (var i=0;i<elems.length;i+=1){
elems[i].style.display = 'block';
}
to be complete: if you use jquery it is as simple as:
?$('.btn-pageMenu').css('display'???????????????????????????,'block');??????
Here a solution for (I believe as seen by 'cp34' on the link below) Python 3.4.
Go to to http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv.
Download the appropriate .whl.
Go to the directory where the .whl is saved.
Use pip to install the .whl. e.g. pip install opencv_python-3.0.0-cp34-none-win_amd64.whl
Then just use import cv2
.
The accepted answer doesn't create a name-only attribute anymore (as of September 2017).
You should use JQuery prop() method to create name-only attributes.
$(body).prop('data-body', true)
Also, cursor.lastrowid
(a dbapi/PEP249 extension supported by MySQLdb):
>>> import MySQLdb
>>> connection = MySQLdb.connect(user='root')
>>> cursor = connection.cursor()
>>> cursor.execute('INSERT INTO sometable VALUES (...)')
1L
>>> connection.insert_id()
3L
>>> cursor.lastrowid
3L
>>> cursor.execute('SELECT last_insert_id()')
1L
>>> cursor.fetchone()
(3L,)
>>> cursor.execute('select @@identity')
1L
>>> cursor.fetchone()
(3L,)
cursor.lastrowid
is somewhat cheaper than connection.insert_id()
and much cheaper than another round trip to MySQL.
If you use gradle build, use this: BuildConfig.APPLICATION_ID
to get the package name of the application.
Settings for Sun/Oracle java version "1.6.0_31" and Eclipse 3.7 running on x86-64 Linux:
-nosplash
-vmargs
-Xincgc
-Xss500k
-Dosgi.requiredJavaVersion=1.6
-Xms64m
-Xmx200m
-XX:NewSize=8m
-XX:PermSize=80m
-XX:MaxPermSize=150m
-XX:MaxPermHeapExpansion=10m
-XX:+UseConcMarkSweepGC
-XX:CMSInitiatingOccupancyFraction=70
-XX:+UseCMSInitiatingOccupancyOnly
-XX:+UseParNewGC
-XX:+CMSConcurrentMTEnabled
-XX:ConcGCThreads=2
-XX:ParallelGCThreads=2
-XX:+CMSIncrementalPacing
-XX:CMSIncrementalDutyCycleMin=0
-XX:CMSIncrementalDutyCycle=5
-XX:GCTimeRatio=49
-XX:MaxGCPauseMillis=20
-XX:GCPauseIntervalMillis=1000
-XX:+UseCMSCompactAtFullCollection
-XX:+CMSClassUnloadingEnabled
-XX:+DoEscapeAnalysis
-XX:+UseCompressedOops
-XX:+AggressiveOpts
-XX:+ExplicitGCInvokesConcurrentAndUnloadsClasses
Note that this uses only 200 MB for the heap and 150 MB for the non-heap. If you're using huge plugins, you might want to increase both the "-Xmx200m" and "-XX:MaxPermSize=150m" limits.
The primary optimization target for these flags has been to minimize latency in all cases and as a secondary optimization target minimize the memory usage.
The Groovy script you provided is formatting the first line as a blank line in the resultant script. The shebang, telling the script to run with /bin/bash instead of /bin/sh, needs to be on the first line of the file or it will be ignored.
So instead, you should format your Groovy like this:
stage('Setting the variables values') {
steps {
sh '''#!/bin/bash
echo "hello world"
'''
}
}
And it will execute with /bin/bash.
You can use:
var queryString = url.Substring(url.IndexOf('?')).Split('#')[0]
System.Web.HttpUtility.ParseQueryString(queryString)
process.stdin.pipe(process.stdout);
Since the value of $var
is the empty string, this:
if [ $var == $var1 ]; then
expands to this:
if [ == abcd ]; then
which is a syntax error.
You need to quote the arguments:
if [ "$var" == "$var1" ]; then
You can also use =
rather than ==
; that's the original syntax, and it's a bit more portable.
If you're using bash, you can use the [[
syntax, which doesn't require the quotes:
if [[ $var = $var1 ]]; then
Even then, it doesn't hurt to quote the variable reference, and adding quotes:
if [[ "$var" = "$var1" ]]; then
might save a future reader a moment trying to remember whether [[
... ]]
requires them.
This did wonders for me:
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
Or you can use one SQL-command instead of create and call stored procedure
INSERT INTO [order_cart](orId,caId)
OUTPUT inserted.*
SELECT
(SELECT MAX(orId) FROM [order]) as orId,
(SELECT MAX(caId) FROM [cart]) as caId;
Bootstrap 4 is not yet a mature tool yet. The part of requiring another plugin to work is even more complicated especially for developers who have been using Bootstrap for a while. I have seen many ways to eliminate the error but not all work for everyone. I think the best and cleanest way to work with Bootstrap 4. Among the Bootstrap installation files, There is one with the name "bootstrap.bundle.js" that already comes with the Popper included.
How does it work if you only are using visible-md at Col4 instead? Do you use the -lg at all? If not this might work.
<div class="container">
<div class="row">
<div class="col-xs-4 col-sm-2 col-md-1" align="center">
Col1
</div>
<div class="col-xs-4 col-sm-2" align="center">
Col2
</div>
<div class="hidden-xs col-sm-6 col-md-5" align="center">
Col3
</div>
<div class="visible-md col-md-3 " align="center">
Col4
</div>
<div class="col-xs-4 col-sm-2 col-md-1" align="center">
Col5
</div>
</div>
</div>
Consider your REST API returns:
{"Intent":{"Command":"search","SubIntent":null}}
Then you can do the following to print it in a nice format:
<pre id="ciResponseText">Output will de displayed here.</pre>
var ciResponseText = document.getElementById('ciResponseText');
var obj = JSON.parse(http.response);
ciResponseText.innerHTML = JSON.stringify(obj, undefined, 2);
As has already been pointed out by others, using a function should be considered best practice.
However, here is another approach, leveraging xargs
:
alias junk="xargs -I "{}" -- mv "{}" "~/.Trash" <<< "
Note that this has side effects regarding redirection of streams.
Starting with PHP 8 (2020-11-24), you can use str_contains:
if (str_contains('www.domain.com/car/', 'car')) {
echo 'car is exist';
} else {
echo 'no cars';
}
Your @POST
method should be accepting a JSON object instead of a string. Jersey uses JAXB to support marshaling and unmarshaling JSON objects (see the jersey docs for details). Create a class like:
@XmlRootElement
public class MyJaxBean {
@XmlElement public String param1;
@XmlElement public String param2;
}
Then your @POST
method would look like the following:
@POST @Consumes("application/json")
@Path("/create")
public void create(final MyJaxBean input) {
System.out.println("param1 = " + input.param1);
System.out.println("param2 = " + input.param2);
}
This method expects to receive JSON object as the body of the HTTP POST. JAX-RS passes the content body of the HTTP message as an unannotated parameter -- input
in this case. The actual message would look something like:
POST /create HTTP/1.1
Content-Type: application/json
Content-Length: 35
Host: www.example.com
{"param1":"hello","param2":"world"}
Using JSON in this way is quite common for obvious reasons. However, if you are generating or consuming it in something other than JavaScript, then you do have to be careful to properly escape the data. In JAX-RS, you would use a MessageBodyReader and MessageBodyWriter to implement this. I believe that Jersey already has implementations for the required types (e.g., Java primitives and JAXB wrapped classes) as well as for JSON. JAX-RS supports a number of other methods for passing data. These don't require the creation of a new class since the data is passed using simple argument passing.
HTML <FORM>
The parameters would be annotated using @FormParam:
@POST
@Path("/create")
public void create(@FormParam("param1") String param1,
@FormParam("param2") String param2) {
...
}
The browser will encode the form using "application/x-www-form-urlencoded". The JAX-RS runtime will take care of decoding the body and passing it to the method. Here's what you should see on the wire:
POST /create HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 25
param1=hello¶m2=world
The content is URL encoded in this case.
If you do not know the names of the FormParam's you can do the following:
@POST @Consumes("application/x-www-form-urlencoded")
@Path("/create")
public void create(final MultivaluedMap<String, String> formParams) {
...
}
HTTP Headers
You can using the @HeaderParam annotation if you want to pass parameters via HTTP headers:
@POST
@Path("/create")
public void create(@HeaderParam("param1") String param1,
@HeaderParam("param2") String param2) {
...
}
Here's what the HTTP message would look like. Note that this POST does not have a body.
POST /create HTTP/1.1
Content-Length: 0
Host: www.example.com
param1: hello
param2: world
I wouldn't use this method for generalized parameter passing. It is really handy if you need to access the value of a particular HTTP header though.
HTTP Query Parameters
This method is primarily used with HTTP GETs but it is equally applicable to POSTs. It uses the @QueryParam annotation.
@POST
@Path("/create")
public void create(@QueryParam("param1") String param1,
@QueryParam("param2") String param2) {
...
}
Like the previous technique, passing parameters via the query string does not require a message body. Here's the HTTP message:
POST /create?param1=hello¶m2=world HTTP/1.1
Content-Length: 0
Host: www.example.com
You do have to be particularly careful to properly encode query parameters on the client side. Using query parameters can be problematic due to URL length restrictions enforced by some proxies as well as problems associated with encoding them.
HTTP Path Parameters
Path parameters are similar to query parameters except that they are embedded in the HTTP resource path. This method seems to be in favor today. There are impacts with respect to HTTP caching since the path is what really defines the HTTP resource. The code looks a little different than the others since the @Path annotation is modified and it uses @PathParam:
@POST
@Path("/create/{param1}/{param2}")
public void create(@PathParam("param1") String param1,
@PathParam("param2") String param2) {
...
}
The message is similar to the query parameter version except that the names of the parameters are not included anywhere in the message.
POST /create/hello/world HTTP/1.1
Content-Length: 0
Host: www.example.com
This method shares the same encoding woes that the query parameter version. Path segments are encoded differently so you do have to be careful there as well.
As you can see, there are pros and cons to each method. The choice is usually decided by your clients. If you are serving FORM
-based HTML pages, then use @FormParam
. If your clients are JavaScript+HTML5-based, then you will probably want to use JAXB-based serialization and JSON objects. The MessageBodyReader/Writer
implementations should take care of the necessary escaping for you so that is one fewer thing that can go wrong. If your client is Java based but does not have a good XML processor (e.g., Android), then I would probably use FORM
encoding since a content body is easier to generate and encode properly than URLs are. Hopefully this mini-wiki entry sheds some light on the various methods that JAX-RS supports.
Note: in the interest of full disclosure, I haven't actually used this feature of Jersey yet. We were tinkering with it since we have a number of JAXB+JAX-RS applications deployed and are moving into the mobile client space. JSON is a much better fit that XML on HTML5 or jQuery-based solutions.
What's the first part of your Subversion repository URL?
I can't guarantee the first four since it's possible to reconfigure everything to use different ports, of if you go through a proxy of some sort.
If you're using a VPN, you may have to configure your VPN client to reroute these to their correct ports. A lot of places don't configure their correctly VPNs to do this type of proxying. It's either because they have some sort of anal-retentive IT person who's being overly security conscious, or because they simply don't know any better. Even worse, they'll give you a client where this stuff can't be reconfigured.
The only way around that is to log into a local machine over the VPN, and then do everything from that system.
Why don't you use
DbTestDataContext obj = new DbTestDataContext();
var q =from a in obj.GetTable<TableName>() select a;
This is simple.
Since you want to pivot multiple columns of data, I would first suggest unpivoting the result
, score
and grade
columns so you don't have multiple columns but you will have multiple rows.
Depending on your version of SQL Server you can use the UNPIVOT function or CROSS APPLY. The syntax to unpivot the data will be similar to:
select ratio, col, value
from GRAND_TOTALS
cross apply
(
select 'result', cast(result as varchar(10)) union all
select 'score', cast(score as varchar(10)) union all
select 'grade', grade
) c(col, value)
See SQL Fiddle with Demo. Once the data has been unpivoted, then you can apply the PIVOT function:
select ratio = col,
[current ratio], [gearing ratio], [performance ratio], total
from
(
select ratio, col, value
from GRAND_TOTALS
cross apply
(
select 'result', cast(result as varchar(10)) union all
select 'score', cast(score as varchar(10)) union all
select 'grade', grade
) c(col, value)
) d
pivot
(
max(value)
for ratio in ([current ratio], [gearing ratio], [performance ratio], total)
) piv;
See SQL Fiddle with Demo. This will give you the result:
| RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO | TOTAL |
|--------|---------------|---------------|-------------------|-----------|
| grade | Good | Good | Satisfactory | Good |
| result | 1.29400 | 0.33840 | 0.04270 | (null) |
| score | 60.00000 | 70.00000 | 50.00000 | 180.00000 |
There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.
Similarity::Similarity()
or Similarity::~Similarity()
are just missing and you have defined the others incorrectly,
void Similarity::readData(Scanner& inStream){
}
not
void readData(Scanner& inStream){
}
etc. etc.
The second one is a function called readData, only the first is the readData method of the Similarity class.
To be clear about this, in Similarity.h
void readData(Scanner& inStream);
but in Similarity.cpp
void Similarity::readData(Scanner& inStream){
}
I solved the same issue setting 'laravel/framework'
dependency version from "^8.0"
to "^7.0"
.
After that running composer update --ignore-platform-reqs
simply worked
Although MP4 is supported in Internet explorer it does matter how you encode the file. Make sure you use BASELINE encoding when rendering the video file. This Fixed my issue with IE11
Already many valid answers to this question. Not many using a functional approach though. Here is an alternative solution using the forEach
method, which works well with callbacks and closures:
let arr = [1,2,3];
let myFunc = (val, index) => {
console.log('val: '+val+'\nindex: '+index);
};
arr.forEach(myFunc);
The Groovy way to do this is
def list = []
list << new MyType(...)
which creates a list and uses the overloaded leftShift
operator to append an item
See the Groovy docs on Lists for lots of examples.
The default value for InnoDB is actually pretty bad. InnoDB is very RAM dependent, you might find better result if you tweak the settings. Here's a guide that I used InnoDB optimization basic
I think natually do it is straightforward, whether Intellij IDEA or Android Studio, I always click new Java class menu, and then typing the class name, press Enter to create. after that, I manually typing "extends Activity" in the class file, and then import the class by shortcut key. finally, I also manually override the onCreate() method and invoke the setContentView() method.
Change your ref into: ref='title'
and delete name='title'
Then delete var title = this.title
and write:
console.log(this.refs.title.value)
Also you should add .bind(this)
to this.onSubmit
(It worked in my case which was quite similar, but instead of onClick
I had onSubmit={...}
and it was put in form ( <form onSubmit={...} ></form>)
)
RemoteEndPoint is a property, its type is System.Net.EndPoint which inherits from System.Net.IPEndPoint.
If you take a look at IPEndPoint's members, you'll see that there's an Address
property.
.toDate
did not really work for me, So, Here is what i did :
futureStartAtDate = new Date(moment().locale("en").add(1, 'd').format("MMM DD, YYYY HH:MM"))
hope this helps
Try with this code, you will get the image preview while uploading
<input type='file' id="upload" onChange="readURL(this);"/>
<img id="img" src="#" alt="your image" />
function readURL(input){
var ext = input.files[0]['name'].substring(input.files[0]['name'].lastIndexOf('.') + 1).toLowerCase();
if (input.files && input.files[0] && (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg"))
var reader = new FileReader();
reader.onload = function (e) {
$('#img').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}else{
$('#img').attr('src', '/assets/no_preview.png');
}
}
Use libraries https://jar-download.com/maven-repository-class-search.php?search_box=org.apache.http.entity.mime Download the library and put it in your project
You should try using the option -i
for in-place editing.
You can search a directory using Find
? Find in files
. This also includes all opened tabs.
The keyboard shortcut is Ctrl?+F on non-Mac (regular) keyboards, and ??+F on a Mac.
You'll be presented with three boxes: Find
, Where
and Replace
. It's a regular Find/Find-replace search where Where
specifies a file or directory to search. I for example often use a file name or .
for searching the current directory. There are also a few special constructs that can be used within the Where
field:
<project>,<current file>,<open files>,<open folders>,-*.doc,*.txt
Note that these are not placeholders, you type these verbatim.
Most of them are self-explanatory (e.g. -*.doc
excludes files with a .doc
extension).
Pressing the ...
to the right will present you with all available options.
After searching you'll be presented with a Find results
page with all of your matching results. To jump to specific lines and files from it you simply double-click on a line.
In python 2.7 and higher, you can use dictionary comprehension: This is an example I encountered while reading a CSV using a DictReader. The user had suffixed all the column names with ':'
ori_dict = {'key1:' : 1, 'key2:' : 2, 'key3:' : 3}
to get rid of the trailing ':' in the keys:
corrected_dict = { k.replace(':', ''): v for k, v in ori_dict.items() }
As far as I can tell, .NET does support persisting settings using the built-in application settings facility:
The Application Settings feature of Windows Forms makes it easy to create, store, and maintain custom application and user preferences on the client computer. With Windows Forms application settings, you can store not only application data such as database connection strings, but also user-specific data, such as user application preferences. Using Visual Studio or custom managed code, you can create new settings, read them from and write them to disk, bind them to properties on your forms, and validate settings data prior to loading and saving. - http://msdn.microsoft.com/en-us/library/k4s6c3a0.aspx
If you are using eloquent model (by looking at your code, i think you are), you dont need to convert it into array. Just use it as object. Becaus elike Thomas Kim said, by default it is a Carbon instance
So it should be
$suborder['payment_date'] = $item->created_at->format('Y-m-d')
But if it is not then, you need convert it to Carbon object as Milan Maharjan answer
$createdAt = Carbon::parse($item['created_at']);
I've had good results with this one. Much easier to use than Sharpen.
http://tangiblesoftwaresolutions.com/Product_Details/Java_to_CSharp_Converter.html
You just need to correct the format of your html
<form>
<li>Number 1: <input type="text" ng-model="one"/> </li>
<li>Number 2: <input type="text" ng-model="two"/> </li>
<li>Total <input type="text" value="{{total()}}"/> </li>
{{total()}}
</form>
Update in 2020. Here is another way if you prefer.
IdentityResult res = new IdentityResult();
var _role = new IdentityRole();
_role.Name = role.RoleName;
res = await _roleManager.CreateAsync(_role);
if (!res.Succeeded)
{
foreach (IdentityError er in res.Errors)
{
ModelState.AddModelError(string.Empty, er.Description);
}
ViewBag.UserMessage = "Error Adding Role";
return View();
}
else
{
ViewBag.UserMessage = "Role Added";
return View();
}
I guess the most universal solution here - is to check for undefined
and null
first, then just call constructor.name.toLowerCase()
.
const getType = v =>
v === undefined
? 'undefined'
: v === null
? 'null'
: v.constructor.name.toLowerCase();
console.log(getType(undefined)); // 'undefined'
console.log(getType(null)); // 'null'
console.log(getType('')); // 'string'
console.log(getType([])); // 'array'
console.log(getType({})); // 'object'
console.log(getType(new Set())); // `set'
console.log(getType(Promise.resolve())); // `promise'
console.log(getType(new Map())); // `map'