If more than one result is expected, then the getResponse()
method will return a Vector
containing the various responses.
In which case the offending code becomes:
Object result = envelope.getResponse();
// treat result as a vector
String resultText = null;
if (result instanceof Vector)
{
SoapPrimitive element0 = (SoapPrimitive)((Vector) result).elementAt(0);
resultText = element0.toString();
}
tv.setText(resultText);
Answer based on the ksoap2-android (mosabua fork)
If you want to uniquely identify a row within the table rather than your result set, then you need to look at using something like an IDENTITY column. See "IDENTITY property" in the SQL Server help. SQL Server does not auto-generate an ID for each row in the table as Oracle does, so you have to go to the trouble of creating your own ID column and explicitly fetch it in your query.
EDIT: for dynamic numbering of result set rows see below, but that would probably an equivalent for Oracle's ROWNUM and I assume from all the comments on the page that you want the stuff above. For SQL Server 2005 and later you can use the new Ranking Functions function to achieve dynamic numbering of rows.
For example I do this on a query of mine:
select row_number() over (order by rn_execution_date asc) as 'Row Number', rn_execution_date as 'Execution Date', count(*) as 'Count'
from td.run
where rn_execution_date >= '2009-05-19'
group by rn_execution_date
order by rn_execution_date asc
Will give you:
Row Number Execution Date Count
---------- ----------------- -----
1 2009-05-19 00:00:00.000 280
2 2009-05-20 00:00:00.000 269
3 2009-05-21 00:00:00.000 279
There's also an article on support.microsoft.com on dynamically numbering rows.
Running the apc.php script is key to understanding what your problem is, IMO. This helped us size our cache properly and for the moment, seems to have resolved the problem.
Most simple, without caring about delegates
if(textBox1.InvokeRequired == true)
textBox1.Invoke((MethodInvoker)delegate { textBox1.Text = "Invoke was needed";});
else
textBox1.Text = "Invoke was NOT needed";
Using the previous method with more than 1 slide at time was giving me the wrong total so I've used the "dotsClass", like this (on v1.7.1):
// JS
var slidesPerPage = 6
$(".slick").on("init", function(event, slick){
maxPages = Math.ceil(slick.slideCount/slidesPerPage);
$(this).find('.slider-paging-number li').append('/ '+maxPages);
});
$(".slick").slick({
slidesToShow: slidesPerPage,
slidesToScroll: slidesPerPage,
arrows: false,
autoplay: true,
dots: true,
infinite: true,
dotsClass: 'slider-paging-number'
});
// CSS
ul.slider-paging-number {
list-style: none;
li {
display: none;
&.slick-active {
display: inline-block;
}
button {
background: none;
border: none;
}
}
}
These are the steps I used to fix the issue:
To add nuget packages to your solution:
http://en.wikipedia.org/wiki/Post/Redirect/Get
The most common way to implement this pattern in ASP.Net is to use Response.Redirect(Request.RawUrl)
Consider the differences between Redirect and Transfer. Transfer really isn't telling the browser to forward to a clear form, it's simply returning a cleared form. That may or may not be what you want.
Response.Redirect() does not a waste round trip. If you post to a script that clears the form by Server.Transfer() and reload you will be asked to repost by most browsers since the last action was a HTTP POST. This may cause your users to unintentionally repeat some action, eg. place a second order which will have to be voided later.
You want in page A to know the URL of page B?
Or to know in page B the URL of page A?
In Page B: document.referrer if set. As already shown here: How to get the previous URL in JavaScript?
In page A you would need to read a cookie or local/sessionStorage you set in page B, assuming the same domains
The dot "." is a special character in java regex engine, so you have to use "\\." to escape this character:
final String extensionRemoved = filename.split("\\.")[0];
I hope this helps
If you want that for display purposes, use java.text.DecimalFormat
:
new DecimalFormat("#.##").format(dblVar);
If you need it for calculations, use java.lang.Math
:
Math.floor(value * 100) / 100;
An iframe is used to embed another document inside a html page.
If the form is to be submitted to an iframe within the form page, then it can be easily acheived using the target attribute of the tag.
Set the target attribute of the form to the name of the iframe tag.
<form action="action" method="post" target="output_frame">
<!-- input elements here -->
</form>
<iframe name="output_frame" src="" id="output_frame" width="XX" height="YY">
</iframe>
Advanced iframe target use
This property can also be used to produce an ajax like experience, especially in cases like file upload, in which case where it becomes mandatory to submit the form, in order to upload the files
The iframe can be set to a width and height of 0, and the form can be submitted with the target set to the iframe, and a loading dialog opened before submitting the form. So, it mocks a ajax control as the control still remains on the input form jsp, with the loading dialog open.
Exmaple
<script>
$( "#uploadDialog" ).dialog({ autoOpen: false, modal: true, closeOnEscape: false,
open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); } });
function startUpload()
{
$("#uploadDialog").dialog("open");
}
function stopUpload()
{
$("#uploadDialog").dialog("close");
}
</script>
<div id="uploadDialog" title="Please Wait!!!">
<center>
<img src="/imagePath/loading.gif" width="100" height="100"/>
<br/>
Loading Details...
</center>
</div>
<FORM ENCTYPE="multipart/form-data" ACTION="Action" METHOD="POST" target="upload_target" onsubmit="startUpload()">
<!-- input file elements here-->
</FORM>
<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;" onload="stopUpload()">
</iframe>
Try using the below command.
git credential-manager
Here you can get various options to manage your credentials (check the below screen).
Or you can even directly try this command:
git credential-manager uninstall
This will start prompting for passwords again on each server interaction request.
How about:
ACell.ListObject.DataBodyRange.Rows.Delete
That will keep your table structure and headings, but clear all the data and rows.
EDIT: I'm going to just modify a section of my answer from your previous post, as it does mostly what you want. This leaves just one row:
With loSource
.Range.AutoFilter
.DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete
.DataBodyRange.Rows(1).Specialcells(xlCellTypeConstants).ClearContents
End With
If you want to leave all the rows intact with their formulas and whatnot, just do:
With loSource
.Range.AutoFilter
.DataBodyRange.Specialcells(xlCellTypeConstants).ClearContents
End With
Which is close to what @Readify suggested, except it won't clear formulas.
You can use date filter to convert in date and display in specific format.
In .ts file (typescript):
let dateString = '1968-11-16T00:00:00'
let newDate = new Date(dateString);
In HTML:
{{dateString | date:'MM/dd/yyyy'}}
Below are some formats which you can implement :
Backend:
public todayDate = new Date();
HTML :
<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option>
</select>
Note: You should sort the list before using groupby
.
You can use groupby
from itertools
package if the list is an ordered list.
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
from itertools import groupby
[len(list(group)) for key, group in groupby(a)]
Output:
[4, 4, 2, 1, 2]
update: Note that sorting takes O(n log(n)) time.
You said you are using process.on('uncaughtException', callback);
Where are you executing this statement? Is it within the callback passed to http.createServer
?
If yes, different copy of the same callback will get attached to the uncaughtException event upon each new request, because the function (req, res) { ... }
gets executed everytime a new request comes in and so will the statement process.on('uncaughtException', callback);
Note that the process object is global to all your requests and adding listeners to its event everytime a new request comes in will not make any sense. You might not want such kind of behaviour.
In case you want to attach a new listener for each new request, you should remove all previous listeners attached to the event as they no longer would be required using:
process.removeAllListeners('uncaughtException');
<TextBlock Text="Stuff on line1
Stuff on line 2"/>
You can use any hexadecimally encoded value to represent a literal. In this case, I used the line feed (char 10). If you want to do "classic" vbCrLf
, then you can use 

By the way, note the syntax: It's the ampersand, a pound, the letter x, then the hex value of the character you want, and then finally a semi-colon.
ALSO: For completeness, you can bind to a text that already has the line feeds embedded in it like a constant in your code behind, or a variable constructed at runtime.
You can use this method to pick image from gallery. Only images will be displayed.
public void pickImage() {
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("scale", true);
intent.putExtra("outputX", 256);
intent.putExtra("outputY", 256);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("return-data", true);
startActivityForResult(intent, 1);
}
and override onActivityResult as
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
if (requestCode == 1) {
final Bundle extras = data.getExtras();
if (extras != null) {
//Get image
Bitmap newProfilePic = extras.getParcelable("data");
}
}
}
I faced this problem on CentOS.
First I try this
sudo service mysql restart
Then error shows up
Redirecting to /bin/systemctl restart mysql.service
Failed to restart mysql.service: Unit not found.
Then I Found this
Command this solve my problem
systemctl start mariadb.service
Look in the file Microsoft.Common.targets
The answer to the question is in the file Microsoft.Common.targets
for your target framework version.
For .Net Framework version 4.0 (and 4.5 !) the AssemblySearchPaths-element is defined like this:
<!--
The SearchPaths property is set to find assemblies in the following order:
(1) Files from current project - indicated by {CandidateAssemblyFiles}
(2) $(ReferencePath) - the reference path property, which comes from the .USER file.
(3) The hintpath from the referenced item itself, indicated by {HintPathFromItem}.
(4) The directory of MSBuild's "target" runtime from GetFrameworkPath.
The "target" runtime folder is the folder of the runtime that MSBuild is a part of.
(5) Registered assembly folders, indicated by {Registry:*,*,*}
(6) Legacy registered assembly folders, indicated by {AssemblyFolders}
(7) Resolve to the GAC.
(8) Treat the reference's Include as if it were a real file name.
(9) Look in the application's output folder (like bin\debug)
-->
<AssemblySearchPaths Condition=" '$(AssemblySearchPaths)' == ''">
{CandidateAssemblyFiles};
$(ReferencePath);
{HintPathFromItem};
{TargetFrameworkDirectory};
{Registry:$(FrameworkRegistryBase),$(TargetFrameworkVersion),$(AssemblyFoldersSuffix)$(AssemblyFoldersExConditions)};
{AssemblyFolders};
{GAC};
{RawFileName};
$(OutDir)
</AssemblySearchPaths>
For .Net Framework 3.5 the definition is the same, but the comment is wrong. The 2.0 definition is slightly different, it uses $(OutputPath) instead of $(OutDir).
On my machine I have the following versions of the file Microsoft.Common.targets:
C:\Windows\Microsoft.NET\Framework\v2.0.50727\Microsoft.Common.targets
C:\Windows\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets
C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Microsoft.Common.targets
C:\Windows\Microsoft.NET\Framework64\v3.5\Microsoft.Common.targets
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Microsoft.Common.targets
This is with Visual Studio 2008, 2010 and 2013 installed on Windows 7.
The fact that the output directory is searched can be a bit frustrating (as the original poster points out) because it may hide an incorrect HintPath. The solution builds OK on your local machine, but breaks when you build on in a clean folder structure (e.g. on the build machine).
Java does not support multiple inheritance. However, your problem may be solved using interfaces.
The easiest solution would be to create an interface for AbstractBillingActivity
and PreferenceActivity
and implement them both.
BIRT works pretty well.
I tried re-creating this, and .someclass.notip
was being generated for me but .someclass:not(.notip)
was not, for as long as I did not have the @mixin tip()
defined. Once I had that, it all worked.
http://sassmeister.com/gist/9775949
$dropdown-width: 100px;
$comp-tip: true;
@mixin tip($pos:right) {
}
@mixin dropdown-pos($pos:right) {
&:not(.notip) {
@if $comp-tip == true{
@if $pos == right {
top:$dropdown-width * -0.6;
background-color: #f00;
@include tip($pos:$pos);
}
}
}
&.notip {
@if $pos == right {
top: 0;
left:$dropdown-width * 0.8;
background-color: #00f;
}
}
}
.someclass { @include dropdown-pos(); }
EDIT: http://sassmeister.com/ is a good place to debug your SASS because it gives you error messages. Undefined mixin 'tip'.
it what I get when I remove @mixin tip($pos:right) { }
You can try something like this:
strncpy(new_str, str1, strlen(str1));
strcat(new_str, str2);
More info on strncpy: http://www.cplusplus.com/reference/clibrary/cstring/strncpy/
For understanding templates, it's of huge advantage to get the terminology straight because the way you speak about them determines the way to think about them.
Specifically, Area
is not a template class, but a class template. That is, it is a template from which classes can be generated. Area<int>
is such a class (it's not an object, but of course you can create an object from that class in the same ways you can create objects from any other class). Another such class would be Area<char>
. Note that those are completely different classes, which have nothing in common except for the fact that they were generated from the same class template.
Since Area
is not a class, you cannot derive the class Rectangle
from it. You only can derive a class from another class (or several of them). Since Area<int>
is a class, you could, for example, derive Rectangle
from it:
class Rectangle:
public Area<int>
{
// ...
};
Since Area<int>
and Area<char>
are different classes, you can even derive from both at the same time (however when accessing members of them, you'll have to deal with ambiguities):
class Rectangle:
public Area<int>,
public Area<char>
{
// ...
};
However you have to specify which classed to derive from when you define Rectangle
. This is true no matter whether those classes are generated from a template or not. Two objects of the same class simply cannot have different inheritance hierarchies.
What you can do is to make Rectangle
a template as well. If you write
template<typename T> class Rectangle:
public Area<T>
{
// ...
};
You have a template Rectangle
from which you can get a class Rectangle<int>
which derives from Area<int>
, and a different class Rectangle<char>
which derives from Area<char>
.
It may be that you want to have a single type Rectangle
so that you can pass all sorts of Rectangle
to the same function (which itself doesn't need to know the Area type). Since the Rectangle<T>
classes generated by instantiating the template Rectangle
are formally independent of each other, it doesn't work that way. However you can make use of multiple inheritance here:
class Rectangle // not inheriting from any Area type
{
// Area independent interface
};
template<typename T> class SpecificRectangle:
public Rectangle,
public Area<T>
{
// Area dependent stuff
};
void foo(Rectangle&); // A function which works with generic rectangles
int main()
{
SpecificRectangle<int> intrect;
foo(intrect);
SpecificRectangle<char> charrect;
foo(charrect);
}
If it is important that your generic Rectangle
is derived from a generic Area
you can do the same trick with Area
too:
class Area
{
// generic Area interface
};
class Rectangle:
public virtual Area // virtual because of "diamond inheritance"
{
// generic rectangle interface
};
template<typename T> class SpecificArea:
public virtual Area
{
// specific implementation of Area for type T
};
template<typename T> class SpecificRectangle:
public Rectangle, // maybe this should be virtual as well, in case the hierarchy is extended later
public SpecificArea<T> // no virtual inheritance needed here
{
// specific implementation of Rectangle for type T
};
You can pass small bits of key/value pair data via the query string:
res.redirect('/?error=denied');
And javascript on the home page can access that and adjust its behavior accordingly.
Note that if you don't mind /category
staying as the URL in the browser address bar, you can just render directly instead of redirecting. IMHO many times people use redirects because older web frameworks made directly responding difficult, but it's easy in express:
app.post('/category', function(req, res) {
// Process the data received in req.body
res.render('home.jade', {error: 'denied'});
});
As @Dropped.on.Caprica commented, using AJAX eliminates the URL changing concern.
class Foo (object):
# ^class name #^ inherits from object
bar = "Bar" #Class attribute.
def __init__(self):
# #^ The first variable is the class instance in methods.
# # This is called "self" by convention, but could be any name you want.
#^ double underscore (dunder) methods are usually special. This one
# gets called immediately after a new instance is created.
self.variable = "Foo" #instance attribute.
print self.variable, self.bar #<---self.bar references class attribute
self.bar = " Bar is now Baz" #<---self.bar is now an instance attribute
print self.variable, self.bar
def method(self, arg1, arg2):
#This method has arguments. You would call it like this: instance.method(1, 2)
print "in method (args):", arg1, arg2
print "in method (attributes):", self.variable, self.bar
a = Foo() # this calls __init__ (indirectly), output:
# Foo bar
# Foo Bar is now Baz
print a.variable # Foo
a.variable = "bar"
a.method(1, 2) # output:
# in method (args): 1 2
# in method (attributes): bar Bar is now Baz
Foo.method(a, 1, 2) #<--- Same as a.method(1, 2). This makes it a little more explicit what the argument "self" actually is.
class Bar(object):
def __init__(self, arg):
self.arg = arg
self.Foo = Foo()
b = Bar(a)
b.arg.variable = "something"
print a.variable # something
print b.Foo.variable # Foo
While other answers perfectly explained the question I will add some real life examples converting tensors to numpy array:
PyTorch tensor residing on CPU shares the same storage as numpy array na
import torch
a = torch.ones((1,2))
print(a)
na = a.numpy()
na[0][0]=10
print(na)
print(a)
Output:
tensor([[1., 1.]])
[[10. 1.]]
tensor([[10., 1.]])
To avoid the effect of shared storage we need to copy()
the numpy array na
to a new numpy array nac
. Numpy copy()
method creates the new separate storage.
import torch
a = torch.ones((1,2))
print(a)
na = a.numpy()
nac = na.copy()
nac[0][0]=10
?print(nac)
print(na)
print(a)
Output:
tensor([[1., 1.]])
[[10. 1.]]
[[1. 1.]]
tensor([[1., 1.]])
Now, just the nac
numpy array will be altered with the line nac[0][0]=10
, na
and a
will remain as is.
requires_grad=True
import torch
a = torch.ones((1,2), requires_grad=True)
print(a)
na = a.detach().numpy()
na[0][0]=10
print(na)
print(a)
Output:
tensor([[1., 1.]], requires_grad=True)
[[10. 1.]]
tensor([[10., 1.]], requires_grad=True)
In here we call:
na = a.numpy()
This would cause: RuntimeError: Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead.
, because tensors that require_grad=True
are recorded by PyTorch AD. Note that tensor.detach()
is the new way for tensor.data
.
This explains why we need to detach()
them first before converting using numpy()
.
requires_grad=False
a = torch.ones((1,2), device='cuda')
print(a)
na = a.to('cpu').numpy()
na[0][0]=10
print(na)
print(a)
Output:
tensor([[1., 1.]], device='cuda:0')
[[10. 1.]]
tensor([[1., 1.]], device='cuda:0')
?
requires_grad=True
a = torch.ones((1,2), device='cuda', requires_grad=True)
print(a)
na = a.detach().to('cpu').numpy()
na[0][0]=10
?print(na)
print(a)
Output:
tensor([[1., 1.]], device='cuda:0', requires_grad=True)
[[10. 1.]]
tensor([[1., 1.]], device='cuda:0', requires_grad=True)
Without detach()
method the error RuntimeError: Can't call
numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead.
will be set.
Without .to('cpu')
method TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.
will be set.
You could use cpu()
but instead of to('cpu')
but I prefer the newer to('cpu')
.
There is probably a smarter way, but you can add the headers manually like this:
var client = new IdentityProofingService.IdentityProofingWSClient();
using (new OperationContextScope(client.InnerChannel))
{
OperationContext.Current.OutgoingMessageHeaders.Add(
new SecurityHeader("UsernameToken-49", "12345/userID", "password123"));
client.invokeIdentityService(new IdentityProofingRequest());
}
Here, SecurityHeader
is a custom implemented class, which needs a few other classes since I chose to use attributes to configure the XML serialization:
public class SecurityHeader : MessageHeader
{
private readonly UsernameToken _usernameToken;
public SecurityHeader(string id, string username, string password)
{
_usernameToken = new UsernameToken(id, username, password);
}
public override string Name
{
get { return "Security"; }
}
public override string Namespace
{
get { return "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; }
}
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
XmlSerializer serializer = new XmlSerializer(typeof(UsernameToken));
serializer.Serialize(writer, _usernameToken);
}
}
[XmlRoot(Namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd")]
public class UsernameToken
{
public UsernameToken()
{
}
public UsernameToken(string id, string username, string password)
{
Id = id;
Username = username;
Password = new Password() {Value = password};
}
[XmlAttribute(Namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd")]
public string Id { get; set; }
[XmlElement]
public string Username { get; set; }
[XmlElement]
public Password Password { get; set; }
}
public class Password
{
public Password()
{
Type = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText";
}
[XmlAttribute]
public string Type { get; set; }
[XmlText]
public string Value { get; set; }
}
I have not added the Nonce
bit to the UsernameToken
XML, but it is very similar to the Password
one. The Created
element also needs to be added still, but it's a simple [XmlElement]
.
var obj = {
"key1" : "k1",
"key2" : "k2",
"key3" : "k3"
};
if ("key1" in obj)
console.log("has key1 in obj");
=========================================================================
To access a child key of another key
var obj = {
"key1": "k1",
"key2": "k2",
"key3": "k3",
"key4": {
"keyF": "kf"
}
};
if ("keyF" in obj.key4)
console.log("has keyF in obj");
you could always create a new list which is a result of adding two lists.
>>> k = [1,2,3] + [4,7,9]
>>> k
[1, 2, 3, 4, 7, 9]
Lists are mutable sequences so I guess it makes sense to modify the original lists by extend or append.
Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.
Specifying the columns on your query should do the trick:
select a.col1, b.col2, a.col3, b.col4, a.category_id
from items_a a, items_b b
where a.category_id = b.category_id
should do the trick with regards to picking the columns you want.
To get around the fact that some data is only in items_a and some data is only in items_b, you would be able to do:
select
coalesce(a.col1, b.col1) as col1,
coalesce(a.col2, b.col2) as col2,
coalesce(a.col3, b.col3) as col3,
a.category_id
from items_a a, items_b b
where a.category_id = b.category_id
The coalesce function will return the first non-null value, so for each row if col1 is non null, it'll use that, otherwise it'll get the value from col2, etc.
Using command prompt in windows you can use below command to get class files.
wsimport "complete file path of your .wsdl file"
example : wsimport C:\Users\schemas\com\myprofile\myprofile2019.wsdl
if you want to generate source code you should be using below commnad.
wsimport -keep -s src "complete file path of your .wsdl file"
example : wsimport -keep -s src C:\Users\schemas\com\myprofile\myprofile2019.wsdl
Note : Here "-s" means source directory and "src" is name of folder that should be created before executing this command. Wsimport is a tool which is bundled along with JAVA SE, no seperate download is required.
You can use File.AppendAllText
for that:
File.AppendAllText(@"c:\path\file.txt", "text content" + Environment.NewLine);
NumPy 1.7.0 (when numpy.pad
was added) is pretty old now (it was released in 2013) so even though the question asked for a way without using that function I thought it could be useful to know how that could be achieved using numpy.pad
.
It's actually pretty simple:
>>> import numpy as np
>>> a = np.array([[ 1., 1., 1., 1., 1.],
... [ 1., 1., 1., 1., 1.],
... [ 1., 1., 1., 1., 1.]])
>>> np.pad(a, [(0, 1), (0, 1)], mode='constant')
array([[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 0., 0., 0., 0., 0., 0.]])
In this case I used that 0
is the default value for mode='constant'
. But it could also be specified by passing it in explicitly:
>>> np.pad(a, [(0, 1), (0, 1)], mode='constant', constant_values=0)
array([[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 0., 0., 0., 0., 0., 0.]])
Just in case the second argument ([(0, 1), (0, 1)]
) seems confusing: Each list item (in this case tuple) corresponds to a dimension and item therein represents the padding before (first element) and after (second element). So:
[(0, 1), (0, 1)]
^^^^^^------ padding for second dimension
^^^^^^-------------- padding for first dimension
^------------------ no padding at the beginning of the first axis
^--------------- pad with one "value" at the end of the first axis.
In this case the padding for the first and second axis are identical, so one could also just pass in the 2-tuple:
>>> np.pad(a, (0, 1), mode='constant')
array([[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 0., 0., 0., 0., 0., 0.]])
In case the padding before and after is identical one could even omit the tuple (not applicable in this case though):
>>> np.pad(a, 1, mode='constant')
array([[ 0., 0., 0., 0., 0., 0., 0.],
[ 0., 1., 1., 1., 1., 1., 0.],
[ 0., 1., 1., 1., 1., 1., 0.],
[ 0., 1., 1., 1., 1., 1., 0.],
[ 0., 0., 0., 0., 0., 0., 0.]])
Or if the padding before and after is identical but different for the axis, you could also omit the second argument in the inner tuples:
>>> np.pad(a, [(1, ), (2, )], mode='constant')
array([[ 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 1., 1., 1., 1., 1., 0., 0.],
[ 0., 0., 1., 1., 1., 1., 1., 0., 0.],
[ 0., 0., 1., 1., 1., 1., 1., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
However I tend to prefer to always use the explicit one, because it's just to easy to make mistakes (when NumPys expectations differ from your intentions):
>>> np.pad(a, [1, 2], mode='constant')
array([[ 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 1., 1., 1., 1., 1., 0., 0.],
[ 0., 1., 1., 1., 1., 1., 0., 0.],
[ 0., 1., 1., 1., 1., 1., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0.]])
Here NumPy thinks you wanted to pad all axis with 1 element before and 2 elements after each axis! Even if you intended it to pad with 1 element in axis 1 and 2 elements for axis 2.
I used lists of tuples for the padding, note that this is just "my convention", you could also use lists of lists or tuples of tuples, or even tuples of arrays. NumPy just checks the length of the argument (or if it doesn't have a length) and the length of each item (or if it has a length)!
I was also having this same error but hopefully after spending 1 day on this error i have got this solution and it got started perfectly and i also hope this works for you guys also...
pip install --upgrade --force-reinstall <package>
When upgrading, reinstall all packages even if they are already up-to-date.
pip install -I <package>
pip install --ignore-installed <package>
Ignore the installed packages (reinstalling instead).
Use this icons with bootstrap (glyphicon):
<span class="glyphicon glyphicon-triangle-bottom"></span>
<span class="glyphicon glyphicon-triangle-top"></span>
http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_glyph_triangle-bottom&stacked=h
http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_glyph_triangle-bottom&stacked=h
Take a look at the Mockito API docs. As the linked document mentions (Point # 12) you can use any of the doThrow()
,doAnswer()
,doNothing()
,doReturn()
family of methods from Mockito framework to mock void methods.
For example,
Mockito.doThrow(new Exception()).when(instance).methodName();
or if you want to combine it with follow-up behavior,
Mockito.doThrow(new Exception()).doNothing().when(instance).methodName();
Presuming that you are looking at mocking the setter setState(String s)
in the class World below is the code uses doAnswer
method to mock the setState
.
World mockWorld = mock(World.class);
doAnswer(new Answer<Void>() {
public Void answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
System.out.println("called with arguments: " + Arrays.toString(args));
return null;
}
}).when(mockWorld).setState(anyString());
Extend your WHERE
condition:
WHERE
(FirstName = ISNULL(@FirstName, FirstName)
OR COALESCE(@FirstName, FirstName, '') = '')
AND (LastName = ISNULL(@LastName, LastName)
OR COALESCE(@LastName, LastName, '') = '')
AND (Title = ISNULL(@Title, Title)
OR COALESCE(@Title, Title, '') = '')
i. e. combine different cases with boolean conditions.
It is just a name change. before_action
is more specific, because it gets executed before an action.
You JSON doesn't match your struct fields: E.g. "district" in JSON and "District" as the field.
Also: Your Item is a slice type but your JSON is a dict value. Do not mix this up. Slices decode from arrays.
I don't think that there are any neat tricks you can do storing this as you can do for example with an MD5 hash.
I think your best bet is to store it as a CHAR(60)
as it is always 60 chars long
You are sending a POST AJAX request so use $albumname = $_POST['album'];
on your server to fetch the value. Also I would recommend you writing the request like this in order to ensure proper encoding:
$.ajax({
type: 'POST',
url: 'test.php',
data: { album: this.title },
success: function(response) {
content.html(response);
}
});
or in its shorter form:
$.post('test.php', { album: this.title }, function() {
content.html(response);
});
and if you wanted to use a GET request:
$.ajax({
type: 'GET',
url: 'test.php',
data: { album: this.title },
success: function(response) {
content.html(response);
}
});
or in its shorter form:
$.get('test.php', { album: this.title }, function() {
content.html(response);
});
and now on your server you wil be able to use $albumname = $_GET['album'];
. Be careful though with AJAX GET requests as they might be cached by some browsers. To avoid caching them you could set the cache: false
setting.
$num = "+918883967576";
$str = substr($num, 3);
echo $str;
Output:8883967576
with pages as (
SELECT object_id, SUM (reserved_page_count) as reserved_pages, SUM (used_page_count) as used_pages,
SUM (case
when (index_id < 2) then (in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count)
else lob_used_page_count + row_overflow_used_page_count
end) as pages
FROM sys.dm_db_partition_stats
group by object_id
), extra as (
SELECT p.object_id, sum(reserved_page_count) as reserved_pages, sum(used_page_count) as used_pages
FROM sys.dm_db_partition_stats p, sys.internal_tables it
WHERE it.internal_type IN (202,204,211,212,213,214,215,216) AND p.object_id = it.object_id
group by p.object_id
)
SELECT object_schema_name(p.object_id) + '.' + object_name(p.object_id) as TableName, (p.reserved_pages + isnull(e.reserved_pages, 0)) * 8 as reserved_kb,
pages * 8 as data_kb,
(CASE WHEN p.used_pages + isnull(e.used_pages, 0) > pages THEN (p.used_pages + isnull(e.used_pages, 0) - pages) ELSE 0 END) * 8 as index_kb,
(CASE WHEN p.reserved_pages + isnull(e.reserved_pages, 0) > p.used_pages + isnull(e.used_pages, 0) THEN (p.reserved_pages + isnull(e.reserved_pages, 0) - p.used_pages + isnull(e.used_pages, 0)) else 0 end) * 8 as unused_kb
from pages p
left outer join extra e on p.object_id = e.object_id
Takes into account internal tables, such as those used for XML storage.
Edit: If you divide the data_kb
and index_kb
values by 1024.0, you will get the numbers you see in the GUI.
Try following steps:
ipconfig
(or ifconfig
on Linux) at command prompt. This will give you the IP address of your own machine. For example, your machine's IP address is 192.168.1.6. So your broadcast IP address is 192.168.1.255.ping 192.168.1.255
(may require -b
on Linux)arp -a
. You will get the list of all IP addresses on your segment.Unlike if
, guard
creates the variable that can be accessed from outside its block. It is useful to unwrap a lot of Optional
s.
The
<a href="image2.gif" ><img src="image1.gif"/></a>
technique has always worked for me. I used it to good effect in my Super Bowl diary, but I see that the scripts I used are broken. Once I get them fixed I will edit in the URL.
bind()
of INADDR_ANY
does NOT "generate a random IP". It binds the socket to all available interfaces.
For a server, you typically want to bind to all interfaces - not just "localhost".
If you wish to bind your socket to localhost only, the syntax would be my_sockaddress.sin_addr.s_addr = inet_addr("127.0.0.1");
, then call bind(my_socket, (SOCKADDR *) &my_sockaddr, ...)
.
As it happens, INADDR_ANY
is a constant that happens to equal "zero":
http://www.castaglia.org/proftpd/doc/devel-guide/src/include/inet.h.html
# define INADDR_ANY ((unsigned long int) 0x00000000)
...
# define INADDR_NONE 0xffffffff
...
# define INPORT_ANY 0
...
If you're not already familiar with it, I urge you to check out Beej's Guide to Sockets Programming:
Since people are still reading this, an additional note:
When a process wants to receive new incoming packets or connections, it should bind a socket to a local interface address using bind(2).
In this case, only one IP socket may be bound to any given local (address, port) pair. When INADDR_ANY is specified in the bind call, the socket will be bound to all local interfaces.
When listen(2) is called on an unbound socket, the socket is automatically bound to a random free port with the local address set to INADDR_ANY.
When connect(2) is called on an unbound socket, the socket is automatically bound to a random free port or to a usable shared port with the local address set to INADDR_ANY...
There are several special addresses: INADDR_LOOPBACK (127.0.0.1) always refers to the local host via the loopback device; INADDR_ANY (0.0.0.0) means any address for binding...
Also:
bind() — Bind a name to a socket:
If the (sin_addr.s_addr) field is set to the constant INADDR_ANY, as defined in netinet/in.h, the caller is requesting that the socket be bound to all network interfaces on the host. Subsequently, UDP packets and TCP connections from all interfaces (which match the bound name) are routed to the application. This becomes important when a server offers a service to multiple networks. By leaving the address unspecified, the server can accept all UDP packets and TCP connection requests made for its port, regardless of the network interface on which the requests arrived.
The message is clear: you have a repeated column in the mapping. That means you mapped the same database column twice. And indeed, you have:
@Column(nullable=false)
private Long customerId;
and also:
@ManyToOne(optional=false)
@JoinColumn(name="customerId",referencedColumnName="id_customer")
private Customer customer;
(and the same goes for productId
/product
).
You shouldn't reference other entities by their ID, but by a direct reference to the entity. Remove the customerId
field, it's useless. And do the same for productId
. If you want the customer ID of a sale, you just need to do this:
sale.getCustomer().getId()
widget['bg'] = '#000000'
or
widget['background'] = '#000000'
would also work as hex-valued colors are also accepted.
jQuery has some issues loading binary data using AJAX requests, as it does not yet implement some HTML5 XHR v2 capabilities, see this enhancement request and this discussion
Given that, you have one of two solutions:
First solution, abandon JQuery and use XMLHTTPRequest
Go with the native HTMLHTTPRequest, here is the code to do what you need
var req = new XMLHttpRequest();
req.open("GET", "/file.pdf", true);
req.responseType = "blob";
req.onload = function (event) {
var blob = req.response;
console.log(blob.size);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="Dossier_" + new Date() + ".pdf";
link.click();
};
req.send();
Second solution, use the jquery-ajax-native plugin
The plugin can be found here and can be used to the XHR V2 capabilities missing in JQuery, here is a sample code how to use it
$.ajax({
dataType: 'native',
url: "/file.pdf",
xhrFields: {
responseType: 'blob'
},
success: function(blob){
console.log(blob.size);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="Dossier_" + new Date() + ".pdf";
link.click();
}
});
To work around this problem, use SQL statements to make the changes to the metadata structure of a table.
This problem occurs when "Prevent saving changes that require table re-creation" option is enabled.
Source: Error message when you try to save a table in SQL Server 2008: "Saving changes is not permitted"
You can get it by XMLHttpRequest.responseText
in XMLHttpRequest.onreadystatechange
when XMLHttpRequest.readyState
equals to XMLHttpRequest.DONE
.
Here's an example (not compatible with IE6/7).
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);
For better crossbrowser compatibility, not only with IE6/7, but also to cover some browser-specific memory leaks or bugs, and also for less verbosity with firing ajaxical requests, you could use jQuery.
$.get('http://example.com', function(responseText) {
alert(responseText);
});
Note that you've to take the Same origin policy for JavaScript into account when not running at localhost. You may want to consider to create a proxy script at your domain.
It depends which one to chose is based on the requirement
Handler is mostly used to switch from other thread to main thread, Handler is attached to a looper on which it post its runnable task in queue. So If you are already in other thread and switch to main thread then you need handle instead of async task or other thread
If Handler created in other than main thread which is not a looper is will not give error as handle is created the thread, that thread need to be made a lopper
AsyncTask is used to execute code for few seconds which run on background thread and gives its result to main thread ** *AsyncTask Limitations 1. Async Task is not attached to life cycle of activity and it keeps run even if its activity destroyed whereas loader doesn't have this limitation 2. All Async Tasks share the same background thread for execution which also impact the app performance
Thread is used in app for background work also but it doesn't have any call back on main thread. If requirement suits some threads instead of one thread and which need to give task many times then thread pool executor is better option.Eg Requirement of Image loading from multiple url like glide.
For simple things, I just use the XmlDocument/XmlNode/XmlAttribute classes and XmlDocument DOM found in System.XML.
It generates the XML for me, I just need to link a few items together.
However, on larger things, I use XML serialization.
Here's a simple way to test it:
public class OperatorTest {
public static void main(String[] args) {
boolean a = false;
a &= b();
}
private static boolean b() {
System.out.println("b() was called");
return true;
}
}
The output is b() was called
, therefore the right-hand operand is evaluated.
So, as already mentioned by others, a &= b
is the same as a = a & b
.
Let PowerShell analyze and decide the data type. It internally uses a 'Variant' for this.
And generally it does a good job...
param($x)
$iTunes = New-Object -ComObject iTunes.Application
if ($iTunes.playerstate -eq 1)
{
$iTunes.PlayerPosition = $iTunes.PlayerPosition + $x
}
Or if you need to pass multiple parameters:
param($x1, $x2)
$iTunes = New-Object -ComObject iTunes.Application
if ($iTunes.playerstate -eq 1)
{
$iTunes.PlayerPosition = $iTunes.PlayerPosition + $x1
$iTunes.<AnyProperty> = $x2
}
It should be:
cursor.execute ("""
UPDATE tblTableName
SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s
WHERE Server=%s
""", (Year, Month, Day, Hour, Minute, ServerID))
You can also do it with basic string manipulation,
cursor.execute ("UPDATE tblTableName SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s WHERE Server='%s' " % (Year, Month, Day, Hour, Minute, ServerID))
but this way is discouraged because it leaves you open for SQL Injection. As it's so easy (and similar) to do it the right waytm. Do it correctly.
The only thing you should be careful, is that some database backends don't follow the same convention for string replacement (SQLite comes to mind).
you could use ts-node-dev
It restarts target node process when any of required files changes (as standard node-dev) but shares Typescript compilation process between restarts.
Install
yarn add ts-node-dev --dev
and your package.json could be like this
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"tsc": "tsc",
"dev": "ts-node-dev --respawn --transpileOnly ./src/index.ts",
"prod": "tsc && node ./build/index.js"
}
The assembly was introduced with .NET 3.5 and is in the GAC.
Simply add a .NET reference to your project.
Project -> Right Click References
-> Select .NET
tab -> System.Web.Extensions
If it is not there, you need to install .NET 3.5 or 4.0.
cleanText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
Distilled from this website (web.achive).
This regex looks for <
, an optional slash /
, one or more characters that are not >
, then either >
or $
(the end of the line)
Examples:
'<div>Hello</div>' ==> 'Hello'
^^^^^ ^^^^^^
'Unterminated Tag <b' ==> 'Unterminated Tag '
^^
But it is not bulletproof:
'If you are < 13 you cannot register' ==> 'If you are '
^^^^^^^^^^^^^^^^^^^^^^^^
'<div data="score > 42">Hello</div>' ==> ' 42">Hello'
^^^^^^^^^^^^^^^^^^ ^^^^^^
If someone is trying to break your application, this regex will not protect you. It should only be used if you already know the format of your input. As other knowledgable and mostly sane people have pointed out, to safely strip tags, you must use a parser.
If you do not have acccess to a convenient parser like the DOM, and you cannot trust your input to be in the right format, you may be better off using a package like sanitize-html, and also other sanitizers are available.
My Issue got resolved by adding the Exception Handler to handle "Cannot redirect after HTTP headers have been sent". this Error as shown below code
catch (System.Threading.ThreadAbortException)
{
// To Handle HTTP Exception "Cannot redirect after HTTP headers have been sent".
}
catch (Exception e)
{//Here you can put your context.response.redirect("page.aspx");}
Can you try this, readfile
need the full file path.
$filename='/pdf/jobs/pdffile.pdf';
$url_download = BASE_URL . RELATIVE_PATH . $filename;
//header("Content-type:application/pdf");
header("Content-type: application/octet-stream");
header("Content-Disposition:inline;filename='".basename($filename)."'");
header('Content-Length: ' . filesize($filename));
header("Cache-control: private"); //use this to open files directly
readfile($filename);
The only property corresponding in WPF to the
Winforms property: TextBox.Multiline = true
is the WPF property: TextBox.AcceptsReturn = true
.
<TextBox AcceptsReturn="True" ...... />
All other settings, such as VerticalAlignement
, WordWrap
etc., only control how the TextBox interacts in the UI but do not affect the Multiline
behaviour.
It's very tempting to want to "fix" this and force a UI update, but the best fix is to do this on a background thread and not tie up the UI thread, so that it can still respond to events.
I had the same problem on CentOS 5.5
In addition to installing unixODBC-devel I also had to install gcc-c++
yum install gcc-c++
To read messages you should use:
kafka-console-consumer.sh --bootstrap-server kafka1:9092,kafka2:9092,kafka3:9092 --topic messages --from-beginning
--bootstrap-server
is required attribute.
You can use only single kafka1:9020
node.
I was using pgAdmin to create my tables and while I was not using reserved words, the generated table had a quote in the name and a couple of columns had quotes in them. Here is an example of the generated SQL.
CREATE TABLE public."Test"
(
id serial NOT NULL,
data text NOT NULL,
updater character varying(50) NOT NULL,
"updateDt" time with time zone NOT NULL,
CONSTRAINT test_pk PRIMARY KEY (id)
)
TABLESPACE pg_default;
ALTER TABLE public."Test"
OWNER to svc_newnews_app;
All of these quotes were inserted at "random". I just needed to drop and re-create the table again without the quotes.
Tested on pgAdmin 4.26
"Segmentation fault" means that you tried to access memory that you do not have access to.
The first problem is with your arguments of main
. The main
function should be int main(int argc, char *argv[])
, and you should check that argc
is at least 2 before accessing argv[1]
.
Also, since you're passing in a float
to printf
(which, by the way, gets converted to a double
when passing to printf
), you should use the %f
format specifier. The %s
format specifier is for strings ('\0'
-terminated character arrays).
$("#div_element").load('script.php');
demo: http://sandbox.phpcode.eu/g/2ecbe/3
whole code:
<div id="submit">ajax</div>
<div id="div_element"></div>
<script>
$('#submit').click(function(event){
$("#div_element").load('script.php?html=some_arguments');
});
</script>
Add a parameter of type UriComponentsBuilder
to your controller method. Spring will give you an instance that's preconfigured with the URI for the current request, and you can then customize it (such as by using MvcUriComponentsBuilder.relativeTo
to point at a different controller using the same prefix).
For extra themes, including making VS 2012 look like VS 2010 see:
http://visualstudiogallery.msdn.microsoft.com/366ad100-0003-4c9a-81a8-337d4e7ace05
Google fix this mistake with the build tools version: 23.0.3 Now zipalign is packaged properly, and everything works fine.
AndroidX is the open-source project that the Android team uses to develop, test, package, version and release libraries within Jetpack.
After hours of struggling, I solved it by including the following within app/build.gradle:
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
Put these flags in your gradle.properties
android.enableJetifier=true
android.useAndroidX=true
Changes in gradle:
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.1.0-alpha04'
When migrating on Android studio, the app/gradle file is automatically updated with the correction library impleemntations from the standard library
Refer to: https://developer.android.com/jetpack/androidx/migrate
Why don't you just right click on the table and then properties -> Storage and it would tell you the row count. You can use the below for row count in a view
SELECT SUM (row_count)
FROM sys.dm_db_partition_stats
WHERE object_id=OBJECT_ID('Transactions')
AND (index_id=0 or index_id=1)`
First
EXEC sp_fkeys 'Table', 'Schema'
Then use NimbleText to play with your results
One way would be to make a list of lists, with each sub-list in the new list containing a word and a count:
list1 = [] #this is your original list of words
list2 = [] #this is a new list
for word in list1:
if word in list2:
list2.index(word)[1] += 1
else:
list2.append([word,0])
Or, more efficiently:
for word in list1:
try:
list2.index(word)[1] += 1
except:
list2.append([word,0])
This would be less efficient than using a dictionary, but it uses more basic concepts.
Oracle 9i+ (maybe 8i too) has FIRST/LAST aggregate functions, that make computation over groups of rows according to row's rank in group. Assuming all rows as one group, you'll get what you want without subqueries:
SELECT
max(MEMBSHIP_ID)
keep (
dense_rank first
order by paym_date desc NULLS LAST
) as LATEST_MEMBER_ID
FROM user_payment
WHERE user_id=1
I spent half a day searching for answers to an identical "Illegal mix of collations" error with conflicts between utf8_unicode_ci and utf8_general_ci.
I found that some columns in my database were not specifically collated utf8_unicode_ci. It seems mysql implicitly collated these columns utf8_general_ci.
Specifically, running a 'SHOW CREATE TABLE table1' query outputted something like the following:
| table1 | CREATE TABLE `table1` (
`id` int(11) NOT NULL,
`col1` varchar(4) CHARACTER SET utf8 NOT NULL,
`col2` int(11) NOT NULL,
PRIMARY KEY (`col1`,`col2`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci |
Note the line 'col1' varchar(4) CHARACTER SET utf8 NOT NULL does not have a collation specified. I then ran the following query:
ALTER TABLE table1 CHANGE col1 col1 VARCHAR(4) CHARACTER SET utf8
COLLATE utf8_unicode_ci NOT NULL;
This solved my "Illegal mix of collations" error. Hope this might help someone else out there.
If you want the second highest number you can use
=LARGE(E4:E9;2)
although that doesn't account for duplicates so you could get the same result as the Max
If you want the largest number that is smaller than the maximum number you can use this version
=LARGE(E4:E9;COUNTIF(E4:E9;MAX(E4:E9))+1)
No it is not possible, hence your runtime error.
But you can assign an instance of a derived class to a variable of base class type.
I'd simply say that it was hyphenated.
1.3.1 fixed it.
Just update your extension and you should be good to go
Use assets like a filesystem to dump any kind of files. And use res to store what it is made for, layouts, images, values.
onMessageReceived(RemoteMessage remoteMessage) method called based on the following cases.
{
"to": "device token list",
"notification": {
"body": "Body of Your Notification",
"title": "Title of Your Notification"
},
"data": {
"body": "Body of Your Notification in Data",
"title": "Title of Your Notification in Title",
"key_1": "Value for key_1",
"image_url": "www.abc.com/xyz.jpeg",
"key_2": "Value for key_2"
}
}
onMessageReceived(RemoteMessage remoteMessage) called, shows LargeIcon and BigPicture in the notification bar. We can read the content from both notification and data block
onMessageReceived(RemoteMessage remoteMessage) not called, system tray will receive the message and read body and title from notification block and shows default message and title in the notification bar.
In this case, removing notification blocks from json
{
"to": "device token list",
"data": {
"body": "Body of Your Notification in Data",
"title": "Title of Your Notification in Title",
"key_1": "Value for key_1",
"image_url": "www.abc.com/xyz.jpeg",
"key_2": "Value for key_2"
}
}
Solution for calling onMessageReceived()
onMessageReceived(RemoteMessage remoteMessage) called, shows LargeIcon and BigPicture in the notification bar. We can read the content from both notification and data block
onMessageReceived(RemoteMessage remoteMessage) called, system tray will not receive the message because of notification key is not in the response. Shows LargeIcon and BigPicture in the notification bar
Code
private void sendNotification(Bitmap bitmap, String title, String
message, PendingIntent resultPendingIntent) {
NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle();
style.bigPicture(bitmap);
Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = mContext.getString(R.string.default_notification_channel_id);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "channel_name", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
}
Bitmap iconLarge = BitmapFactory.decodeResource(mContext.getResources(),
R.drawable.mdmlogo);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.mdmlogo)
.setContentTitle(title)
.setAutoCancel(true)
.setSound(defaultSound)
.setContentText(message)
.setContentIntent(resultPendingIntent)
.setStyle(style)
.setLargeIcon(iconLarge)
.setWhen(System.currentTimeMillis())
.setPriority(Notification.PRIORITY_MAX)
.setChannelId(NOTIFICATION_CHANNEL_ID);
notificationManager.notify(1, notificationBuilder.build());
}
Reference Link:
https://firebase.google.com/docs/cloud-messaging/android/receive
Range.Rows, Range.Columns and Range.Cells are Excel.Range objects, according to the VBA Type() functions:
?TypeName(Selection.rows) RangeHowever, that's not the whole story: those returned objects are extended types that inherit every property and method from Excel::Range - but .Columns and .Rows have a special For... Each iterator, and a special .Count property that aren't quite the same as the parent Range object's iterator and count.
So .Cells is iterated and counted as a collection of single-cell ranges, just like the default iterator of the parent range.
But .Columns is iterated and counted as a collection of vertical subranges, each of them a single column wide;
...And .Rows is iterated and counted as a collection of horizontal subranges, each of them a single row high.
The easiest way to understand this is to step through this code and watch what's selected:
Public Sub Test()Enjoy. And try it with a couple of merged cells in there, just to see how odd merged ranges can be.
Dim SubRange As Range Dim ParentRange As Range
Set ParentRange = ActiveSheet.Range("B2:E5")
For Each SubRange In ParentRange.Cells SubRange.Select Next
For Each SubRange In ParentRange.Rows SubRange.Select Next
For Each SubRange In ParentRange.Columns SubRange.Select Next
For Each SubRange In ParentRange SubRange.Select Next
End Sub
FailedDev's answer is good, but can be improved. If you want to preserve the ascii equivalents, you need to normalize first:
String subjectString = "öäü";
subjectString = Normalizer.normalize(subjectString, Normalizer.Form.NFD);
String resultString = subjectString.replaceAll("[^\\x00-\\x7F]", "");
=> will produce "oau"
That way, characters like "öäü" will be mapped to "oau", which at least preserves some information. Without normalization, the resulting String will be blank.
It can't be done directly, but you can emulate the same thing using function pointers and explicitly passing the "this" parameter:
typedef struct client_t client_t, *pno;
struct client_t
{
pid_t pid;
char password[TAM_MAX]; // -> 50 chars
pno next;
pno (*AddClient)(client_t *);
};
pno client_t_AddClient(client_t *self) { /* code */ }
int main()
{
client_t client;
client.AddClient = client_t_AddClient; // probably really done in some init fn
//code ..
client.AddClient(&client);
}
It turns out that doing this, however, doesn't really buy you an awful lot. As such, you won't see many C APIs implemented in this style, since you may as well just call your external function and pass the instance.
Here is what made the error disappear for me:
Close eclipse, open up a terminal window and run:
$ mvn clean eclipse:clean eclipse:eclipse
Are you using Maven? If so,
To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.
And then clean
Edit 1:
If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.
Edit 2:
You can also try going into the folder where you have all your projects and delete the .metadata
for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.
i think unlink & link php versions are not enough because we are often using php with apache(httpd), so need to update httpd.conf after switch php version.
i have write shell script for disable/enable php_module
automatically inside httpd.conf
, look at line 46 to line 54 https://github.com/dangquangthai/switch-php-version-on-mac-sierra/blob/master/switch-php#L46
Follow my steps:
1) Check installed php versions by brew, for sure everything good
> brew list | grep php
#output
php56
php56-intl
php56-mcrypt
php71
php71-intl
php71-mcrypt
2) Run script
> switch-php 71 # or switch-php 56
#output
PHP version [71] found
Switching from [php56] to [php71] ...
Unlink php56 ... [OK] and Link php71 ... [OK]
Updating Apache2.4 Configuration /usr/local/etc/httpd/httpd.conf ... [OK]
Restarting Apache2.4 ... [OK]
PHP 7.1.11 (cli) (built: Nov 3 2017 08:48:02) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies
3) Finally, when your got above message, check httpd.conf
, in my laptop:
vi /usr/local/etc/httpd/httpd.conf
You can see near by LoadModule lines
LoadModule php7_module /usr/local/Cellar/php71/7.1.11_22/libexec/apache2/libphp7.so
#LoadModule php5_module /usr/local/Cellar/php56/5.6.32_8/libexec/apache2/libphp5.so
4) open httpd://localhost/info.php
i hope it helpful
Using Pygrok, you can define abstracted extensions to the Regular Expression syntax.
The custom patterns can be included in your regex in the format %{PATTERN_NAME}
.
You can also create a label for that pattern, by separating with a colon: %s{PATTERN_NAME:matched_string}
. If the pattern matches, the value will be returned as part of the resulting dictionary (e.g. result.get('matched_string')
)
For example:
from pygrok import Grok
input_string = 'monkey 2010-07-10 love banana'
date_pattern = '%{YEAR:year}-%{MONTHNUM:month}-%{MONTHDAY:day}'
grok = Grok(date_pattern)
print(grok.match(input_string))
The resulting value will be a dictionary:
{'month': '07', 'day': '10', 'year': '2010'}
If the date_pattern does not exist in the input_string, the return value will be None
. By contrast, if your pattern does not have any labels, it will return an empty dictionary {}
References:
I also got same error, compiling with -D flag fixed it, Try this:
g++ -Dstd=c++11
To retrieve environment variables in Node.JS you can use process.env.VARIABLE_NAME, but don't forget that assigning a property on process.env will implicitly convert the value to a string.
Even if your .env file defines a variable like SHOULD_SEND=false or SHOULD_SEND=0, the values will be converted to strings (“false” and “0” respectively) and not interpreted as booleans.
if (process.env.SHOULD_SEND) {
mailer.send();
} else {
console.log("this won't be reached with values like false and 0");
}
Instead, you should make explicit checks. I’ve found depending on the environment name goes a long way.
db.connect({
debug: process.env.NODE_ENV === 'development'
});
Just add the seen attribute to redirect tag as below:
<redirect include-view-params="true">
<view-param>
<name>id</name>
<value>#{myBean.id}</value>
</view-param>
</redirect>
DECLARE @DeleteProcCommand NVARCHAR(500)
DECLARE Syntax_Cursor CURSOR
FOR
SELECT 'DROP PROCEDURE ' + p.NAME
FROM sys.procedures p
OPEN Syntax_Cursor
FETCH NEXT FROM Syntax_Cursor
INTO @DeleteProcCommand
WHILE (@@FETCH_STATUS = 0)
BEGIN
EXEC (@DeleteProcCommand)
FETCH NEXT FROM Syntax_Cursor
INTO @DeleteProcCommand
END
CLOSE Syntax_Cursor
DEALLOCATE Syntax_Cursor
1 . If you are unsure about an exception, check the API:
java.lang.Object extended by java.lang.Throwable extended by java.lang.Exception extended by java.lang.RuntimeException //<-NumberFormatException is a RuntimeException extended by java.lang.IllegalArgumentException extended by java.lang.NumberFormatException
2 . Yes, and every exception that extends it.
3 . There is no need to catch and throw the same exception. You can show a new File Dialog in this case.
4 . FileNotFoundException is already a checked exception.
5 . If it is expected that the method calling someMethod
to catch the exception, the latter can be thrown. It just "passes the ball". An example of it usage would be if you want to throw it in your own private methods, and handle the exception in your public method instead.
A good reading is the Oracle doc itself: http://download.oracle.com/javase/tutorial/essential/exceptions/runtime.html
Why did the designers decide to force a method to specify all uncaught checked exceptions that can be thrown within its scope? Any Exception that can be thrown by a method is part of the method's public programming interface. Those who call a method must know about the exceptions that a method can throw so that they can decide what to do about them. These exceptions are as much a part of that method's programming interface as its parameters and return value.
The next question might be: "If it's so good to document a method's API, including the exceptions it can throw, why not specify runtime exceptions too?" Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.
There's also an important bit of information in the Java Language Specification:
The checked exception classes named in the throws clause are part of the contract between the implementor and user of the method or constructor.
The bottom line IMHO is that you can catch any RuntimeException
, but you are not required to and, in fact the implementation is not required to maintain the same non-checked exceptions thrown, as those are not part of the contract.
It's not a Visual Studio add in, but it is a tool that I couldn't use Visual Studio without it...
ClipX - it's works with the normal clipboard, but saves the entries to a searchable list, you can use copy and paste as ususal, but you can hit CTRL+SHIFT+V and the list pops up. It works with images, text, etc. It even persists after you reboot your computer.
empty
is an operator:
The
empty
operator is a prefix operation that can be used to determine whether a value is null or empty.
<c:if test="${empty myObject.featuresList}">
I have stumbled upon this problem for one hour. After an hour, I tried debugging and this helped:
$('.list').on('click', 'span', (e) => {
$(e.target).parent().remove();
});
HTML:
<ul class="list">
<li class="task">some text<span>X</span></li>
<li class="task">some text<span>X</span></li>
<li class="task">some text<span>X</span></li>
<li class="task">some text<span>X</span></li>
<li class="task">some text<span>X</span></li>
</ul>
Yes. In fact you should. If you're wondering if it creates a segmentation fault, it doesn't.
Check if you do not have declared the method getAll() in the model. That causes the controller to think that you are calling a non-static method.
I agree with @arcy, the problem is on client side, on my case it was because of nginx, let me elaborate
I am using nginx as the frontend (so I can distribute load, ssl, etc ...) and using proxy_pass http://127.0.0.1:8080
to forward the appropiate requests to tomcat.
There is a default value for the nginx variable proxy_read_timeout
of 60s that should be enough, but on some peak moments my setup would error with the java.io.IOException: Broken pipe changing the value will help until the root cause (60s should be enough) can be fixed.
NOTE: I made a new answer so I could expand a bit more with my case (it was the only mention I found about this error on internet after looking quite a lot)
I'm pretty sure C-style casting syntax works in Objective C, so try that, too:
int myInt = (int) myFloat;
It might silence a compiler warning, at least.
The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity
changes.
Instead you could try the following approach. Change your markup to the following:
<div ng-controller="myAppController" style="text-align:center">
<p style="font-size:28px;">Enter Quantity:
<input type="text" ng-model="quantity"/>
</p>
<button ng-click="calculateQuantity()">Calculate</button>
<h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>
Next, update your controller:
myAppModule.controller('myAppController', function($scope,calculateService) {
$scope.quantity=1;
$scope.quantityResult = 0;
$scope.calculateQuantity = function() {
$scope.quantityResult = calculateService.calculate($scope.quantity, 10);
};
});
Here's a JSBin example that demonstrates the above approach.
The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity
changes.
This would involve updating the template to add an ng-change
on the input, and an ng-if
on the result:
<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>
and
<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>
In the controller add:
$scope.showQuantityResult = false;
$scope.calculateQuantity = function() {
$scope.quantityResult = calculateService.calculate($scope.quantity, 10);
$scope.showQuantityResult = true;
};
$scope.hideQuantityResult = function() {
$scope.showQuantityResult = false;
};
These updates can be seen in this JSBin demo.
You have to dot source
them:
. .\build_funtions.ps1
. .\build_builddefs.ps1
Note the extra .
This heyscriptingguy
article should be of help - How to Reuse Windows PowerShell Functions in Scripts
CSS only solution
HTML
<div class="container">
<div class="h_iframe">
<iframe src="//www.youtube.com/embed/9KunP3sZyI0" frameborder="0" allowfullscreen></iframe>
</div>
</div>
CSS
html,body {
height:100%;
}
.h_iframe iframe {
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
}
Another demo here with HTML page in iframe
A small javascript snippet to mimic the blink , no need of css even
<span id="lastDateBlinker">
Last Date for Participation : 30th July 2014
</span>
<script type="text/javascript">
function blinkLastDateSpan() {
if ($("#lastDateBlinker").css("visibility").toUpperCase() == "HIDDEN") {
$("#lastDateBlinker").css("visibility", "visible");
setTimeout(blinkLastDateSpan, 200);
} else {
$("#lastDateBlinker").css("visibility", "hidden");
setTimeout(blinkLastDateSpan, 200);
}
}
blinkLastDateSpan();
</script>
Simple and easy. You can do this from the URI just like below!
public void getContents(Uri uri)
{
Cursor vidCursor = getActivity.getContentResolver().query(uri, null, null,
null, null);
if (vidCursor.moveToFirst())
{
int column_index =
vidCursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
Uri filePathUri = Uri.parse(vidCursor .getString(column_index));
String video_name = filePathUri.getLastPathSegment().toString();
String file_path=filePathUri.getPath();
Log.i("TAG", video_name + "\b" file_path);
}
}
More info about why it wasn't working for me in case it helps future people:
The reason why it wasn't working is that {% include %} in django doesn't like special characters like fancy apostrophe. The template data I was trying to include was pasted from word. I had to manually remove all of these special characters and then it included successfully.
UPDATE: The code below has a bug, described here. The test program below works, but if you were to use DayOfWeek.Mon (for example) before DayOfWeek itself, it would fail because DayOfWeek has not been initialized (use of an inner object does not cause an outer object to be initialized). You can still use this code if you do something like val enums = Seq( DayOfWeek )
in your main class, forcing initialization of your enums, or you can use chaotic3quilibrium's modifications. Looking forward to a macro-based enum!
If you want
then the following may be of interest. Feedback welcome.
In this implementation there are abstract Enum and EnumVal base classes, which you extend. We'll see those classes in a minute, but first, here's how you would define an enum:
object DayOfWeek extends Enum {
sealed abstract class Val extends EnumVal
case object Mon extends Val; Mon()
case object Tue extends Val; Tue()
case object Wed extends Val; Wed()
case object Thu extends Val; Thu()
case object Fri extends Val; Fri()
case object Sat extends Val; Sat()
case object Sun extends Val; Sun()
}
Note that you have to use each enum value (call its apply method) to bring it to life. [I wish inner objects weren't lazy unless I specifically ask for them to be. I think.]
We could of course add methods/data to DayOfWeek, Val, or the individual case objects if we so desired.
And here's how you would use such an enum:
object DayOfWeekTest extends App {
// To get a map from Int id to enum:
println( DayOfWeek.valuesById )
// To get a map from String name to enum:
println( DayOfWeek.valuesByName )
// To iterate through a list of the enum values in definition order,
// which can be made different from ID order, and get their IDs and names:
DayOfWeek.values foreach { v => println( v.id + " = " + v ) }
// To sort by ID or name:
println( DayOfWeek.values.sorted mkString ", " )
println( DayOfWeek.values.sortBy(_.toString) mkString ", " )
// To look up enum values by name:
println( DayOfWeek("Tue") ) // Some[DayOfWeek.Val]
println( DayOfWeek("Xyz") ) // None
// To look up enum values by id:
println( DayOfWeek(3) ) // Some[DayOfWeek.Val]
println( DayOfWeek(9) ) // None
import DayOfWeek._
// To compare enums as ordinals:
println( Tue < Fri )
// Warnings about non-exhaustive pattern matches:
def aufDeutsch( day: DayOfWeek.Val ) = day match {
case Mon => "Montag"
case Tue => "Dienstag"
case Wed => "Mittwoch"
case Thu => "Donnerstag"
case Fri => "Freitag"
// Commenting these out causes compiler warning: "match is not exhaustive!"
// case Sat => "Samstag"
// case Sun => "Sonntag"
}
}
Here's what you get when you compile it:
DayOfWeekTest.scala:31: warning: match is not exhaustive!
missing combination Sat
missing combination Sun
def aufDeutsch( day: DayOfWeek.Val ) = day match {
^
one warning found
You can replace "day match" with "( day: @unchecked ) match" where you don't want such warnings, or simply include a catch-all case at the end.
When you run the above program, you get this output:
Map(0 -> Mon, 5 -> Sat, 1 -> Tue, 6 -> Sun, 2 -> Wed, 3 -> Thu, 4 -> Fri)
Map(Thu -> Thu, Sat -> Sat, Tue -> Tue, Sun -> Sun, Mon -> Mon, Wed -> Wed, Fri -> Fri)
0 = Mon
1 = Tue
2 = Wed
3 = Thu
4 = Fri
5 = Sat
6 = Sun
Mon, Tue, Wed, Thu, Fri, Sat, Sun
Fri, Mon, Sat, Sun, Thu, Tue, Wed
Some(Tue)
None
Some(Thu)
None
true
Note that since the List and Maps are immutable, you can easily remove elements to create subsets, without breaking the enum itself.
Here is the Enum class itself (and EnumVal within it):
abstract class Enum {
type Val <: EnumVal
protected var nextId: Int = 0
private var values_ = List[Val]()
private var valuesById_ = Map[Int ,Val]()
private var valuesByName_ = Map[String,Val]()
def values = values_
def valuesById = valuesById_
def valuesByName = valuesByName_
def apply( id : Int ) = valuesById .get(id ) // Some|None
def apply( name: String ) = valuesByName.get(name) // Some|None
// Base class for enum values; it registers the value with the Enum.
protected abstract class EnumVal extends Ordered[Val] {
val theVal = this.asInstanceOf[Val] // only extend EnumVal to Val
val id = nextId
def bumpId { nextId += 1 }
def compare( that:Val ) = this.id - that.id
def apply() {
if ( valuesById_.get(id) != None )
throw new Exception( "cannot init " + this + " enum value twice" )
bumpId
values_ ++= List(theVal)
valuesById_ += ( id -> theVal )
valuesByName_ += ( toString -> theVal )
}
}
}
And here is a more advanced use of it which controls the IDs and adds data/methods to the Val abstraction and to the enum itself:
object DayOfWeek extends Enum {
sealed abstract class Val( val isWeekday:Boolean = true ) extends EnumVal {
def isWeekend = !isWeekday
val abbrev = toString take 3
}
case object Monday extends Val; Monday()
case object Tuesday extends Val; Tuesday()
case object Wednesday extends Val; Wednesday()
case object Thursday extends Val; Thursday()
case object Friday extends Val; Friday()
nextId = -2
case object Saturday extends Val(false); Saturday()
case object Sunday extends Val(false); Sunday()
val (weekDays,weekendDays) = values partition (_.isWeekday)
}
You could use the bootstrap grid system :
<div class="col-md-6 form-group">
<label for="textbox1">Label1</label>
<input class="form-control" id="textbox1" type="text"/>
</div>
<div class="col-md-6 form-group">
<label for="textbox2">Label2</label>
<input class="form-control" id="textbox2" type="text"/>
</div>
<span class="clearfix">
http://getbootstrap.com/css/#grid
Is that what you want to achieve?
@mani's Original answer is all you want, but if you'd also like to read it in official way, here's
https://router.vuejs.org/guide/essentials/history-mode.html#caveat
I spent many sad days trying to come up with a way to do this for C++17, which deprecated code_cvt
facets, and this is the best I was able to come up with by combining code from a few different sources:
setlocale( LC_ALL, "en_US.UTF-8" ); //Invoked in main()
std::string wideToMultiByte( std::wstring const & wideString )
{
std::string ret;
std::string buff( MB_CUR_MAX, '\0' );
for ( wchar_t const & wc : wideString )
{
int mbCharLen = std::wctomb( &buff[ 0 ], wc );
if ( mbCharLen < 1 ) { break; }
for ( int i = 0; i < mbCharLen; ++i )
{
ret += buff[ i ];
}
}
return ret;
}
std::wstring multiByteToWide( std::string const & multiByteString )
{
std::wstring ws( multiByteString.size(), L' ' );
ws.resize(
std::mbstowcs( &ws[ 0 ],
multiByteString.c_str(),
multiByteString.size() ) );
return ws;
}
I tested this code on Windows 10, and at least for my purposes, it seems to work fine. Please don't lynch me if this doesn't consider some crazy edge cases that you might need to handle, I'm sure someone with more experience can improve on this! :-)
Also, credit where it's due:
Each column has like()
method, which can be used in query.filter()
. Given a search string, add a %
character on either side to search as a substring in both directions.
tag = request.form["tag"]
search = "%{}%".format(tag)
posts = Post.query.filter(Post.tags.like(search)).all()
The pure python solution for this problem under Linux to get the MAC for a specific local interface, originally posted as a comment by vishnubob and improved by on Ben Mackey in this activestate recipe
#!/usr/bin/python
import fcntl, socket, struct
def getHwAddr(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', ifname[:15]))
return ':'.join(['%02x' % ord(char) for char in info[18:24]])
print getHwAddr('eth0')
This is the Python 3 compatible code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import fcntl
import socket
import struct
def getHwAddr(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', bytes(ifname, 'utf-8')[:15]))
return ':'.join('%02x' % b for b in info[18:24])
def main():
print(getHwAddr('enp0s8'))
if __name__ == "__main__":
main()
In addition to @Khanetor's answer, for those who are working with cross-origin requests: credentials: 'include'
Sample JSON fetch request:
fetch(url, {
method: 'GET',
credentials: 'include'
})
.then((response) => response.json())
.then((json) => {
console.log('Gotcha');
}).catch((err) => {
console.log(err);
});
https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials
Each field constraint should be handled by a distinct validator annotation, or in other words it's not suggested practice to have one field's validation annotation checking against other fields; cross-field validation should be done at the class level. Additionally, the JSR-303 Section 2.2 preferred way to express multiple validations of the same type is via a list of annotations. This allows the error message to be specified per match.
For example, validating a common form:
@FieldMatch.List({
@FieldMatch(first = "password", second = "confirmPassword", message = "The password fields must match"),
@FieldMatch(first = "email", second = "confirmEmail", message = "The email fields must match")
})
public class UserRegistrationForm {
@NotNull
@Size(min=8, max=25)
private String password;
@NotNull
@Size(min=8, max=25)
private String confirmPassword;
@NotNull
@Email
private String email;
@NotNull
@Email
private String confirmEmail;
}
The Annotation:
package constraints;
import constraints.impl.FieldMatchValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
/**
* Validation annotation to validate that 2 fields have the same value.
* An array of fields and their matching confirmation fields can be supplied.
*
* Example, compare 1 pair of fields:
* @FieldMatch(first = "password", second = "confirmPassword", message = "The password fields must match")
*
* Example, compare more than 1 pair of fields:
* @FieldMatch.List({
* @FieldMatch(first = "password", second = "confirmPassword", message = "The password fields must match"),
* @FieldMatch(first = "email", second = "confirmEmail", message = "The email fields must match")})
*/
@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = FieldMatchValidator.class)
@Documented
public @interface FieldMatch
{
String message() default "{constraints.fieldmatch}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
/**
* @return The first field
*/
String first();
/**
* @return The second field
*/
String second();
/**
* Defines several <code>@FieldMatch</code> annotations on the same element
*
* @see FieldMatch
*/
@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Documented
@interface List
{
FieldMatch[] value();
}
}
The Validator:
package constraints.impl;
import constraints.FieldMatch;
import org.apache.commons.beanutils.BeanUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object>
{
private String firstFieldName;
private String secondFieldName;
@Override
public void initialize(final FieldMatch constraintAnnotation)
{
firstFieldName = constraintAnnotation.first();
secondFieldName = constraintAnnotation.second();
}
@Override
public boolean isValid(final Object value, final ConstraintValidatorContext context)
{
try
{
final Object firstObj = BeanUtils.getProperty(value, firstFieldName);
final Object secondObj = BeanUtils.getProperty(value, secondFieldName);
return firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);
}
catch (final Exception ignore)
{
// ignore
}
return true;
}
}
I recently ran into similar issues, and this is what worked for me.
If the variable is numeric, then a simple df$Var[df$Var == ""] <- NA
should suffice. But if the variable is a factor, then you need to convert it to the character first, then replace ""
cells with the value you want, and convert it back to factor. So case in point, your Sex
variable, I assume it would be a factor and if you want to replace the empty cell, I would do the following:
df$Var <- as.character(df$Var)
df$Var[df$Var==""] <- NA
df$Var <- as.factor(df$Var)
myLabel.setHorizontalAlignment(SwingConstants.CENTER);
myLabel.setVerticalAlignment(SwingConstants.CENTER);
If you cannot reconstruct the label for some reason, this is how you edit these properties of a pre-existent JLabel.
if it's too long for one page, use the longtable
package. and if it's too wide for the page, use p{width}
in place of l,r, or c for the column specifier. you can also go smaller than \small
, i.e. \footnotesize
and \tiny
. I would consult the setspace package for options on how to remove the double space, though it's probably \singlespace
or something like that.
I simply converted the varchar field that I wanted to convert into a new table (with a DateTime filed) to a DateTime compatible layout first and then SQL will do the conversion from varchar to DateTime without problems.
In the below (not my created table with those names !) I simply make the varchar field to be a DateTime lookalike if you want to:
update report1455062507424
set [Move Time] = substring([Move Time], 7, 4) + '-'+ substring([Move Time], 4, 2) + '-'+ substring([Move Time], 1, 2) + ' ' +
substring([Move Time], 12, 5)
You can go for identifying a list of elements with xPath:
//td[text() = ' Color Digest ']/following-sibling::td[1]
This will give you a list of two elements, than you can use the 2nd element as your intended one. For example:
List<WebElement> elements = driver.findElements(By.xpath("//td[text() = ' Color Digest ']/following-sibling::td[1]"))
Now, you can use the 2nd element as your intended element, which is elements.get(1)
Scope tag is always use to limit the transitive dependencies and availability of the jar at class path level.If we don't provide any scope then the default scope will work i.e. Compile .
Here is the list of valid timezones:
http://en.wikipedia.org/wiki/List_of_tz_database_time_zones
You can use
TIME_ZONE = 'Europe/Istanbul'
for UTC+02:00
You have not used float:left
command for your text.
Window Builder Pro is a great GUI Designer for eclipse and is now offered for free by google.
How to convert string to lowercase in Python?
Is there any way to convert an entire user inputted string from uppercase, or even part uppercase to lowercase?
E.g. Kilometers --> kilometers
The canonical Pythonic way of doing this is
>>> 'Kilometers'.lower()
'kilometers'
However, if the purpose is to do case insensitive matching, you should use case-folding:
>>> 'Kilometers'.casefold()
'kilometers'
Here's why:
>>> "Maße".casefold()
'masse'
>>> "Maße".lower()
'maße'
>>> "MASSE" == "Maße"
False
>>> "MASSE".lower() == "Maße".lower()
False
>>> "MASSE".casefold() == "Maße".casefold()
True
This is a str method in Python 3, but in Python 2, you'll want to look at the PyICU or py2casefold - several answers address this here.
Python 3 handles plain string literals as unicode:
>>> string = '????????'
>>> string
'????????'
>>> string.lower()
'????????'
In Python 2, the below, pasted into a shell, encodes the literal as a string of bytes, using utf-8
.
And lower
doesn't map any changes that bytes would be aware of, so we get the same string.
>>> string = '????????'
>>> string
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> string.lower()
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> print string.lower()
????????
In scripts, Python will object to non-ascii (as of Python 2.5, and warning in Python 2.4) bytes being in a string with no encoding given, since the intended coding would be ambiguous. For more on that, see the Unicode how-to in the docs and PEP 263
str
literalsSo we need a unicode
string to handle this conversion, accomplished easily with a unicode string literal, which disambiguates with a u
prefix (and note the u
prefix also works in Python 3):
>>> unicode_literal = u'????????'
>>> print(unicode_literal.lower())
????????
Note that the bytes are completely different from the str
bytes - the escape character is '\u'
followed by the 2-byte width, or 16 bit representation of these unicode
letters:
>>> unicode_literal
u'\u041a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> unicode_literal.lower()
u'\u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
Now if we only have it in the form of a str
, we need to convert it to unicode
. Python's Unicode type is a universal encoding format that has many advantages relative to most other encodings. We can either use the unicode
constructor or str.decode
method with the codec to convert the str
to unicode
:
>>> unicode_from_string = unicode(string, 'utf-8') # "encoding" unicode from string
>>> print(unicode_from_string.lower())
????????
>>> string_to_unicode = string.decode('utf-8')
>>> print(string_to_unicode.lower())
????????
>>> unicode_from_string == string_to_unicode == unicode_literal
True
Both methods convert to the unicode type - and same as the unicode_literal.
It is recommended that you always work with text in Unicode.
Software should only work with Unicode strings internally, converting to a particular encoding on output.
However, to get the lowercase back in type str
, encode the python string to utf-8
again:
>>> print string
????????
>>> string
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> string.decode('utf-8')
u'\u041a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> string.decode('utf-8').lower()
u'\u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> string.decode('utf-8').lower().encode('utf-8')
'\xd0\xba\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> print string.decode('utf-8').lower().encode('utf-8')
????????
So in Python 2, Unicode can encode into Python strings, and Python strings can decode into the Unicode type.
Try something like this:-
table {
width: 50%;
height: 50%;
border-spacing: 0;
position:absolute;
}
td {
border: 1px solid black;
}
#content {
position:absolute;
width:100%;
left:0px;
top:20px;
bottom:20px;
overflow: hidden;
}
If you've got the PowerShell-based git installation, you can use the Get-Command object to find git:
Get-Command git.exe | Select-Object -ExpandProperty Definition
To get the definition of the SQL codes, the easiest way is to use db2 cli!
at the unix or dos command prompt, just type
db2 "? SQL302"
this will give you the required explanation of the particular SQL code that you normally see in the java exception or your db2 sql output :)
hope this helped.
SQL Server requires subqueries that you SELECT FROM
or JOIN
to have an alias.
Add an alias to your subquery (in this case x
):
select COUNT(*) from
(
select m.Company_id
from Monitor as m
inner join Monitor_Request as mr on mr.Company_ID=m.Company_id
group by m.Company_id
having COUNT(m.Monitor_id)>=5) x
FYI, even if an exception is re-raised in the rescue
section, the ensure
block will be executed before the code execution continues to the next exception handler. For instance:
begin
raise "Error!!"
rescue
puts "test1"
raise # Reraise exception
ensure
puts "Ensure block"
end
As of Matplotlib 2.0, there is a reversed()
method for ListedColormap
and LinearSegmentedColorMap
objects, so you can just do
cmap_reversed = cmap.reversed()
Here is the documentation.
Without any iteration with the --line-buffered grep option:
your_command | grep --line-buffered "your search"
Real life exemple with a Symfony PHP Framework router debug command ouput, to grep all "api" related routes:
php bin/console d:r | grep --line-buffered "api"
Example about sleep doesn’t release lock and wait does
Here there are two classes :
Singleton : This is singleton class with two static methods getInstance() and getInstance(boolean isWait).
public class Main {
private static Singleton singletonA = null;
private static Singleton singletonB = null;
public static void main(String[] args) throws InterruptedException {
Thread threadA = new Thread() {
@Override
public void run() {
singletonA = Singleton.getInstance(true);
}
};
Thread threadB = new Thread() {
@Override
public void run() {
singletonB = Singleton.getInstance();
while (singletonA == null) {
System.out.println("SingletonA still null");
}
if (singletonA == singletonB) {
System.out.println("Both singleton are same");
} else {
System.out.println("Both singleton are not same");
}
}
};
threadA.start();
threadB.start();
}
}
and
public class Singleton {
private static Singleton _instance;
public static Singleton getInstance() {
if (_instance == null) {
synchronized (Singleton.class) {
if (_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
public static Singleton getInstance(boolean isWait) {
if (_instance == null) {
synchronized (Singleton.class) {
if (_instance == null) {
if (isWait) {
try {
// Singleton.class.wait(500);//Using wait
Thread.sleep(500);// Using Sleep
System.out.println("_instance :"
+ String.valueOf(_instance));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
_instance = new Singleton();
}
}
}
return _instance;
}
}
Now run this example you will get below output :
_instance :null
Both singleton are same
Here Singleton instances created by threadA and threadB are same. It means threadB is waiting outside until threadA release it’s lock.
Now change the Singleton.java by commenting Thread.sleep(500); method and uncommenting Singleton.class.wait(500); . Here because of Singleton.class.wait(500); method threadA will release all acquire locks and moves into the “Non Runnable” state, threadB will get change to enter in synchronized block.
Now run again :
SingletonA still null
SingletonA still null
SingletonA still null
_instance :com.omt.sleepwait.Singleton@10c042ab
SingletonA still null
SingletonA still null
SingletonA still null
Both singleton are not same
Here Singleton instances created by threadA and threadB are NOT same because of threadB got change to enter in synchronised block and after 500 milliseconds threadA started from it’s last position and created one more Singleton object.
See the answer at: http://omappedia.org/wiki/Android_eMMC_Booting#Modifying_.IMG_Files
First you need to "uncompress" userdata.img
with simg2img
, then you can mount it via the loop device.
MSYS has not been updated a long time, MSYS2 is more active, you can download from MSYS2, it has both mingw
and cygwin fork
package.
To install the MinGW-w64 toolchain (Reference):
pacman -Sy pacman
to update the package databasepacman -Syu
to update the package database and core system packagespacman -Su
to update the restpacman -S mingw-w64-i686-toolchain
pacman -S mingw-w64-x86_64-toolchain
make
, run pacman -S make
You can load your External JS files in Angular and you can load them directly instead of defining in index.html file.
component.ts:
ngOnInit() {
this.loadScripts();
}
loadScripts() {
const dynamicScripts = [
//scripts to be loaded
"assets/lib/js/hand-1.3.8.js",
"assets/lib/js/modernizr.jr.js",
"assets/lib/js/jquery-2.2.3.js",
"assets/lib/js/jquery-migrate-1.4.1.js",
"assets/js/jr.utils.js"
];
for (let i = 0; i < dynamicScripts.length; i++) {
const node = document.createElement('script');
node.src = dynamicScripts[i];
node.type = 'text/javascript';
node.async = false;
document.getElementById('scripts').appendChild(node);
}
}
component.html:
<div id="scripts">
</div>
You can also load styles similarly.
component.ts:
ngOnInit() {
this.loadStyles();
}
loadStyles() {
const dynamicStyles = [
//styles to be loaded
"assets/lib/css/ui.css",
"assets/lib/css/material-theme.css",
"assets/lib/css/custom-style.css"
];
for (let i = 0; i < dynamicStyles.length; i++) {
const node = document.createElement('link');
node.href = dynamicStyles[i];
node.rel = 'stylesheet';
document.getElementById('styles').appendChild(node);
}
}
component.html:
<div id="styles">
</div>
maybe this will help you out:
or this page:
www.scala-lang.org/node/6372
In addition to existing answers it is often desired to format the REST output (typically JSON and XML lacks indentation). Try this:
$ curl https://api.twitter.com/1/help/configuration.xml | xmllint --format -
$ curl https://api.twitter.com/1/help/configuration.json | python -mjson.tool
Tested on Ubuntu 11.0.4/11.10.
Another issue is the desired content type. Twitter uses .xml
/.json
extension, but more idiomatic REST would require Accept
header:
$ curl -H "Accept: application/json"
With text files, maybe the EOF is -1 when using BufferReader.read(), char by char. I made a test with BufferReader.readLine()!=null and it worked properly.
Use Javascript's setTimeout:
<body onload="setTimeout(function(){window.location = 'form2.html';}, 5000)">
I don't work with contiguous ranges all the time. My solution for non-contiguous ranges is as follows (includes some code from other answers here):
Sub test_inters()
Dim rng1 As Range
Dim rng2 As Range
Dim inters As Range
Set rng2 = Worksheets("Gen2").Range("K7")
Set rng1 = ExcludeCell(Worksheets("Gen2").Range("K6:K8"), rng2)
If (rng2.Parent.name = rng1.Parent.name) Then
Dim ints As Range
MsgBox rng1.Address & vbCrLf _
& rng2.Address & vbCrLf _
For Each cell In rng1
MsgBox cell.Address
Set ints = Application.Intersect(cell, rng2)
If (Not (ints Is Nothing)) Then
MsgBox "Yes intersection"
Else
MsgBox "No intersection"
End If
Next cell
End If
End Sub
is a concept that languages like Perl have had for quite a while, and now we’ll get this ability in C# as well. In String Interpolation, we simply prefix the string with a $ (much like we use the @ for verbatim strings). Then, we simply surround the expressions we want to interpolate with curly braces (i.e. { and }):
It looks a lot like the String.Format() placeholders, but instead of an index, it is the expression itself inside the curly braces. In fact, it shouldn’t be a surprise that it looks like String.Format() because that’s really all it is – syntactical sugar that the compiler treats like String.Format() behind the scenes.
A great part is, the compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.
C# string interpolation is a method of concatenating,formatting and manipulating strings. This feature was introduced in C# 6.0. Using string interpolation, we can use objects and expressions as a part of the string interpolation operation.
Syntax of string interpolation starts with a ‘$’ symbol and expressions are defined within a bracket {} using the following syntax.
{<interpolatedExpression>[,<alignment>][:<formatString>]}
Where:
The following code example concatenates a string where an object, author as a part of the string interpolation.
string author = "Mohit";
string hello = $"Hello {author} !";
Console.WriteLine(hello); // Hello Mohit !
Read more on C#/.NET Little Wonders: String Interpolation in C# 6
I can sympathise... having once been in a similar predicament, though I did at least have some background. I concur with @ShawnMilo regarding Head Fist Java. Also recommend Sams Teach Yourself Java in 21 Days and, given that you say you have no programming background, I strongly urge you to look at The Oject Oriented Thought Process by Matt Weisfeld. I also concur with all the people on this thread who say that there's WAY more to programming than 'simply' learning one language (especially if it's Java). Having said that, good luck and god speed.
PS I'd +1 @Patrick McDonald for sense of humour, but I don't have enough rep!
PPS And another virtual +1 for @Robin. I was wondering when the Four Yorkshiremen would get in on this thread...
Using merge
is different from lookup in Excel as it has potential to duplicate (multiply) your data if primary key constraint is not enforced in lookup table or reduce the number of records if you are not using all.x = T
.
To make sure you don't get into trouble with that and lookup safely, I suggest two strategies.
First one is to make a check on a number of duplicated rows in lookup key:
safeLookup <- function(data, lookup, by, select = setdiff(colnames(lookup), by)) {
# Merges data to lookup making sure that the number of rows does not change.
stopifnot(sum(duplicated(lookup[, by])) == 0)
res <- merge(data, lookup[, c(by, select)], by = by, all.x = T)
return (res)
}
This will force you to de-dupe lookup dataset before using it:
baseSafe <- safeLookup(largetable, house.ids, by = "HouseType")
# Error: sum(duplicated(lookup[, by])) == 0 is not TRUE
baseSafe<- safeLookup(largetable, unique(house.ids), by = "HouseType")
head(baseSafe)
# HouseType HouseTypeNo
# 1 Apartment 4
# 2 Apartment 4
# ...
Second option is to reproduce Excel behaviour by taking the first matching value from the lookup dataset:
firstLookup <- function(data, lookup, by, select = setdiff(colnames(lookup), by)) {
# Merges data to lookup using first row per unique combination in by.
unique.lookup <- lookup[!duplicated(lookup[, by]), ]
res <- merge(data, unique.lookup[, c(by, select)], by = by, all.x = T)
return (res)
}
baseFirst <- firstLookup(largetable, house.ids, by = "HouseType")
These functions are slightly different from lookup
as they add multiple columns.
The below approach works with latest Android studio (> v0.8.x):
Save the aar
file under app module's libs
folder (eg: <project>/<app>/libs/myaar.aar
)
Add the below to build.gradle of your "app" module folder (not your project root build.gradle). Note the name in compile line, it is myaar@aar not myaar.aar.
dependencies {
compile 'package.name.of.your.aar:myaar@aar'
}
repositories{
flatDir{
dirs 'libs'
}
}
Click Tools -> Android -> Sync Project with Gradle Files
Make sure the .gitignore does not have a extension!! It can't be .gitignore.txt, in windows just name the file .gitignore. and it will work.
Well I had situation when web service returned a color in hex format like "#CC2233" and I wanted to put this color on textView by using setBackGroundColor(), so I used android Color class to get int value of hex string and passed it to mentioned function. Everything worked. This is example:
String myHexColor = "#CC2233";
TextView myView = (TextView) findViewById(R.id.myTextView);
myView.setBackGroundColor(Color.pasrsehexString(myHexColor));
P.S. posted this answer because other solutions didn't work for me. I hope this will help someone:)
This eclipse plugin allows for inline source viewing and even stepping inside the Android source code:
http://code.google.com/p/adt-addons/
(edit: specifically the "Android Sources" plugin: http://adt-addons.googlecode.com/svn/trunk/source/com.android.ide.eclipse.source.update/)
Change Your Web.Config file as below. It will act like charm.
In node <system.webServer>
add below portion of code
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/>
</modules>
After adding, your Web.Config will look like below
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/>
</modules>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
To remove leading and trailing whitespaces:
let trimmedString = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
Swift 3 / Swift 4:
let trimmedString = string.trimmingCharacters(in: .whitespaces)
ID of the last updated row is the same ID that you use in the 'updateQuery' to found & update that row. So, just save(call) that ID on anyway you want.
last_insert_id()
depends of the AUTO_INCREMENT
, but the last updated ID not.
It is very simple;
def median(alist):
#to find median you will have to sort the list first
sList = sorted(alist)
first = 0
last = len(sList)-1
midpoint = (first + last)//2
return midpoint
And you can use the return value like this median = median(anyList)
You can use the gulp-filenames module to get the array of paths. You can even group them by namespaces:
var filenames = require("gulp-filenames");
gulp.src("./src/*.coffee")
.pipe(filenames("coffeescript"))
.pipe(gulp.dest("./dist"));
gulp.src("./src/*.js")
.pipe(filenames("javascript"))
.pipe(gulp.dest("./dist"));
filenames.get("coffeescript") // ["a.coffee","b.coffee"]
// Do Something With it
I have two functions:
function setSelectionRange(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
}
function setCaretToPos (input, pos) {
setSelectionRange(input, pos, pos);
}
Then you can use setCaretToPos like this:
setCaretToPos(document.getElementById("YOURINPUT"), 4);
Live example with both a textarea
and an input
, showing use from jQuery:
function setSelectionRange(input, selectionStart, selectionEnd) {_x000D_
if (input.setSelectionRange) {_x000D_
input.focus();_x000D_
input.setSelectionRange(selectionStart, selectionEnd);_x000D_
} else if (input.createTextRange) {_x000D_
var range = input.createTextRange();_x000D_
range.collapse(true);_x000D_
range.moveEnd('character', selectionEnd);_x000D_
range.moveStart('character', selectionStart);_x000D_
range.select();_x000D_
}_x000D_
}_x000D_
_x000D_
function setCaretToPos(input, pos) {_x000D_
setSelectionRange(input, pos, pos);_x000D_
}_x000D_
_x000D_
$("#set-textarea").click(function() {_x000D_
setCaretToPos($("#the-textarea")[0], 10)_x000D_
});_x000D_
$("#set-input").click(function() {_x000D_
setCaretToPos($("#the-input")[0], 10);_x000D_
});
_x000D_
<textarea id="the-textarea" cols="40" rows="4">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>_x000D_
<br><input type="button" id="set-textarea" value="Set in textarea">_x000D_
<br><input id="the-input" type="text" size="40" value="Lorem ipsum dolor sit amet, consectetur adipiscing elit">_x000D_
<br><input type="button" id="set-input" value="Set in input">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
_x000D_
As of 2016, tested and working on Chrome, Firefox, IE11, even IE8 (see that last here; Stack Snippets don't support IE8).
To add to jensendp's answer:
I would pass the entity to a user created model and use the values from that entity to set the values in your newly created model. For example:
public class UserInformation {
public string Name { get; set; }
public int Age { get; set; }
public UserInformation(UserEntity user) {
this.Name = user.name;
this.Age = user.age;
}
}
Then change your return type to: IEnumerable<UserInformation>
Tough one for a newbie like me - here is a screenshot that describes it.
Xcode 10.2.1
Take a look at http://start.spring.io/ it basically gives you a kick starter with either maven or gradle build.
Note: This is a Spring Boot based archetype.
You really can't display 3 columns of data as a 'surface'. Only having one column of 'Z' data will give you a line in 3 dimensional space, not a surface (Or in the case of your data, 3 separate lines). For Excel to be able to work with this data, it needs to be formatted as shown below:
13 21 29 37 45
1000 75.2
1000 79.21
1000 80.02
5000 87.9
5000 88.54
5000 88.56
10000 90.11
10000 90.79
10000 90.87
Then, to get an actual surface, you would need to fill in all the missing cells with the appropriate Z-values. If you don't have those, then you are better off showing this as 3 separate 2D lines, because there isn't enough data for a surface.
The best 3D representation that Excel will give you of the above data is pretty confusing:
Representing this limited dataset as 2D data might be a better choice:
As a note for future reference, these types of questions usually do a little better on superuser.com.
Also see PEP 263 if you are using a non-ascii characterset
Abstract
This PEP proposes to introduce a syntax to declare the encoding of a Python source file. The encoding information is then used by the Python parser to interpret the file using the given encoding. Most notably this enhances the interpretation of Unicode literals in the source code and makes it possible to write Unicode literals using e.g. UTF-8 directly in an Unicode aware editor.
Problem
In Python 2.1, Unicode literals can only be written using the Latin-1 based encoding "unicode-escape". This makes the programming environment rather unfriendly to Python users who live and work in non-Latin-1 locales such as many of the Asian countries. Programmers can write their 8-bit strings using the favorite encoding, but are bound to the "unicode-escape" encoding for Unicode literals.
Proposed Solution
I propose to make the Python source code encoding both visible and changeable on a per-source file basis by using a special comment at the top of the file to declare the encoding.
To make Python aware of this encoding declaration a number of concept changes are necessary with respect to the handling of Python source code data.
Defining the Encoding
Python will default to ASCII as standard encoding if no other encoding hints are given.
To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as:
# coding=<encoding name>
or (using formats recognized by popular editors)
#!/usr/bin/python # -*- coding: <encoding name> -*-
or
#!/usr/bin/python # vim: set fileencoding=<encoding name> :
...
You can use the following command c:\path of you tomcat directory\bin>catalina run
We can use slice to do this:
val = "abc"
=> "abc"
val.slice!(0)
=> "a"
val
=> "bc"
Using slice!
we can delete any character by specifying its index.
npm build
no longer exists. You must call npm run build
now. More info below.
npm install
: installs dependencies, then calls the install
from the package.json
scripts
field.
npm run build
: runs the build field from the package.json
scripts
field.
https://docs.npmjs.com/misc/scripts
There are many things you can put into the npm package.json
scripts field. Check out the documentation link above more above the lifecycle of the scripts - most have pre and post hooks that you can run scripts before/after install, publish, uninstall, test, start, stop, shrinkwrap, version.
npm install
is not the same as npm run install
npm install
installs package.json
dependencies, then runs the package.json
scripts.install
npm run install
after dependencies are installed.npm run install
only runs the package.json
scripts.install
, it will not install dependencies.npm build
used to be a valid command (used to be the same as npm run build
) but it no longer is; it is now an internal command. If you run it you'll get: npm WARN build npm build called with no arguments. Did you mean to npm run-script build?
You can read more on the documentation: https://docs.npmjs.com/cli/buildThere are still two top level commands that will run scripts, they are:
npm start
which is the same as npm run start
npm test
==> npm run test
You can handle it like this:
for API level 5 and greater
@Override
public void onBackPressed() {
// your code.
}
older than API 5
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// your code
return true;
}
return super.onKeyDown(keyCode, event);
}
min/max_element return the iterator to the min/max element, not the value of the min/max element. You have to dereference the iterator in order to get the value out and assign it to a double. That is:
cLower = *min_element(C.begin(), C.end());
There is a pairwise()
function example in the itertools
document:
from itertools import tee, izip
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)
import pandas as pd
df = pd.DataFrame(['AA', 'BB', 'CC'], columns = ['value'])
for (i1, row1), (i2, row2) in pairwise(df.iterrows()):
print i1, i2, row1["value"], row2["value"]
Here is the output:
0 1 AA BB
1 2 BB CC
But, I think iter rows in a DataFrame
is slow, if you can explain what's the problem you want to solve, maybe I can suggest some better method.
HTML5 introduces a number of APIs that help in creating Web applications. These can be used together with the new elements introduced for applications:
contenteditable
attribute.draggable
attribute.window.onload = function(){
var slider = document.getElementById("sss");
var result = document.getElementById("final");
slider.oninput = function(){
result.innerHTML = slider.value ;
}
}
_x000D_
.slider{
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.slider .container-slider{
width: 600px;
display: flex;
justify-content: center;
align-items: center;
transform: rotate(90deg)
}
.slider .container-slider input[type="range"]{
width: 60%;
-webkit-appearance: none;
background-color: blue;
height: 7px;
border-radius: 5px;;
outline: none;
margin: 0 20px
}
.slider .container-slider input[type="range"]::-webkit-slider-thumb{
-webkit-appearance: none;
width: 40px;
height: 40px;
border-radius: 50%;
background-color: red;
}
.slider .container-slider input[type="range"]::-webkit-slider-thumb:hover{
box-shadow: 0px 0px 10px rgba(255,255,255,.3),
0px 0px 15px rgba(255,255,255,.4),
0px 0px 20px rgba(255,255,255,.5),
0px 0px 25px rgba(255,255,255,.6),
0px 0px 30px rgba(255,255,255,.7)
}
.slider .container-slider .val {
width: 60px;
height: 40px;
background-color: #ACB6E5;
display: flex;
justify-content: center;
align-items: center;
font-family: consolas;
font-weight: 700;
font-size: 20px;
letter-spacing: 1.3px;
transform: rotate(-90deg)
}
.slider .container-slider .val::before{
content: "";
position: absolute;
width: 0;
height: 0;
display: block;
border: 20px solid transparent;
border-bottom-color: #ACB6E5;
top: -30px;
}
_x000D_
<div class="slider">
<div class="container-slider">
<input type="range" min="0" max="100" step="1" value="" id="sss">
<div class="val" id="final">0</div>
</div>
</div>
_x000D_
Custom String Values for Enum
from http://javahowto.blogspot.com/2006/10/custom-string-values-for-enum.html
The default string value for java enum is its face value, or the element name. However, you can customize the string value by overriding toString() method. For example,
public enum MyType {
ONE {
public String toString() {
return "this is one";
}
},
TWO {
public String toString() {
return "this is two";
}
}
}
Running the following test code will produce this:
public class EnumTest {
public static void main(String[] args) {
System.out.println(MyType.ONE);
System.out.println(MyType.TWO);
}
}
this is one
this is two
You can do it without forcing html
and body
to me 100% height. Use view port height instead. And with mouse wheel control too.
function debounce(func, wait, immediate) {_x000D_
var timeout;_x000D_
return function() {_x000D_
var context = this,_x000D_
args = arguments;_x000D_
var later = function() {_x000D_
timeout = null;_x000D_
if (!immediate) func.apply(context, args);_x000D_
};_x000D_
var callNow = immediate && !timeout;_x000D_
clearTimeout(timeout);_x000D_
timeout = setTimeout(later, wait);_x000D_
if (callNow) func.apply(context, args);_x000D_
};_x000D_
}_x000D_
_x000D_
var slider = document.getElementById("demo");_x000D_
var onScroll = debounce(function(direction) {_x000D_
//console.log(direction);_x000D_
if (direction == false) {_x000D_
$('.carousel-control-next').click();_x000D_
} else {_x000D_
$('.carousel-control-prev').click();_x000D_
}_x000D_
}, 100, true);_x000D_
_x000D_
slider.addEventListener("wheel", function(e) {_x000D_
e.preventDefault();_x000D_
var delta;_x000D_
if (event.wheelDelta) {_x000D_
delta = event.wheelDelta;_x000D_
} else {_x000D_
delta = -1 * event.deltaY;_x000D_
}_x000D_
_x000D_
onScroll(delta >= 0);_x000D_
});
_x000D_
.carousel-item {_x000D_
height: 100vh;_x000D_
background: #212121;_x000D_
}_x000D_
_x000D_
.carousel-control-next,_x000D_
.carousel-control-prev {_x000D_
width: 8% !important;_x000D_
}_x000D_
_x000D_
.carousel-item.active,_x000D_
.carousel-item-left,_x000D_
.carousel-item-right {_x000D_
display: flex !important;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
}_x000D_
_x000D_
.carousel-item h1 {_x000D_
color: #fff;_x000D_
font-size: 72px;_x000D_
padding: 0 10%;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<div id="demo" class="carousel slide" data-ride="carousel" data-interval="false">_x000D_
_x000D_
<!-- The slideshow -->_x000D_
<div class="carousel-inner">_x000D_
<div class="carousel-item active">_x000D_
<h1 class="display-1 text-center">Lorem ipsum dolor sit amet adipisicing</h1>_x000D_
</div>_x000D_
<div class="carousel-item">_x000D_
<h1 class="display-1 text-center">Inventore omnis odio, dolore culpa atque?</h1>_x000D_
</div>_x000D_
<div class="carousel-item">_x000D_
<h1 class="display-1 text-center">Lorem ipsum dolor sit</h1>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<!-- Left and right controls -->_x000D_
<a class="carousel-control-prev" href="#demo" data-slide="prev">_x000D_
<span class="carousel-control-prev-icon"></span>_x000D_
</a>_x000D_
<a class="carousel-control-next" href="#demo" data-slide="next">_x000D_
<span class="carousel-control-next-icon"></span>_x000D_
</a>_x000D_
_x000D_
</div>
_x000D_
you can use
<img className="image" src=`images/${this.props.image}`>
or
<img className="image" src={'images/'+this.props.image}>
or
render() {
let imageUrl = this.props.image ? "images/"+this.props.image : 'some placeholder url image';
return (
<div>
<img className="image" src={imageUrl} />
</div>
)
}
I have slightly modified Ilya_Gazman answer to use new APIs (IntentCompat is deprecated starting API 26). Runtime.getRuntime().exit(0) seems to be better than System.exit(0).
public static void triggerRebirth(Context context) {
PackageManager packageManager = context.getPackageManager();
Intent intent = packageManager.getLaunchIntentForPackage(context.getPackageName());
ComponentName componentName = intent.getComponent();
Intent mainIntent = Intent.makeRestartActivityTask(componentName);
context.startActivity(mainIntent);
Runtime.getRuntime().exit(0);
}
What happens if the text plus tables plus text doesn't fit onto a single page? By trying to force the typesetting in this way, you are very likely to end up with pages that run too short; i.e., because a table cannot by default break over a page it will be pushed to the next, and leave a gap on the page before. You'll notice that you never see this in a published book.
The floating behaviour is a Good Thing! I recommend using [htbp]
as the default setting for all tables and figures until your document is complete; only then should think about fine-tuning their precise placement.
P.S. Read the FAQ; most other answers here are partial combinations of advice given there.
Below code will list directories and the files within the dir. The other one is os.walk
def print_directory_contents(sPath):
import os
for sChild in os.listdir(sPath):
sChildPath = os.path.join(sPath,sChild)
if os.path.isdir(sChildPath):
print_directory_contents(sChildPath)
else:
print(sChildPath)
I also wanted to clarify that if you have complex url parameters to build, you will need to build them manually. ie if your query is example.com/?latlng=-37,147
, instead of providing the lat and lng values individually, you will need to build the latlng string externally, then provide it as a parameter, ie:
public interface LocationService {
@GET("/example/")
void getLocation(@Query(value="latlng", encoded=true) String latlng);
}
Note the encoded=true
is necessary, otherwise retrofit will encode the comma in the string parameter. Usage:
String latlng = location.getLatitude() + "," + location.getLongitude();
service.getLocation(latlng);
def reverse(text):
output = []
for i in range(len(text)-1, -1, -1):
output.append(text[i])
return output
Once you're logged into phpmyadmin look on the top navigation for "Settings" and click that then:
"Features" >
Unfortunately changing it through the UI means that the changes don't persist between logins.
It checks to see whether the specific object is contained in the list.
You might be better using the Find method on the list.
Here's an example
List<CartProduct> lst = new List<CartProduct>();
CartProduct objBeer;
objBeer = lst.Find(x => (x.Name == "Beer"));
Hope that helps
You should also look at LinQ - overkill for this perhaps, but a useful tool nonetheless...
This thread has been around a while, and I thought I'd add something about HOW to build Boost as fast as possible on your specific hardware.
If you have a 4 or 6-core use -j5 or -j7 respectively. Certainly not the standard build nor -j2 unless you indeed have dual core.
I'm running a Sandy Bridge Extreme with stock clocked 3930K (6-core) on my main station, but have a 2600k (4-core) on older backup box, and the trend is I get the best Boost compile times with N + 1 build processes where N is the number of physical cores. N+2 reaches a point of diminishing returns and the times go up.
Notes: Hyperthreading is enabled, 32GB RAM DDR3, Samsung 840 EVO SSD.
-j7 on 6-core (2 minutes and 51 seconds) (Win7 Ultimate x64)(Visual Studio 2013)
PS C:\Boost\boost_1_56_0> measure-command { .\b2 -j7 --build-type=complete msvc stage }
Days : 0
Hours : 0
Minutes : 2
Seconds : 51
Milliseconds : 128
Ticks : 1711281830
TotalDays : 0.0019806502662037
TotalHours : 0.0475356063888889
TotalMinutes : 2.85213638333333
TotalSeconds : 171.128183
TotalMilliseconds : 171128.183
-j6 on 6-core (3 minutes and 2 seconds) (Win7 Ultimate x64)(Visual Studio 2013)
PS C:\Boost\boost_1_56_0> measure-command { .\b2 -j6 --build-type=complete msvc stage }
Days : 0
Hours : 0
Minutes : 3
Seconds : 2
Milliseconds : 809
Ticks : 1828093904
TotalDays : 0.00211584942592593
TotalHours : 0.0507803862222222
TotalMinutes : 3.04682317333333
TotalSeconds : 182.8093904
TotalMilliseconds : 182809.3904
-j8 on 6-core (3 minutes and 17 seconds) (Win7 Ultimate x64)(Visual Studio 2013)
PS C:\Boost\boost_1_56_0> measure-command { .\b2 -j8 --build-type=complete msvc stage }
Days : 0
Hours : 0
Minutes : 3
Seconds : 17
Milliseconds : 652
Ticks : 1976523915
TotalDays : 0.00228764342013889
TotalHours : 0.0549034420833333
TotalMinutes : 3.294206525
TotalSeconds : 197.6523915
TotalMilliseconds : 197652.3915
Config
Building the Boost C++ Libraries.
Performing configuration checks
- 32-bit : yes (cached)
- arm : no (cached)
- mips1 : no (cached)
- power : no (cached)
- sparc : no (cached)
- x86 : yes (cached)
- has_icu builds : no (cached)
warning: Graph library does not contain MPI-based parallel components.
note: to enable them, add "using mpi ;" to your user-config.jam
- zlib : no (cached)
- iconv (libc) : no (cached)
- iconv (separate) : no (cached)
- icu : no (cached)
- icu (lib64) : no (cached)
- message-compiler : yes (cached)
- compiler-supports-ssse3 : yes (cached)
- compiler-supports-avx2 : yes (cached)
- gcc visibility : no (cached)
- long double support : yes (cached)
warning: skipping optional Message Passing Interface (MPI) library.
note: to enable MPI support, add "using mpi ;" to user-config.jam.
note: to suppress this message, pass "--without-mpi" to bjam.
note: otherwise, you can safely ignore this message.
- zlib : no (cached)
I note the 64-bit build takes a bit longer, I need to do the same comparison for those and update.
I was having this same issue and I resolved it in the following way...
I have the NVIDIA "Tegra Android Development Pack" installed and it seems to also have a version of mysysgit.exe with it. TortoiseGit automatically found that installation location (instead of the standard git installation) and auto-populated it in the settings menu.
To correct this, go to: "Settings -> General" and there is a field for the path to mysysgit.exe. Make sure this is pointing to the correct installation.
You can use a deadlock graph
and gather the information you require from the log file.
The only other way I could suggest is digging through the information by using EXEC SP_LOCK
(Soon to be deprecated), EXEC SP_WHO2
or the sys.dm_tran_locks
table.
SELECT L.request_session_id AS SPID,
DB_NAME(L.resource_database_id) AS DatabaseName,
O.Name AS LockedObjectName,
P.object_id AS LockedObjectId,
L.resource_type AS LockedResource,
L.request_mode AS LockType,
ST.text AS SqlStatementText,
ES.login_name AS LoginName,
ES.host_name AS HostName,
TST.is_user_transaction as IsUserTransaction,
AT.name as TransactionName,
CN.auth_scheme as AuthenticationMethod
FROM sys.dm_tran_locks L
JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
JOIN sys.objects O ON O.object_id = P.object_id
JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE resource_database_id = db_id()
ORDER BY L.request_session_id
http://www.sqlmag.com/article/sql-server-profiler/gathering-deadlock-information-with-deadlock-graph
Use as.integer
:
set.seed(1)
x <- runif(5, 0, 100)
x
[1] 26.55087 37.21239 57.28534 90.82078 20.16819
as.integer(x)
[1] 26 37 57 90 20
Test for class:
xx <- as.integer(x)
str(xx)
int [1:5] 26 37 57 90 20
Apply (different) name attribute to both buttons like
<button name="one">
and catch them in request.data.
For MySql take in mind that it's not a good idea to write camelcase. For example if the schema is like that:
CREATE TABLE IF NOT EXISTS `task`(
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`teaching_hours` DECIMAL(5,2) DEFAULT NULL,
`isActive` BOOLEAN DEFAULT FALSE,
`is_validated` BOOLEAN DEFAULT FALSE,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
You must be very careful cause isActive
column will translate to isactive
.
So in your Entity class is should be like this:
@Basic
@Column(name = "isactive", nullable = true)
public boolean isActive() {
return isActive;
}
public void setActive(boolean active) {
isActive = active;
}
That was my problem at least that got me your error
This has nothing to do with MySql which is case insensitive, but rather is a naming strategy that spring will use to translate your tables. For more refer to this post
I use jQuery.getJSON( url [, data ] [, success( data, textStatus, jqXHR ) ] )
for example:
var url="my.php";
$.getJSON( url, myObj )
.done(function( json ) { ... }) /* got JSON from server */
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Failed to obtain JSON data from server: " + err );
}); /* failed to get JSON */
getJSON is shorthand for:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
For me, I encountered this error many times,
Error inflating class android.support.design.widget.NavigationView #28 and #29
The solution that works for me is that you must match your support design library and your support appcompat library.
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
For me they must match. :) It works for me!
I had the same issue, and spent quite a bit of time trying to track down the solution. I had Anonymous Authentication set up at two different levels with two different users. Make sure that you're not overwriting your set up at a lower level.
You can write your own Extension method for type String :-
public static string NonBlankValueOf(this string source)
{
return (string.IsNullOrEmpty(source)) ? "0" : source;
}
Now you can use it like with any string type
FooTextBox.Text = strFoo.NonBlankValueOf();
It's simple
y = [['vegas','London'],['US','UK']]
for x in y:
for a in x:
print(a)
you may be create function before so, update your function again using.
Alter FUNCTION dbo.Afisho_rankimin(@emri_rest int)
RETURNS int
AS
BEGIN
Declare @rankimi int
Select @rankimi=dbo.RESTORANTET.Rankimi
From RESTORANTET
Where dbo.RESTORANTET.ID_Rest=@emri_rest
RETURN @rankimi
END
GO
SELECT dbo.Afisho_rankimin(5) AS Rankimi
GO
$ bash --init-file <(echo 'some_command')
$ bash --rcfile <(echo 'some_command')
In case you can't or don't want to use process substitution:
$ cat script
some_command
$ bash --init-file script
Another way:
$ bash -c 'some_command; exec bash'
$ sh -c 'some_command; exec sh'
sh
-only way (dash
, busybox
):
$ ENV=script sh
Using Altair.
from altair import *
import pandas as pd
df = datasets.load_dataset('iris')
Chart(df).mark_point().encode(x='petalLength',y='sepalLength', color='species')
Sorry, misunderstood your question.
According to Javascript - capturing onsubmit when calling form.submit():
I was recently asked: "Why doesn't the form.onsubmit event get fired when I submit my form using javascript?"
The answer: Current browsers do not adhere to this part of the html specification. The event only fires when it is activated by a user - and does not fire when activated by code.
(emphasis added).
Note: "activated by a user" also includes hitting submit buttons (probably including default submit behaviour from the enter key but I haven't tried this). Nor, I believe, does it get triggered if you (with code) click a submit button.
You can pass this
to each block. See here: http://jsfiddle.net/yR7TZ/1/
{{#each this}}
<div class="row"></div>
{{/each}}
Removing the borders should make the background color paint without any gaps between the cells. If you look carefully at this jsFiddle, you should see that the light blue color stretches across the row with no white gaps.
If all else fails, try this:
table { border-collapse: collapse; }
You can find an updated version of the mentioned script that works on both Windows and Linux here
If using WORD for mac enable 'use maths autocorrect rules outside maths regions' Type \therefore