simple one:
[[@"first" stringByAppendingString:@"second"] stringByAppendingString:@"third"];
if you have many STRINGS to Concatenate, you should use NSMutableString
for better performance
Save to local storage
localStorage.setItem('currentUser', JSON.stringify({ token: token, name: name }));
Load from local storage
var currentUser = JSON.parse(localStorage.getItem('currentUser'));
var token = currentUser.token; // your token
For more I suggest you go through this tutorial: Angular 2 JWT Authentication Example & Tutorial
This thread seems unnecessarily controversial.
If you really want to solve this question correctly, using jQuery, please see the solution below.
The question is "jQuery How do you get an image to fade in on load?"
First, a quick note.
This is not a good candidate for $(document).ready...
Why? Because the document is ready when the HTML DOM is loaded. The logo image will not be ready at this point - it may still be downloading in fact!
So to answer first the general question "jQuery How do you get an image to fade in on load?" - the image in this example has an id="logo" attribute:
$("#logo").bind("load", function () { $(this).fadeIn(); });
This does exactly what the question asks. When the image has loaded, it will fade in. If you change the source of the image, when the new source has loaded, it will fade in.
There is a comment about using window.onload alongside jQuery. This is perfectly possible. It works. It can be done. However, the window.onload event needs a particular bit of care. This is because if you use it more than once, you overwrite your previous events. Example (feel free to try it...).
function SaySomething(words) {
alert(words);
}
window.onload = function () { SaySomething("Hello"); };
window.onload = function () { SaySomething("Everyone"); };
window.onload = function () { SaySomething("Oh!"); };
Of course, you wouldn't have three onload events so close together in your code. You would most likely have a script that does something onload, and then add your window.onload handler to fade in your image - "why has my slide show stopped working!!?" - because of the window.onload problem.
One great feature of jQuery is that when you bind events using jQuery, they ALL get added.
So there you have it - the question has already been marked as answered, but the answer seems to be insufficient based on all the comments. I hope this helps anyone arriving from the world's search engines!
I had the same issue and solved it using this code.
MyFragment fragment = (MyFragment) thisActivity.getFragmentManager().findFragmentById(R.id.container);
Just replace the name MyFragment with the name of your fragment and add the id of your fragment container.
For what it's worth adding to the discussion... what I did that ended up helping me... Since the pipeline is run within a workspace within a docker image that is cleaned up each time it runs. I grabbed the credentials needed to perform necessary operations on the repo within my pipeline and stored them in a .netrc file. this allowed me to authorize the git repo operations successfully.
withCredentials([usernamePassword(credentialsId: '<credentials-id>', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
sh '''
printf "machine github.com\nlogin $GIT_USERNAME\n password $GIT_PASSWORD" >> ~/.netrc
// continue script as necessary working with git repo...
'''
}
For Apache server, you should check mod_expires for setting Expires and Cache-Control headers.
Alternatively, you can use Header directive to add Cache-Control on your own:
Header set Cache-Control "max-age=290304000, public"
lstr=[1, 2, 3]
lstr=map(str,lstr)
r=re.compile('^(3){1}')
results=list(filter(r.match,lstr))
print(results)
There are two elements in array and this definitely doesn't mean that array is empty. As a quick workaround you can do following:
$errors = array_filter($errors);
if (!empty($errors)) {
}
array_filter()
function's default behavior will remove all values from array which are equal to null
, 0
, ''
or false
.
Otherwise in your particular case empty()
construct will always return true
if there is at least one element even with "empty" value.
Doing it the mathy way...
nums = [1, 2, 3, 4, 5]
min_combo = (min(nums), max(nums))
Unless, of course, you have negatives in there. In that case, this won't work because you actually want the min and max absolute values - the numerator should be close to zero, and the denominator far from it, in either direction. And double negatives would break it.
That is very odd.
I went through ItemNotFoundException
's base classes and tested the following multiple catch
es to see what would catch it:
try {
remove-item C:\nonexistent\file.txt -erroraction stop
}
catch [System.Management.Automation.ItemNotFoundException] {
write-host 'ItemNotFound'
}
catch [System.Management.Automation.SessionStateException] {
write-host 'SessionState'
}
catch [System.Management.Automation.RuntimeException] {
write-host 'RuntimeException'
}
catch [System.SystemException] {
write-host 'SystemException'
}
catch [System.Exception] {
write-host 'Exception'
}
catch {
write-host 'well, darn'
}
As it turns out, the output was 'RuntimeException'
. I also tried it with a different exception CommandNotFoundException
:
try {
do-nonexistent-command
}
catch [System.Management.Automation.CommandNotFoundException] {
write-host 'CommandNotFoundException'
}
catch {
write-host 'well, darn'
}
That output 'CommandNotFoundException'
correctly.
I vaguely remember reading elsewhere (though I couldn't find it again) of problems with this. In such cases where exception filtering didn't work correctly, they would catch the closest Type
they could and then use a switch
. The following just catches Exception
instead of RuntimeException
, but is the switch
equivalent of my first example that checks all base types of ItemNotFoundException
:
try {
Remove-Item C:\nonexistent\file.txt -ErrorAction Stop
}
catch [System.Exception] {
switch($_.Exception.GetType().FullName) {
'System.Management.Automation.ItemNotFoundException' {
write-host 'ItemNotFound'
}
'System.Management.Automation.SessionStateException' {
write-host 'SessionState'
}
'System.Management.Automation.RuntimeException' {
write-host 'RuntimeException'
}
'System.SystemException' {
write-host 'SystemException'
}
'System.Exception' {
write-host 'Exception'
}
default {'well, darn'}
}
}
This writes 'ItemNotFound'
, as it should.
Since Dave asked for me to repeat my answer to Omitting all xsi and xsd namespaces when serializing an object in .NET, I have updated this post and repeated my answer here from the afore-mentioned link. The example used in this answer is the same example used for the other question. What follows is copied, verbatim.
After reading Microsoft's documentation and several solutions online, I have discovered the solution to this problem. It works with both the built-in XmlSerializer
and custom XML serialization via IXmlSerialiazble
.
To whit, I'll use the same MyTypeWithNamespaces
XML sample that's been used in the answers to this question so far.
[XmlRoot("MyTypeWithNamespaces", Namespace="urn:Abracadabra", IsNullable=false)]
public class MyTypeWithNamespaces
{
// As noted below, per Microsoft's documentation, if the class exposes a public
// member of type XmlSerializerNamespaces decorated with the
// XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
// namespaces during serialization.
public MyTypeWithNamespaces( )
{
this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
// Don't do this!! Microsoft's documentation explicitly says it's not supported.
// It doesn't throw any exceptions, but in my testing, it didn't always work.
// new XmlQualifiedName(string.Empty, string.Empty), // And don't do this:
// new XmlQualifiedName("", "")
// DO THIS:
new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
// Add any other namespaces, with prefixes, here.
});
}
// If you have other constructors, make sure to call the default constructor.
public MyTypeWithNamespaces(string label, int epoch) : this( )
{
this._label = label;
this._epoch = epoch;
}
// An element with a declared namespace different than the namespace
// of the enclosing type.
[XmlElement(Namespace="urn:Whoohoo")]
public string Label
{
get { return this._label; }
set { this._label = value; }
}
private string _label;
// An element whose tag will be the same name as the property name.
// Also, this element will inherit the namespace of the enclosing type.
public int Epoch
{
get { return this._epoch; }
set { this._epoch = value; }
}
private int _epoch;
// Per Microsoft's documentation, you can add some public member that
// returns a XmlSerializerNamespaces object. They use a public field,
// but that's sloppy. So I'll use a private backed-field with a public
// getter property. Also, per the documentation, for this to work with
// the XmlSerializer, decorate it with the XmlNamespaceDeclarations
// attribute.
[XmlNamespaceDeclarations]
public XmlSerializerNamespaces Namespaces
{
get { return this._namespaces; }
}
private XmlSerializerNamespaces _namespaces;
}
That's all to this class. Now, some objected to having an XmlSerializerNamespaces
object somewhere within their classes; but as you can see, I neatly tucked it away in the default constructor and exposed a public property to return the namespaces.
Now, when it comes time to serialize the class, you would use the following code:
MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);
/******
OK, I just figured I could do this to make the code shorter, so I commented out the
below and replaced it with what follows:
// You have to use this constructor in order for the root element to have the right namespaces.
// If you need to do custom serialization of inner objects, you can use a shortened constructor.
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces), new XmlAttributeOverrides(),
new Type[]{}, new XmlRootAttribute("MyTypeWithNamespaces"), "urn:Abracadabra");
******/
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });
// I'll use a MemoryStream as my backing store.
MemoryStream ms = new MemoryStream();
// This is extra! If you want to change the settings for the XmlSerializer, you have to create
// a separate XmlWriterSettings object and use the XmlTextWriter.Create(...) factory method.
// So, in this case, I want to omit the XML declaration.
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Encoding = Encoding.UTF8; // This is probably the default
// You could use the XmlWriterSetting to set indenting and new line options, but the
// XmlTextWriter class has a much easier method to accomplish that.
// The factory method returns a XmlWriter, not a XmlTextWriter, so cast it.
XmlTextWriter xtw = (XmlTextWriter)XmlTextWriter.Create(ms, xws);
// Then we can set our indenting options (this is, of course, optional).
xtw.Formatting = Formatting.Indented;
// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);
Once you have done this, you should get the following output:
<MyTypeWithNamespaces>
<Label xmlns="urn:Whoohoo">myLabel</Label>
<Epoch>42</Epoch>
</MyTypeWithNamespaces>
I have successfully used this method in a recent project with a deep hierachy of classes that are serialized to XML for web service calls. Microsoft's documentation is not very clear about what to do with the publicly accesible XmlSerializerNamespaces
member once you've created it, and so many think it's useless. But by following their documentation and using it in the manner shown above, you can customize how the XmlSerializer generates XML for your classes without resorting to unsupported behavior or "rolling your own" serialization by implementing IXmlSerializable
.
It is my hope that this answer will put to rest, once and for all, how to get rid of the standard xsi
and xsd
namespaces generated by the XmlSerializer
.
UPDATE: I just want to make sure I answered the OP's question about removing all namespaces. My code above will work for this; let me show you how. Now, in the example above, you really can't get rid of all namespaces (because there are two namespaces in use). Somewhere in your XML document, you're going to need to have something like xmlns="urn:Abracadabra" xmlns:w="urn:Whoohoo
. If the class in the example is part of a larger document, then somewhere above a namespace must be declared for either one of (or both) Abracadbra
and Whoohoo
. If not, then the element in one or both of the namespaces must be decorated with a prefix of some sort (you can't have two default namespaces, right?). So, for this example, Abracadabra
is the default namespace. I could inside my MyTypeWithNamespaces
class add a namespace prefix for the Whoohoo
namespace like so:
public MyTypeWithNamespaces
{
this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
new XmlQualifiedName(string.Empty, "urn:Abracadabra"), // Default Namespace
new XmlQualifiedName("w", "urn:Whoohoo")
});
}
Now, in my class definition, I indicated that the <Label/>
element is in the namespace "urn:Whoohoo"
, so I don't need to do anything further. When I now serialize the class using my above serialization code unchanged, this is the output:
<MyTypeWithNamespaces xmlns:w="urn:Whoohoo">
<w:Label>myLabel</w:Label>
<Epoch>42</Epoch>
</MyTypeWithNamespaces>
Because <Label>
is in a different namespace from the rest of the document, it must, in someway, be "decorated" with a namespace. Notice that there are still no xsi
and xsd
namespaces.
This ends my answer to the other question. But I wanted to make sure I answered the OP's question about using no namespaces, as I feel I didn't really address it yet. Assume that <Label>
is part of the same namespace as the rest of the document, in this case urn:Abracadabra
:
<MyTypeWithNamespaces>
<Label>myLabel<Label>
<Epoch>42</Epoch>
</MyTypeWithNamespaces>
Your constructor would look as it would in my very first code example, along with the public property to retrieve the default namespace:
// As noted below, per Microsoft's documentation, if the class exposes a public
// member of type XmlSerializerNamespaces decorated with the
// XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
// namespaces during serialization.
public MyTypeWithNamespaces( )
{
this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
});
}
[XmlNamespaceDeclarations]
public XmlSerializerNamespaces Namespaces
{
get { return this._namespaces; }
}
private XmlSerializerNamespaces _namespaces;
Then, later, in your code that uses the MyTypeWithNamespaces
object to serialize it, you would call it as I did above:
MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });
...
// Above, you'd setup your XmlTextWriter.
// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);
And the XmlSerializer
would spit back out the same XML as shown immediately above with no additional namespaces in the output:
<MyTypeWithNamespaces>
<Label>myLabel<Label>
<Epoch>42</Epoch>
</MyTypeWithNamespaces>
If you want to know the number of days (if any), the number of hours (if any), minutues (if any) and seconds, you can do the following:
$previousTimeStamp = strtotime("2011/07/01 21:12:34");
$lastTimeStamp = strtotime("2013/09/17 12:34:11");
$menos=$lastTimeStamp-$previousTimeStamp;
$mins=$menos/60;
if($mins<1){
$showing= $menos . " seconds ago";
}
else{
$minsfinal=floor($mins);
$secondsfinal=$menos-($minsfinal*60);
$hours=$minsfinal/60;
if($hours<1){
$showing= $minsfinal . " minutes and " . $secondsfinal. " seconds ago";
}
else{
$hoursfinal=floor($hours);
$minssuperfinal=$minsfinal-($hoursfinal*60);
$days=$hoursfinal/24;
if($days<1){
$showing= $hoursfinal . "hours, " . $minssuperfinal . " minutes and " . $secondsfinal. " seconds ago";
}
else{
$daysfinal=floor($days);
$hourssuperfinal=$hoursfinal-($daysfinal*24);
$showing= $daysfinal. "days, " .$hourssuperfinal . " hours, " . $minssuperfinal . " minutes and " . $secondsfinal. " seconds ago";
}}}
echo $showing;
You could use the same logic if you want to add months and years.
The CSS element()
function may eventually help some people here, even though it's not a direct answer to the question. It allows you to use an element (and all children, including videos, cross-domain iframes, etc.) as a background image (and anywhere else that you'd normally use url(...)
in your CSS code). Here's a blog post that shows what you can do with it.
It has been implemented in Firefox since 2011, and is being considered in Chromium/Chrome (don't forget to give the issue a star if you care about this functionality).
I found myself here after needing this same query for some Business Intelligence Queries I'm running on an e-commerce store. I wanted to add my solution as it may be helpful to others.
set @firstOfLastLastMonth = DATE_SUB(LAST_DAY(DATE_ADD(NOW(), INTERVAL -2 MONTH)),INTERVAL DAY(LAST_DAY(DATE_ADD(NOW(), INTERVAL -2 MONTH)))-1 DAY);
set @lastOfLastLastMonth = LAST_DAY(DATE_ADD(NOW(), INTERVAL -2 MONTH));
set @firstOfLastMonth = DATE_SUB(LAST_DAY(DATE_ADD(NOW(), INTERVAL -1 MONTH)),INTERVAL DAY(LAST_DAY(DATE_ADD(NOW(), INTERVAL -1 MONTH)))-1 DAY);
set @lastOfLastMonth = LAST_DAY(DATE_ADD(NOW(), INTERVAL -1 MONTH));
set @firstOfMonth = DATE_ADD(@lastOfLastMonth, INTERVAL 1 DAY);
set @today = CURRENT_DATE;
@firstOfLastLastMonth = '2019-08-01'
@lastOfLastLastMonth = '2019-08-31'
@firstOfLastMonth = '2019-09-01'
@lastOfLastMonth = '2019-09-30'
@firstOfMonth = '2019-10-01'
@today = '2019-10-08'
Reading the friendly manual? Who'd want to do that?
start = Time.now
largest_known_fixnum = 1
smallest_known_bignum = nil
until smallest_known_bignum == largest_known_fixnum + 1
if smallest_known_bignum.nil?
next_number_to_try = largest_known_fixnum * 1000
else
next_number_to_try = (smallest_known_bignum + largest_known_fixnum) / 2 # Geometric mean would be more efficient, but more risky
end
if next_number_to_try <= largest_known_fixnum ||
smallest_known_bignum && next_number_to_try >= smallest_known_bignum
raise "Can't happen case"
end
case next_number_to_try
when Bignum then smallest_known_bignum = next_number_to_try
when Fixnum then largest_known_fixnum = next_number_to_try
else raise "Can't happen case"
end
end
finish = Time.now
puts "The largest fixnum is #{largest_known_fixnum}"
puts "The smallest bignum is #{smallest_known_bignum}"
puts "Calculation took #{finish - start} seconds"
This works everywhere including Safari 5 and Firefox 5 on OS X.
UPDATE: Fx Quantum (54) has no need for the replace, but Safari 11 is still not happy unless you convert as below
var date_test = new Date("2011-07-14 11:23:00".replace(/-/g,"/"));_x000D_
console.log(date_test);
_x000D_
The linker problem you encountered is probably caused by:
This is a common problem for those who starts with C++. Static class member must be initialized in single translation unit i.e. in single source file.
Unfortunately, the static class member must be initialized outside of the class body. This complicates writing header-only code, and, therefore, I am using quite different approach. You can provide your static object through static or non-static class function for example:
class Foo
{
// int& getObjectInstance() const {
static int& getObjectInstance() {
static int object;
return object;
}
void func() {
int &object = getValueInstance();
object += 5;
}
};
Some frameworks are using this header to detect xhr requests e.g. grails spring security is using this header to identify xhr request and give either a json response or html response as response.
Most Ajax libraries (Prototype, JQuery, and Dojo as of v2.1) include an X-Requested-With header that indicates that the request was made by XMLHttpRequest instead of being triggered by clicking a regular hyperlink or form submit button.
Source: http://grails-plugins.github.io/grails-spring-security-core/guide/helperClasses.html
Firefox 3.0 and higher have disabled setting location
by default. resizable
and status
are also disabled by default. You can verify this by typing `about:config' in your address bar and filtering by "dom". The items of interest are:
You can get further information at the Mozilla Developer site. What this basically means, though, is that you won't be able to do what you want to do.
One thing you might want to do (though it won't solve your problem), is put quotes around your window feature parameters, like so:
window.open('/pageaddress.html','winname','directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=400,height=350');
The :nth-child() and :nth-of-type() pseudo-classes allows you to select elements with a formula.
The syntax is :nth-child(an+b), where you replace a and b by numbers of your choice.
For instance, :nth-child(3n+1) selects the 1st, 4th, 7th etc. child.
td:nth-child(3n+1) {
/* your stuff here */
}
:nth-of-type() works the same, except that it only considers element of the given type ( in the example).
In a situation where you have this:
enum fruit {
apple,
orange,
grape,
banana,
// etc.
};
I like to put this in the header file where the enum is defined:
static inline char *stringFromFruit(enum fruit f)
{
static const char *strings[] = { "apple", "orange", "grape", "banana", /* continue for rest of values */ };
return strings[f];
}
From the command line:
psql -f 1.sql
psql -f 2.sql
From the psql
prompt:
\i 1.sql
\i 2.sql
Note that you may need to import the files in a specific order (for example: data definition before data manipulation). If you've got bash
shell (GNU/Linux, Mac OS X, Cygwin) and the files may be imported in the alphabetical order, you may use this command:
for f in *.sql ; do psql -f $f ; done
Here's the documentation of the psql
application (thanks, Frank): http://www.postgresql.org/docs/current/static/app-psql.html
If working on EJB client library:
You need to mention the argument for getting the initial context.
InitialContext ctx = new InitialContext();
If you do not, it will look in the project folder for properties file. Also you can include the properties credentials or values in your class file itself as follows:
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
props.put(Context.PROVIDER_URL, "jnp://localhost:1099");
InitialContext ctx = new InitialContext(props);
URL_PKG_PREFIXES: Constant that holds the name of the environment property for specifying the list of package prefixes to use when loading in URL context factories.
The EJB client library is the primary library to invoke remote EJB components.
This library can be used through the InitialContext. To invoke EJB components the library creates an EJB client context via a URL context factory. The only necessary configuration is to parse the value org.jboss.ejb.client.naming for the java.naming.factory.url.pkgs property to instantiate an InitialContext.
This is an old question, but I am not sure why people didn't suggest using the event object to retrieve the info instead of searching through the DOM again.
Simply go through the event object in your function onChange, see example bellow
function test() {
console.log(event.srcElement.value);
}
http://jsfiddle.net/Corsico/3yvh9wc6/5/
Might be useful to people looking this up today if this wasn't default behavior 7 years ago
The way it's set in the initialize
method uses the protected RoundRectDrawable
class, like so:
RoundRectDrawable backgroundDrawable = new RoundRectDrawable(backgroundColor, cardView.getRadius());
cardView.setBackgroundDrawable(backgroundDrawable);
It's not pretty, but you can extend that class. Something like:
package android.support.v7.widget;
public class MyRoundRectDrawable extends RoundRectDrawable {
public MyRoundRectDrawable(int backgroundColor, float radius) {
super(backgroundColor, radius);
}
}
then:
final MyRoundRectDrawable backgroundDrawable = new MyRoundRectDrawable(bgColor,
mCardView.getRadius());
mCardView.setBackgroundDrawable(backgroundDrawable);
EDIT
This won't give you the shadow on < API 21, so you'd have to do the same with RoundRectDrawableWithShadow
.
There doesn't appear to be a better way to do this.
Recommended as an answer:
Here's a solution using es2015 generators:
function* subsetSum(numbers, target, partial = [], partialSum = 0) {
if(partialSum === target) yield partial
if(partialSum >= target) return
for(let i = 0; i < numbers.length; i++){
const remaining = numbers.slice(i + 1)
, n = numbers[i]
yield* subsetSum(remaining, target, [...partial, n], partialSum + n)
}
}
Using generators can actually be very useful because it allows you to pause script execution immediately upon finding a valid subset. This is in contrast to solutions without generators (ie lacking state) which have to iterate through every single subset of numbers
if you add the print code to check the type of real, you will see that real is a string, not an Entry so there is no delete attribute.
def res(real, secret):
print(type(real))
if secret==eval(real):
showinfo(message='that is right!')
real.delete(0, END)
>> output: <class 'str'>
secret = randrange(1,100)
print(secret)
def res(real, secret):
if secret==eval(real):
showinfo(message='that is right!')
ent.delete(0, END) # we call the entry an delete its content
def guess():
ge = Tk()
ge.title('guessing game')
Label(ge, text="what is your guess:").pack(side=TOP)
global ent # Globalize ent to use it in other function
ent = Entry(ge)
ent.pack(side=TOP)
btn=Button(ge, text="Enter", command=lambda: res(ent.get(),secret))
btn.pack(side=LEFT)
ge.mainloop()
It should work.
The ternary operator can be included within an rvalue, whereas an if-then-else cannot; on the other hand, an if-then-else can execute loops and other statements, whereas the ternary operator can only execute (possibly void) rvalues.
On a related note, the && and || operators allow some execution patterns which are harder to implement with if-then-else. For example, if one has several functions to call and wishes to execute a piece of code if any of them fail, it can be done nicely using the && operator. Doing it without that operator will either require redundant code, a goto, or an extra flag variable.
When a JSF view (Facelets/JSP file) get built/restored, a JSF component tree will be produced. At that moment, the view build time, all binding
attributes are evaluated (along with id
attribtues and taghandlers like JSTL). When the JSF component needs to be created before being added to the component tree, JSF will check if the binding
attribute returns a precreated component (i.e. non-null
) and if so, then use it. If it's not precreated, then JSF will autocreate the component "the usual way" and invoke the setter behind binding
attribute with the autocreated component instance as argument.
In effects, it binds a reference of the component instance in the component tree to a scoped variable. This information is in no way visible in the generated HTML representation of the component itself. This information is in no means relevant to the generated HTML output anyway. When the form is submitted and the view is restored, the JSF component tree is just rebuilt from scratch and all binding
attributes will just be re-evaluated like described in above paragraph. After the component tree is recreated, JSF will restore the JSF view state into the component tree.
Important to know and understand is that the concrete component instances are effectively request scoped. They're newly created on every request and their properties are filled with values from JSF view state during restore view phase. So, if you bind the component to a property of a backing bean, then the backing bean should absolutely not be in a broader scope than the request scope. See also JSF 2.0 specitication chapter 3.1.5:
3.1.5 Component Bindings
...
Component bindings are often used in conjunction with JavaBeans that are dynamically instantiated via the Managed Bean Creation facility (see Section 5.8.1 “VariableResolver and the Default VariableResolver”). It is strongly recommend that application developers place managed beans that are pointed at by component binding expressions in “request” scope. This is because placing it in session or application scope would require thread-safety, since UIComponent instances depends on running inside of a single thread. There are also potentially negative impacts on memory management when placing a component binding in “session” scope.
Otherwise, component instances are shared among multiple requests, possibly resulting in "duplicate component ID" errors and "weird" behaviors because validators, converters and listeners declared in the view are re-attached to the existing component instance from previous request(s). The symptoms are clear: they are executed multiple times, one time more with each request within the same scope as the component is been bound to.
And, under heavy load (i.e. when multiple different HTTP requests (threads) access and manipulate the very same component instance at the same time), you may face sooner or later an application crash with e.g. Stuck thread at UIComponent.popComponentFromEL, or Java Threads at 100% CPU utilization using richfaces UIDataAdaptorBase and its internal HashMap, or even some "strange" IndexOutOfBoundsException
or ConcurrentModificationException
coming straight from JSF implementation source code while JSF is busy saving or restoring the view state (i.e. the stack trace indicates saveState()
or restoreState()
methods and like).
binding
on a bean property is bad practiceRegardless, using binding
this way, binding a whole component instance to a bean property, even on a request scoped bean, is in JSF 2.x a rather rare use case and generally not the best practice. It indicates a design smell. You normally declare components in the view side and bind their runtime attributes like value
, and perhaps others like styleClass
, disabled
, rendered
, etc, to normal bean properties. Then, you just manipulate exactly that bean property you want instead of grabbing the whole component and calling the setter method associated with the attribute.
In cases when a component needs to be "dynamically built" based on a static model, better is to use view build time tags like JSTL, if necessary in a tag file, instead of createComponent()
, new SomeComponent()
, getChildren().add()
and what not. See also How to refactor snippet of old JSP to some JSF equivalent?
Or, if a component needs to be "dynamically rendered" based on a dynamic model, then just use an iterator component (<ui:repeat>
, <h:dataTable>
, etc). See also How to dynamically add JSF components.
Composite components is a completely different story. It's completely legit to bind components inside a <cc:implementation>
to the backing component (i.e. the component identified by <cc:interface componentType>
. See also a.o. Split java.util.Date over two h:inputText fields representing hour and minute with f:convertDateTime and How to implement a dynamic list with a JSF 2.0 Composite Component?
binding
in local scopeHowever, sometimes you'd like to know about the state of a different component from inside a particular component, more than often in use cases related to action/value dependent validation. For that, the binding
attribute can be used, but not in combination with a bean property. You can just specify an in the local EL scope unique variable name in the binding
attribute like so binding="#{foo}"
and the component is during render response elsewhere in the same view directly as UIComponent
reference available by #{foo}
. Here are several related questions where such a solution is been used in the answer:
Use an EL expression to pass a component ID to a composite component in JSF
(and that's only from the last month...)
When FIND
returns #VALUE!
, it is an error, not a string, so you can't compare FIND(...)
with "#VALUE!"
, you need to check if FIND
returns an error with ISERROR
. Also FIND
can work on multiple characters.
So a simplified and working version of your formula would be:
=IF(ISERROR(FIND("abc",A1))=FALSE, "Green", IF(ISERROR(FIND("xyz",A1))=FALSE, "Yellow", "Red"))
Or, to remove the double negations:
=IF(ISERROR(FIND("abc",A1)), IF(ISERROR(FIND("xyz",A1)), "Red", "Yellow"),"Green")
Here's a solution that works for both non-overlapping and overlapping occurrences. To clarify: an overlapping substring is one whose last character is identical to its first character.
def substr_count(st, sub):
# If a non-overlapping substring then just
# use the standard string `count` method
# to count the substring occurences
if sub[0] != sub[-1]:
return st.count(sub)
# Otherwise, create a copy of the source string,
# and starting from the index of the first occurence
# of the substring, adjust the source string to start
# from subsequent occurences of the substring and keep
# keep count of these occurences
_st = st[::]
start = _st.index(sub)
cnt = 0
while start is not None:
cnt += 1
try:
_st = _st[start + len(sub) - 1:]
start = _st.index(sub)
except (ValueError, IndexError):
return cnt
return cnt
I cannot help you much without a small (possibly reduced) snippit of the problem. If the problem is what I think it is then it's because a div by default takes up 100% width, and as such cannot be aligned.
What you may be after is to align the inline elements inside the div (such as text) with text-align:center; otherwise you may consider setting the div to display:inline-block;
If you do go down the inline-block route then you may have to consider my favorite IE hack.
width:100px;
display:inline-block;
zoom:1; //IE only
*display:inline; //IE only
Happy Coding :)
try this instead
Set TxtRng = ActiveWorkbook.Sheets("Game").Range("A1")
ADDITION
Maybe the file is corrupt - this has happened to me several times before and the only solution is to copy everything out into a new file.
Please can you try the following:
Does this run?
Sub varchanger()
With Excel.Application
.ScreenUpdating = True
.Calculation = Excel.xlCalculationAutomatic
.EnableEvents = True
End With
On Error GoTo Whoa:
Dim myBook As Excel.Workbook
Dim mySheet As Excel.Worksheet
Dim Rng As Excel.Range
Set myBook = Excel.Workbooks("MyFullyQualified.xlsm")
Set mySheet = myBook.Worksheets("mySheet")
Set Rng = mySheet.Range("A1")
'ActiveSheet.Unprotect
Rng.Value = "SubTotal"
Excel.Workbooks("MyFullyQualified.xlsm").Worksheets("mySheet").Range("A1").Value = "Asdf"
LetsContinue:
Exit Sub
Whoa:
MsgBox Err.Number
GoTo LetsContinue
End Sub
jQuery(document).ready(function(){
jQuery('#datetimepicker').datepicker();
})
I don't know your file-structure. I never include local files like this as I use relative URLs from the start rather than having to change everytime I'm ready to use the code, but it's likely one of the files isn't being loaded in. I've included the standard datepicker below using Google CDN's jQuery UI. Does your console log any resources not found?
I think your jQuery is loaded OK, because it's not telling you jQuery is not defined so it's one of your files.
BTW, PHP gets the home URL:
$home="http://" . $_SERVER['HTTP_HOST'].'/';
Demo code datepicker, jQuery UI:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#datetimepicker').datepicker();
})
</script>
<input id="datetimepicker" type="text">
var matches = new Array();
var allDom = document.getElementsByTagName("*");
for(var i =0; i < allDom.length; i++){
var d = allDom[i];
if(d["data-foo"] !== undefined) {
matches.push(d);
}
}
Not sure who dinged me with a -1, but here's the proof.
Here is a presentation on this topic that you might find interesting:
http://www.bytemining.com/2010/08/taking-r-to-the-limit-part-ii-large-datasets-in-r/
I haven't tried the discussed things myself, but the bigmemory
package seems very useful
You can use:
Handler handler = new Handler()
handler.postDelayed(new Runnable())
Or you can use:
handler.removeCallbacksAndMessages(null);
Docs
public final void removeCallbacksAndMessages (Object token)
Added in API level 1 Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.
Or you could also do like the following:
Handler handler = new Handler()
Runnable myRunnable = new Runnable() {
public void run() {
// do something
}
};
handler.postDelayed(myRunnable,zeit_dauer2);
Then:
handler.removeCallbacks(myRunnable);
Docs
public final void removeCallbacks (Runnable r)
Added in API level 1 Remove any pending posts of Runnable r that are in the message queue.
public final void removeCallbacks (Runnable r, Object token)
Edit:
Change this:
@Override
public void onClick(View v) {
Handler handler = new Handler();
Runnable myRunnable = new Runnable() {
To:
@Override
public void onClick(View v) {
handler = new Handler();
myRunnable = new Runnable() { /* ... */}
Because you have the below. Declared before onCreate
but you re-declared and then initialized it in onClick
leading to a NPE.
Handler handler; // declared before onCreate
Runnable myRunnable;
I recast Brajesh Kumar's answer above into Clojure as follows:
(defn open-browser
"Open a new browser (window or tab) viewing the document at this `uri`."
[uri]
(if (java.awt.Desktop/isDesktopSupported)
(let [desktop (java.awt.Desktop/getDesktop)]
(.browse desktop (java.net.URI. uri)))
(let [rt (java.lang.Runtime/getRuntime)]
(.exec rt (str "xdg-open " uri)))))
in case it's useful to anyone.
Please look at http://www.tldp.org/LDP/abs/html/parameter-substitution.html for examples
${parameter-default}, ${parameter:-default}
If parameter not set, use default. After the call, parameter is still not set.
Both forms are almost equivalent. The extra :
makes a difference only when parameter has been declared, but is null.
unset EGGS
echo 1 ${EGGS-spam} # 1 spam
echo 2 ${EGGS:-spam} # 2 spam
EGGS=
echo 3 ${EGGS-spam} # 3
echo 4 ${EGGS:-spam} # 4 spam
EGGS=cheese
echo 5 ${EGGS-spam} # 5 cheese
echo 6 ${EGGS:-spam} # 6 cheese
${parameter=default}, ${parameter:=default}
If parameter not set, set parameter value to default.
Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is null
# sets variable without needing to reassign
# colons suppress attempting to run the string
unset EGGS
: ${EGGS=spam}
echo 1 $EGGS # 1 spam
unset EGGS
: ${EGGS:=spam}
echo 2 $EGGS # 2 spam
EGGS=
: ${EGGS=spam}
echo 3 $EGGS # 3 (set, but blank -> leaves alone)
EGGS=
: ${EGGS:=spam}
echo 4 $EGGS # 4 spam
EGGS=cheese
: ${EGGS:=spam}
echo 5 $EGGS # 5 cheese
EGGS=cheese
: ${EGGS=spam}
echo 6 $EGGS # 6 cheese
${parameter+alt_value}, ${parameter:+alt_value}
If parameter set, use alt_value, else use null string. After the call, parameter value not changed.
Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is null
unset EGGS
echo 1 ${EGGS+spam} # 1
echo 2 ${EGGS:+spam} # 2
EGGS=
echo 3 ${EGGS+spam} # 3 spam
echo 4 ${EGGS:+spam} # 4
EGGS=cheese
echo 5 ${EGGS+spam} # 5 spam
echo 6 ${EGGS:+spam} # 6 spam
yes you need to call repaint(); revalidate(); when you call removeAll() then you have to call repaint() and revalidate()
Took some working, but I thougth my solution would be something to share as it is seems elegant as well as quite fast.
SELECT h.year, h.id, h.rate
FROM (
SELECT id,
SUBSTRING_INDEX(GROUP_CONCAT(CONCAT(id, '-', year) ORDER BY rate DESC), ',' , 5) AS l
FROM h
WHERE year BETWEEN 2000 AND 2009
GROUP BY id
ORDER BY id
) AS h_temp
LEFT JOIN h ON h.id = h_temp.id
AND SUBSTRING_INDEX(h_temp.l, CONCAT(h.id, '-', h.year), 1) != h_temp.l
Note that this example is specified for the purpose of the question and can be modified quite easily for other similar purposes.
Use snmp-interfaces.nse nmap script (written in lua) to get the MAC address of remote machine like this:
nmap -sU -p 161 -T4 -d -v -n -Pn --script snmp-interfaces 80.234.33.182
Completed NSE at 13:25, 2.69s elapsed Nmap scan report for 80.234.33.182 Host is up, received user-set (0.078s latency). Scanned at 2014-08-22 13:25:29 ???????? ????? (????) for 3s PORT STATE SERVICE REASON 161/udp open snmp udp-response | snmp-interfaces: | eth | MAC address: 00:50:60:03:81:c9 (Tandberg Telecom AS) | Type: ethernetCsmacd Speed: 10 Mbps | Status: up | Traffic stats: 1.27 Gb sent, 53.91 Mb received | lo | Type: softwareLoopback Speed: 0 Kbps | Status: up |_ Traffic stats: 4.10 Kb sent, 4.10 Kb received
I also encountered this problem, and I have to change the folder name from Chinese to English. Pity that current gradle build tool does not support Unicode names.
The other answer is correct, but for completeness, here are other ways:
List<SomeClass> list = mapper.readValue(jsonString, new TypeReference<List<SomeClass>>() { });
SomeClass[] array = mapper.readValue(jsonString, SomeClass[].class);
Install bootstrap using npm i --save bootstrap@version
.Now,go to nodemodules folder and from bootstrap folder copy the path of 'bootstrap.min.css.js' and paste the full path(like nodemodules/bootstrap/css/bootstrap.min.css.js
) in angular.json
under script tag file and re-run the server and to check whether the installation is successful run the program in any browser you like and press F12 you'll find a part of the window gets opened,now go to elements tab open head tag and if you see bootstrap in style tag,then your installation is successful.
C# does not support this. Hejlsberg has described the reasons for not implementing the feature in an interview with Bruce Eckel:
And it's not clear that the added complexity is worth the small yield that you get. If something you want to do is not directly supported in the constraint system, you can do it with a factory pattern. You could have a
Matrix<T>
, for example, and in thatMatrix
you would like to define a dot product method. That of course that means you ultimately need to understand how to multiply twoT
s, but you can't say that as a constraint, at least not ifT
isint
,double
, orfloat
. But what you could do is have yourMatrix
take as an argument aCalculator<T>
, and inCalculator<T>
, have a method calledmultiply
. You go implement that and you pass it to theMatrix
.
However, this leads to fairly convoluted code, where the user has to supply their own Calculator<T>
implementation, for each T
that they want to use. As long as it doesn’t have to be extensible, i.e. if you just want to support a fixed number of types, such as int
and double
, you can get away with a relatively simple interface:
var mat = new Matrix<int>(w, h);
(Minimal implementation in a GitHub Gist.)
However, as soon as you want the user to be able to supply their own, custom types, you need to open up this implementation so that the user can supply their own Calculator
instances. For instance, to instantiate a matrix that uses a custom decimal floating point implementation, DFP
, you’d have to write this code:
var mat = new Matrix<DFP>(DfpCalculator.Instance, w, h);
… and implement all the members for DfpCalculator : ICalculator<DFP>
.
An alternative, which unfortunately shares the same limitations, is to work with policy classes, as discussed in Sergey Shandar’s answer.
If it is read-only a good idea would be to create a table, then apply some really easy-but-powerful JQuery to that.
For simple alternative colour, try this simple JQuery.
If you need sorting, this JQuery plug-in simply rocks.
If you install the SDK, the offline documentation can be found in $ANDROID_SDK/docs/
.
Caling .Value2
is an expensive operation because it's a COM-interop call. I would instead read the entire range into an array and then loop through the array:
object[,] data = Range.Value2;
// Create new Column in DataTable
for (int cCnt = 1; cCnt <= Range.Columns.Count; cCnt++)
{
textBox3.Text = cCnt.ToString();
var Column = new DataColumn();
Column.DataType = System.Type.GetType("System.String");
Column.ColumnName = cCnt.ToString();
DT.Columns.Add(Column);
// Create row for Data Table
for (int rCnt = 1; rCnt <= Range.Rows.Count; rCnt++)
{
textBox2.Text = rCnt.ToString();
string CellVal = String.Empty;
try
{
cellVal = (string)(data[rCnt, cCnt]);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)
{
ConvertVal = (double)(data[rCnt, cCnt]);
cellVal = ConvertVal.ToString();
}
DataRow Row;
// Add to the DataTable
if (cCnt == 1)
{
Row = DT.NewRow();
Row[cCnt.ToString()] = cellVal;
DT.Rows.Add(Row);
}
else
{
Row = DT.Rows[rCnt + 1];
Row[cCnt.ToString()] = cellVal;
}
}
}
There are a couple of variables to set the max number of connections. Most likely, you're running out of file numbers first. Check ulimit -n. After that, there are settings in /proc, but those default to the tens of thousands.
More importantly, it sounds like you're doing something wrong. A single TCP connection ought to be able to use all of the bandwidth between two parties; if it isn't:
ping -s 1472
...)tc
iperf
Possibly I have misunderstood. Maybe you're doing something like Bittorrent, where you need lots of connections. If so, you need to figure out how many connections you're actually using (try netstat
or lsof
). If that number is substantial, you might:
ulimit -n
. Still, ~1000 connections (default on my system) is quite a few.iostat -x
?Also, if you are using a consumer-grade NAT router (Linksys, Netgear, DLink, etc.), beware that you may exceed its abilities with thousands of connections.
I hope this provides some help. You're really asking a networking question.
So .. quickest way is rename site config names ending in ".conf"
mv /etc/apache2/sites-available/mysite /etc/apache2/sites-available/mysite.conf
a2ensite mysite.conf
other notes on previous comments:
IncludeOptional wasn't introduced until apache 2.36 - making change above followed by restart on 2.2 will leave your server down!
also, version 2.2 a2ensite can't be hacked as described
as well, since your sites-available file is actually a configuration file, it should be named that way anyway..
In general do not restart services (webservers are one type of service):
Servers can run for many years - live update, reload config, etc.
The cloud doesn't mean you have to restart to load a configuration file.
When changing configuration of a service use "reload" not "restart".
restart stops the service then starts service - if there is a any problem in your change to the config, the service will not restart.
reload will give an error but the service never shuts down giving you a chance to fix the config error which could only be bad syntax.
debian or ubunto [service-name for this thread is apache2]
service {service-name} {start} {stop} {reload} ..
other os's left as an excersize for the reader.
npm install
from git bash did work for me.
After rebooting PC.
BCrypt is a very good library, and there is a Java port of it.
You need rawQuery method.
Example:
private final String MY_QUERY = "SELECT * FROM table_a a INNER JOIN table_b b ON a.id=b.other_id WHERE b.property_id=?";
db.rawQuery(MY_QUERY, new String[]{String.valueOf(propertyId)});
Use ? bindings instead of putting values into raw sql query.
You aren't building your formula right.
Worksheets("EmployeeCosts").Range("B" & var1a).Formula = "=SUM(H5:H" & var1a & ")"
This does the same as the following lines do:
Dim myFormula As String
myFormula = "=SUM(H5:H"
myFormula = myFormula & var1a
myformula = myformula & ")"
which is what you are trying to do.
Also, you want to have the =
at the beginning of the formala.
I stumbled upon this post recently and think that it needs an updated solution for the standard library's c++11 mutex (namely std::mutex).
I've pasted some code below (my first steps with a mutex - I learned concurrency on win32 with HANDLE, SetEvent, WaitForMultipleObjects etc).
Since it's my first attempt with std::mutex and friends, I'd love to see comments, suggestions and improvements!
#include <condition_variable>
#include <mutex>
#include <algorithm>
#include <thread>
#include <queue>
#include <chrono>
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
// these vars are shared among the following threads
std::queue<unsigned int> nNumbers;
std::mutex mtxQueue;
std::condition_variable cvQueue;
bool m_bQueueLocked = false;
std::mutex mtxQuit;
std::condition_variable cvQuit;
bool m_bQuit = false;
std::thread thrQuit(
[&]()
{
using namespace std;
this_thread::sleep_for(chrono::seconds(5));
// set event by setting the bool variable to true
// then notifying via the condition variable
m_bQuit = true;
cvQuit.notify_all();
}
);
std::thread thrProducer(
[&]()
{
using namespace std;
int nNum = 13;
unique_lock<mutex> lock( mtxQuit );
while ( ! m_bQuit )
{
while( cvQuit.wait_for( lock, chrono::milliseconds(75) ) == cv_status::timeout )
{
nNum = nNum + 13 / 2;
unique_lock<mutex> qLock(mtxQueue);
cout << "Produced: " << nNum << "\n";
nNumbers.push( nNum );
}
}
}
);
std::thread thrConsumer(
[&]()
{
using namespace std;
unique_lock<mutex> lock(mtxQuit);
while( cvQuit.wait_for(lock, chrono::milliseconds(150)) == cv_status::timeout )
{
unique_lock<mutex> qLock(mtxQueue);
if( nNumbers.size() > 0 )
{
cout << "Consumed: " << nNumbers.front() << "\n";
nNumbers.pop();
}
}
}
);
thrQuit.join();
thrProducer.join();
thrConsumer.join();
return 0;
}
Call the continuation with TaskScheduler.FromCurrentSynchronizationContext()
:
Task UITask= task.ContinueWith(() =>
{
this.TextBlock1.Text = "Complete";
}, TaskScheduler.FromCurrentSynchronizationContext());
This is suitable only if the current execution context is on the UI thread.
Use some tag, to aligning the input element. So
<form>
<div>
<input>
<br />
<input>
</div>
</form>
.mydiv
{
width: 500px;
height: 250px;
display: table;
text-align: right;
}
Your code experiences a case where the Automatic Semicolon Insertion (ASI) process doesn't happen.
You should never rely on ASI. You should use semicolons to properly separate statements:
var postTypes = new Array('hello', 'there'); // <--- Place a semicolon here!!
(function() { alert('hello there') })();
Your code was actually trying to invoke the array object.
if you are using android studio you should run the android studio through the command prompt(in windows) or terminal(in UNIX base OS) so you can see more detail about this error in command prompt window.
img{display: flex; max-width: 80%; margin: auto;}
This is working for me. You can also use display: table in this case. Moreover, if you don't want to stick to this approach you can use the following:
img{position: relative; left: 50%;}
~/.gradle/gradle.properties:
mavenUser=admin
mavenPassword=admin123
build.gradle:
...
authentication(userName: mavenUser, password: mavenPassword)
You can set a custom baud rate using the stty
command on Linux. For example, to set a custom baud rate of 567890 on your serial port /dev/ttyX0, use the command:
stty -F /dev/ttyX0 567890
And if you want to avoid the restart of the application, you can move out the appSettings
section:
<appSettings configSource="Config\appSettings.config"/>
to a separate file. And in combination with ConfigurationSaveMode.Minimal
var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
config.Save(ConfigurationSaveMode.Minimal);
you can continue to use the appSettings
section as the store for various settings without causing application restarts and without the need to use a file with a different format than the normal appSettings section.
I know this is old but this answer came up in search results. For the next guy - the proposed and accepted answer works, however the code initially submitted in the question is lower-level than it needs to be. Nobody got time for that.
//one-line post request/response...
response, err := http.PostForm(APIURL, url.Values{
"ln": {c.ln},
"ip": {c.ip},
"ua": {c.ua}})
//okay, moving on...
if err != nil {
//handle postform error
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
//handle read response error
}
fmt.Printf("%s\n", string(body))
In postgres simply : TO_CHAR(timestamp_column, 'DD/MM/YYYY') as submission_date
Longest Increasing Subsequence(Java)
import java.util.*;
class ChainHighestValue implements Comparable<ChainHighestValue>{
int highestValue;
int chainLength;
ChainHighestValue(int highestValue,int chainLength) {
this.highestValue = highestValue;
this.chainLength = chainLength;
}
@Override
public int compareTo(ChainHighestValue o) {
return this.chainLength-o.chainLength;
}
}
public class LongestIncreasingSubsequenceLinkedList {
private static LinkedList<Integer> LongestSubsequent(int arr[], int size){
ArrayList<LinkedList<Integer>> seqList=new ArrayList<>();
ArrayList<ChainHighestValue> valuePairs=new ArrayList<>();
for(int i=0;i<size;i++){
int currValue=arr[i];
if(valuePairs.size()==0){
LinkedList<Integer> aList=new LinkedList<>();
aList.add(arr[i]);
seqList.add(aList);
valuePairs.add(new ChainHighestValue(arr[i],1));
}else{
try{
ChainHighestValue heighestIndex=valuePairs.stream().filter(e->e.highestValue<currValue).max(ChainHighestValue::compareTo).get();
int index=valuePairs.indexOf(heighestIndex);
seqList.get(index).add(arr[i]);
heighestIndex.highestValue=arr[i];
heighestIndex.chainLength+=1;
}catch (Exception e){
LinkedList<Integer> aList=new LinkedList<>();
aList.add(arr[i]);
seqList.add(aList);
valuePairs.add(new ChainHighestValue(arr[i],1));
}
}
}
ChainHighestValue heighestIndex=valuePairs.stream().max(ChainHighestValue::compareTo).get();
int index=valuePairs.indexOf(heighestIndex);
return seqList.get(index);
}
public static void main(String[] args){
int arry[]={5,1,3,6,11,30,32,5,3,73,79};
//int arryB[]={3,1,5,2,6,4,9};
LinkedList<Integer> LIS=LongestSubsequent(arry, arry.length);
System.out.println("Longest Incrementing Subsequence:");
for(Integer a: LIS){
System.out.print(a+" ");
}
}
}
This worked for me ::-
mysql --host=hostNameorIp --user=username --password=password
or
mysql --host=hostNameorIp --user=username --password=password database_name
The first one creates a single lambda function and calls it ten times.
The second one doesn't call the function. It creates 10 different lambda functions. It puts all of those in a list. To make it equivalent to the first you need:
[(lambda x: x*x)(x) for x in range(10)]
Or better yet:
[x*x for x in range(10)]
Start By going through the Fingerpaint demo in the sdk sample.
Another Sample:
public class MainActivity extends Activity {
DrawingView dv ;
private Paint mPaint;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dv = new DrawingView(this);
setContentView(dv);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.GREEN);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(12);
}
public class DrawingView extends View {
public int width;
public int height;
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
Context context;
private Paint circlePaint;
private Path circlePath;
public DrawingView(Context c) {
super(c);
context=c;
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
circlePaint = new Paint();
circlePath = new Path();
circlePaint.setAntiAlias(true);
circlePaint.setColor(Color.BLUE);
circlePaint.setStyle(Paint.Style.STROKE);
circlePaint.setStrokeJoin(Paint.Join.MITER);
circlePaint.setStrokeWidth(4f);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap( mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath( mPath, mPaint);
canvas.drawPath( circlePath, circlePaint);
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
private void touch_start(float x, float y) {
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touch_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
mX = x;
mY = y;
circlePath.reset();
circlePath.addCircle(mX, mY, 30, Path.Direction.CW);
}
}
private void touch_up() {
mPath.lineTo(mX, mY);
circlePath.reset();
// commit the path to our offscreen
mCanvas.drawPath(mPath, mPaint);
// kill this so we don't double draw
mPath.reset();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
}
}
Snap shot
Explanation :
You are creating a view class then extends View. You override the onDraw(). You add the path of where finger touches and moves. You override the onTouch() of this purpose. In your onDraw() you draw the paths using the paint of your choice. You should call invalidate() to refresh the view.
To choose options you can click menu and choose the options.
The below can be used as a reference. You can modify the below according to your needs.
public class FingerPaintActivity extends Activity
implements ColorPickerDialog.OnColorChangedListener {
MyView mv;
AlertDialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mv= new MyView(this);
mv.setDrawingCacheEnabled(true);
mv.setBackgroundResource(R.drawable.afor);//set the back ground if you wish to
setContentView(mv);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(0xFFFF0000);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(20);
mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 },
0.4f, 6, 3.5f);
mBlur = new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL);
}
private Paint mPaint;
private MaskFilter mEmboss;
private MaskFilter mBlur;
public void colorChanged(int color) {
mPaint.setColor(color);
}
public class MyView extends View {
private static final float MINP = 0.25f;
private static final float MAXP = 0.75f;
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
Context context;
public MyView(Context c) {
super(c);
context=c;
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mPath, mPaint);
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
private void touch_start(float x, float y) {
//showDialog();
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touch_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
mX = x;
mY = y;
}
}
private void touch_up() {
mPath.lineTo(mX, mY);
// commit the path to our offscreen
mCanvas.drawPath(mPath, mPaint);
// kill this so we don't double draw
mPath.reset();
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SCREEN));
//mPaint.setMaskFilter(null);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
}
private static final int COLOR_MENU_ID = Menu.FIRST;
private static final int EMBOSS_MENU_ID = Menu.FIRST + 1;
private static final int BLUR_MENU_ID = Menu.FIRST + 2;
private static final int ERASE_MENU_ID = Menu.FIRST + 3;
private static final int SRCATOP_MENU_ID = Menu.FIRST + 4;
private static final int Save = Menu.FIRST + 5;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, COLOR_MENU_ID, 0, "Color").setShortcut('3', 'c');
menu.add(0, EMBOSS_MENU_ID, 0, "Emboss").setShortcut('4', 's');
menu.add(0, BLUR_MENU_ID, 0, "Blur").setShortcut('5', 'z');
menu.add(0, ERASE_MENU_ID, 0, "Erase").setShortcut('5', 'z');
menu.add(0, SRCATOP_MENU_ID, 0, "SrcATop").setShortcut('5', 'z');
menu.add(0, Save, 0, "Save").setShortcut('5', 'z');
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
mPaint.setXfermode(null);
mPaint.setAlpha(0xFF);
switch (item.getItemId()) {
case COLOR_MENU_ID:
new ColorPickerDialog(this, this, mPaint.getColor()).show();
return true;
case EMBOSS_MENU_ID:
if (mPaint.getMaskFilter() != mEmboss) {
mPaint.setMaskFilter(mEmboss);
} else {
mPaint.setMaskFilter(null);
}
return true;
case BLUR_MENU_ID:
if (mPaint.getMaskFilter() != mBlur) {
mPaint.setMaskFilter(mBlur);
} else {
mPaint.setMaskFilter(null);
}
return true;
case ERASE_MENU_ID:
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
mPaint.setAlpha(0x80);
return true;
case SRCATOP_MENU_ID:
mPaint.setXfermode(new PorterDuffXfermode(
PorterDuff.Mode.SRC_ATOP));
mPaint.setAlpha(0x80);
return true;
case Save:
AlertDialog.Builder editalert = new AlertDialog.Builder(FingerPaintActivity.this);
editalert.setTitle("Please Enter the name with which you want to Save");
final EditText input = new EditText(FingerPaintActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT);
input.setLayoutParams(lp);
editalert.setView(input);
editalert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String name= input.getText().toString();
Bitmap bitmap = mv.getDrawingCache();
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
File file = new File("/sdcard/"+name+".png");
try
{
if(!file.exists())
{
file.createNewFile();
}
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 10, ostream);
ostream.close();
mv.invalidate();
}
catch (Exception e)
{
e.printStackTrace();
}finally
{
mv.setDrawingCacheEnabled(false);
}
}
});
editalert.show();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Color Picker
public class ColorPickerDialog extends Dialog {
public interface OnColorChangedListener {
void colorChanged(int color);
}
private OnColorChangedListener mListener;
private int mInitialColor;
private static class ColorPickerView extends View {
private Paint mPaint;
private Paint mCenterPaint;
private final int[] mColors;
private OnColorChangedListener mListener;
ColorPickerView(Context c, OnColorChangedListener l, int color) {
super(c);
mListener = l;
mColors = new int[] {
0xFFFF0000, 0xFFFF00FF, 0xFF0000FF, 0xFF00FFFF, 0xFF00FF00,
0xFFFFFF00, 0xFFFF0000
};
Shader s = new SweepGradient(0, 0, mColors, null);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setShader(s);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(32);
mCenterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mCenterPaint.setColor(color);
mCenterPaint.setStrokeWidth(5);
}
private boolean mTrackingCenter;
private boolean mHighlightCenter;
@Override
protected void onDraw(Canvas canvas) {
float r = CENTER_X - mPaint.getStrokeWidth()*0.5f;
canvas.translate(CENTER_X, CENTER_X);
canvas.drawOval(new RectF(-r, -r, r, r), mPaint);
canvas.drawCircle(0, 0, CENTER_RADIUS, mCenterPaint);
if (mTrackingCenter) {
int c = mCenterPaint.getColor();
mCenterPaint.setStyle(Paint.Style.STROKE);
if (mHighlightCenter) {
mCenterPaint.setAlpha(0xFF);
} else {
mCenterPaint.setAlpha(0x80);
}
canvas.drawCircle(0, 0,
CENTER_RADIUS + mCenterPaint.getStrokeWidth(),
mCenterPaint);
mCenterPaint.setStyle(Paint.Style.FILL);
mCenterPaint.setColor(c);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(CENTER_X*2, CENTER_Y*2);
}
private static final int CENTER_X = 100;
private static final int CENTER_Y = 100;
private static final int CENTER_RADIUS = 32;
private int floatToByte(float x) {
int n = java.lang.Math.round(x);
return n;
}
private int pinToByte(int n) {
if (n < 0) {
n = 0;
} else if (n > 255) {
n = 255;
}
return n;
}
private int ave(int s, int d, float p) {
return s + java.lang.Math.round(p * (d - s));
}
private int interpColor(int colors[], float unit) {
if (unit <= 0) {
return colors[0];
}
if (unit >= 1) {
return colors[colors.length - 1];
}
float p = unit * (colors.length - 1);
int i = (int)p;
p -= i;
// now p is just the fractional part [0...1) and i is the index
int c0 = colors[i];
int c1 = colors[i+1];
int a = ave(Color.alpha(c0), Color.alpha(c1), p);
int r = ave(Color.red(c0), Color.red(c1), p);
int g = ave(Color.green(c0), Color.green(c1), p);
int b = ave(Color.blue(c0), Color.blue(c1), p);
return Color.argb(a, r, g, b);
}
private int rotateColor(int color, float rad) {
float deg = rad * 180 / 3.1415927f;
int r = Color.red(color);
int g = Color.green(color);
int b = Color.blue(color);
ColorMatrix cm = new ColorMatrix();
ColorMatrix tmp = new ColorMatrix();
cm.setRGB2YUV();
tmp.setRotate(0, deg);
cm.postConcat(tmp);
tmp.setYUV2RGB();
cm.postConcat(tmp);
final float[] a = cm.getArray();
int ir = floatToByte(a[0] * r + a[1] * g + a[2] * b);
int ig = floatToByte(a[5] * r + a[6] * g + a[7] * b);
int ib = floatToByte(a[10] * r + a[11] * g + a[12] * b);
return Color.argb(Color.alpha(color), pinToByte(ir),
pinToByte(ig), pinToByte(ib));
}
private static final float PI = 3.1415926f;
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX() - CENTER_X;
float y = event.getY() - CENTER_Y;
boolean inCenter = java.lang.Math.sqrt(x*x + y*y) <= CENTER_RADIUS;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mTrackingCenter = inCenter;
if (inCenter) {
mHighlightCenter = true;
invalidate();
break;
}
case MotionEvent.ACTION_MOVE:
if (mTrackingCenter) {
if (mHighlightCenter != inCenter) {
mHighlightCenter = inCenter;
invalidate();
}
} else {
float angle = (float)java.lang.Math.atan2(y, x);
// need to turn angle [-PI ... PI] into unit [0....1]
float unit = angle/(2*PI);
if (unit < 0) {
unit += 1;
}
mCenterPaint.setColor(interpColor(mColors, unit));
invalidate();
}
break;
case MotionEvent.ACTION_UP:
if (mTrackingCenter) {
if (inCenter) {
mListener.colorChanged(mCenterPaint.getColor());
}
mTrackingCenter = false; // so we draw w/o halo
invalidate();
}
break;
}
return true;
}
}
public ColorPickerDialog(Context context,
OnColorChangedListener listener,
int initialColor) {
super(context);
mListener = listener;
mInitialColor = initialColor;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OnColorChangedListener l = new OnColorChangedListener() {
public void colorChanged(int color) {
mListener.colorChanged(color);
dismiss();
}
};
setContentView(new ColorPickerView(getContext(), l, mInitialColor));
setTitle("Pick a Color");
}
}
In case anyone had the same problem: check this as @PravinS suggested. I used the exact same code as shown there and it worked for me perfectly.
This is the relevant part of the server code that helped:
if (isset($_POST['btnUpload']))
{
$url = "URL_PATH of upload.php"; // e.g. http://localhost/myuploader/upload.php // request URL
$filename = $_FILES['file']['name'];
$filedata = $_FILES['file']['tmp_name'];
$filesize = $_FILES['file']['size'];
if ($filedata != '')
{
$headers = array("Content-Type:multipart/form-data"); // cURL headers for file uploading
$postfields = array("filedata" => "@$filedata", "filename" => $filename);
$ch = curl_init();
$options = array(
CURLOPT_URL => $url,
CURLOPT_HEADER => true,
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $postfields,
CURLOPT_INFILESIZE => $filesize,
CURLOPT_RETURNTRANSFER => true
); // cURL options
curl_setopt_array($ch, $options);
curl_exec($ch);
if(!curl_errno($ch))
{
$info = curl_getinfo($ch);
if ($info['http_code'] == 200)
$errmsg = "File uploaded successfully";
}
else
{
$errmsg = curl_error($ch);
}
curl_close($ch);
}
else
{
$errmsg = "Please select the file";
}
}
html form should look something like:
<form action="uploadpost.php" method="post" name="frmUpload" enctype="multipart/form-data">
<tr>
<td>Upload</td>
<td align="center">:</td>
<td><input name="file" type="file" id="file"/></td>
</tr>
<tr>
<td> </td>
<td align="center"> </td>
<td><input name="btnUpload" type="submit" value="Upload" /></td>
</tr>
Link for adding through JS https://www.youtube.com/watch?v=idyyQ23joy0
Please see the below link as well. This would help you add the rows dynamically on the fly: https://www.lynda.com/C-tutorials/Adding-data-HTML-tables-runtime/161815/366843-4.html
This is quite simple the way I resolved this problem:
your problem is resolved .
If you are after the side effects that happen within the loop, I'd personally go for the range()
approach.
If you care about the result of whatever functions you call within the loop, I'd go for a list comprehension or map
approach. Something like this:
def f(n):
return n * n
results = [f(i) for i in range(50)]
# or using map:
results = map(f, range(50))
There's now a much simpler solution than when this question was originally asked, five years ago. A CSS Flexbox makes the two column layout originally asked for easy. This is the bare bones equivalent of the table in the original question:
<div style="display: flex">
<div>AAA</div>
<div>BBB</div>
</div>
One of the nice things about a Flexbox is that it lets you easily specify how child elements should shrink and grow to adjust to the container size. I will expand on the above example to make the box the full width of the page, make the left column a minimum of 75px wide, and grow the right column to capture the leftover space. I will also pull the style into its own proper block, assign some background colors so that the columns are apparent, and add legacy Flex support for some older browsers.
<style type="text/css">
.flexbox {
display: -ms-flex;
display: -webkit-flex;
display: flex;
width: 100%;
}
.left {
background: #a0ffa0;
min-width: 75px;
flex-grow: 0;
}
.right {
background: #a0a0ff;
flex-grow: 1;
}
</style>
...
<div class="flexbox">
<div class="left">AAA</div>
<div class="right">BBB</div>
</div>
Flex is relatively new, and so if you're stuck having to support IE 8 and IE 9 you can't use it. However, as of this writing, http://caniuse.com/#feat=flexbox indicates at least partial support by browsers used by 94.04% of the market.
By influencing from getpsyched's answer, I created a generic method which checks column value by its name
public static T SafeGet<T>(this System.Data.SqlClient.SqlDataReader reader, string nameOfColumn)
{
var indexOfColumn = reader.GetOrdinal(nameOfColumn);
return reader.IsDBNull(indexOfColumn) ? default(T) : reader.GetFieldValue<T>(indexOfColumn);
}
Usage:
var myVariable = SafeGet<string>(reader, "NameOfColumn")
If you're giving the same seed, that's normal. That's an important feature allowing tests.
Check this to understand pseudo random generation and seeds:
A pseudorandom number generator (PRNG), also known as a deterministic random bit generator DRBG, is an algorithm for generating a sequence of numbers that approximates the properties of random numbers. The sequence is not truly random in that it is completely determined by a relatively small set of initial values, called the PRNG's state, which includes a truly random seed.
If you want to have different sequences (the usual case when not tuning or debugging the algorithm), you should call the zero argument constructor which uses the nanoTime to try to get a different seed every time. This Random
instance should of course be kept outside of your method.
Your code should probably be like this:
private Random generator = new Random();
double randomGenerator() {
return generator.nextDouble()*0.5;
}
Add m.Ename
to your SELECT
query:
select distinct e.Ename as Employee, m.mgr as reports_to, m.Ename as Manager
from EMPLOYEES e
inner join Employees m on e.mgr = m.EmpID;
I had faced similar issue with Angular4 and Jasmine unit tests; below given solution worked for me
Add below import statement
import { APP_BASE_HREF } from '@angular/common';
Add below statement for TestBed configuration:
TestBed.configureTestingModule({
providers: [
{ provide: APP_BASE_HREF, useValue : '/' }
]
})
If you are using this for Angular, then export a function via a named export. Such as:
function someFunc(){}
export { someFunc as someFuncName }
otherwise, Angular will complain that object is not a function.
You're looking for Enumerable#select (also called find_all
):
@fathers.select {|father| father["age"] > 35 }
# => [ { "age" => 40, "father" => "Bob" },
# { "age" => 50, "father" => "Batman" } ]
Per the documentation, it "returns an array containing all elements of [the enumerable, in this case @fathers
] for which block is not false."
According to PEP8, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes. You should also try to put the line break after boolean operators.
Further to this, if you're using a code style check such as pycodestyle, the next logical line needs to have different indentation to your code block.
For example:
if (abcdefghijklmnopqrstuvwxyz > some_other_long_identifier and
here_is_another_long_identifier != and_finally_another_long_name):
# ... your code here ...
pass
make as usual... Just make sure you have it in your path and correct Makefile
If you want "insert or replace" semantics, use this syntax:
A[key] = value; // <-- insert or replace semantics
It's more efficient and readable than calls involving "ContainsKey()" or "Remove()" prior to "Add()".
So in your case:
rct3Features[items[0]] = items[1];
It is SUBSTITUTE(B1," ","")
, not REPLACE(xx;xx;xx)
.
Say you had some URL that gave you JSON data like:
{'field': 'value'}
...and you had a similar URL except it used JSONP, to which you passed the callback function name 'myCallback' (usually done by giving it a query parameter called 'callback', e.g. http://example.com/dataSource?callback=myCallback
). Then it would return:
myCallback({'field':'value'})
...which is not just an object, but is actually code that can be executed. So if you define a function elsewhere in your page called myFunction
and execute this script, it will be called with the data from the URL.
The cool thing about this is: you can create a script tag and use your URL (complete with callback
parameter) as the src
attribute, and the browser will run it. That means you can get around the 'same-origin' security policy (because browsers allow you to run script tags from sources other than the domain of the page).
This is what jQuery does when you make an ajax request (using .ajax
with 'jsonp' as the value for the dataType
property). E.g.
$.ajax({
url: 'http://example.com/datasource',
dataType: 'jsonp',
success: function(data) {
// your code to handle data here
}
});
Here, jQuery takes care of the callback function name and query parameter - making the API identical to other ajax calls. But unlike other types of ajax requests, as mentioned, you're not restricted to getting data from the same origin as your page.
You could use GSON, using Gradle Build.gradle :
implementation 'com.google.code.gson:gson:2.8.0'
Then in your code, for example pairs of string/boolean with Kotlin :
val nestedData = HashMap<String,Boolean>()
for (i in 0..29) {
nestedData.put(i.toString(), true)
}
val gson = Gson()
val jsonFromMap = gson.toJson(nestedData)
Adding to SharedPrefs :
val sharedPrefEditor = context.getSharedPreferences(_prefName, Context.MODE_PRIVATE).edit()
sharedPrefEditor.putString("sig_types", jsonFromMap)
sharedPrefEditor.apply()
Now to retrieve data :
val gson = Gson()
val sharedPref: SharedPreferences = context.getSharedPreferences(_prefName, Context.MODE_PRIVATE)
val json = sharedPref.getString("sig_types", "false")
val type = object : TypeToken<Map<String, Boolean>>() {}.type
val map = gson.fromJson(json, type) as LinkedTreeMap<String,Boolean>
for (key in map.keys) {
Log.i("myvalues", key.toString() + map.get(key).toString())
}
C:\Program Files (x86)\Microsoft Visual Studio (Your Version Here)\Common7\IDE
Also you should know that you can force TLS v1.2 for Android 4.0 devices that don't have it enabled by default:
Put this code in onCreate() of your Application file:
try {
ProviderInstaller.installIfNeeded(getApplicationContext());
SSLContext sslContext;
sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, null, null);
sslContext.createSSLEngine();
} catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException
| NoSuchAlgorithmException | KeyManagementException e) {
e.printStackTrace();
}
You are getting that error because an application with a package name same as your application already exists. If you are sure that you have not installed the same application before, change the package name and try.
Else wise, here is what you can do:
This regex works perfectly:
bool IsValidEmail(string email)
{
return Regex.IsMatch(email, @"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*@((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))\z");
}
Use your developer's tool of choice and check if the tr
, td
or img
has any padding or margins.
As stated multiple times, inversion is achieved by the -v
option to grep
. Let me add the (hopefully amusing) note that you could have figured this out yourself by grepping through the grep
help text:
grep --help | grep invert
-v, --invert-match select non-matching lines
This is an alternative:
- name: Install this only for local dev machine
pip: name=pyramid
delegate_to: localhost
Unfortunately I have a unique build (stuck with Gentoo for the moment) of PHP 5.5, and what I found was that
$xml->tagName['attribute']
was the only solution that worked. I tried all of Bora's methods above, including the 'Right & Quick' format, and they all failed.
The fact that this is the easiest format is a plus, but didn't enjoy thinking I was insane trying all of the formats others were saying worked.
Njoy for what its worth (did I mention unique build?).
To stick with the Maven terms:
http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html#Lifecycle_Reference
It's HTML character references for encoding a character by its decimal code point
Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe
int cannot be null. If you are not assigning any value to int default value will be 0. If you want to check for null then make int as Integer in declaration. Then Integer object can be null. So, you can check where it is null or not. Even in javax bean validation you won't be able to get error for @NotNull annotation until the variable is declared as Integer.
The problem is that the first argument passed to class methods in python is always a copy of the class instance on which the method is called, typically labelled self
. If the class is declared thus:
class foo(object):
def foodo(self, thing=None, thong='not underwear'):
print thing if thing else "nothing"
print 'a thong is',thong
it behaves as expected.
Explanation:
Without self
as the first parameter, when myfoo.foodo(thing="something")
is executed, the foodo
method is called with arguments (myfoo, thing="something")
. The instance myfoo
is then assigned to thing
(since thing
is the first declared parameter), but python also attempts to assign "something"
to thing
, hence the Exception.
To demonstrate, try running this with the original code:
myfoo.foodo("something")
print
print myfoo
You'll output like:
<__main__.foo object at 0x321c290>
a thong is something
<__main__.foo object at 0x321c290>
You can see that 'thing' has been assigned a reference to the instance 'myfoo' of the class 'foo'. This section of the docs explains how function arguments work a bit more.
This is not exactly showing you which rows are locked, but this may helpful to you.
You can check which statements are blocked by running this:
select cmd,* from sys.sysprocesses
where blocked > 0
It will also tell you what each block is waiting on. So you can trace that all the way up to see which statement caused the first block that caused the other blocks.
Edit to add comment from @MikeBlandford:
The blocked column indicates the spid of the blocking process. You can run kill {spid} to fix it.
select partition_name,column_name,high_value,partition_position
from ALL_TAB_PARTITIONS a , ALL_PART_KEY_COLUMNS b
where table_name='YOUR_TABLE' and a.table_name = b.name;
This query lists the column name used as key and the allowed values. make sure, you insert the allowed values(high_value
). Else, if default partition is defined, it would go there.
EDIT:
I presume, your TABLE DDL would be like this.
CREATE TABLE HE0_DT_INF_INTERFAZ_MES
(
COD_PAIS NUMBER,
FEC_DATA NUMBER,
INTERFAZ VARCHAR2(100)
)
partition BY RANGE(COD_PAIS, FEC_DATA)
(
PARTITION PDIA_98_20091023 VALUES LESS THAN (98,20091024)
);
Which means I had created a partition with multiple columns which holds value less than the composite range (98,20091024);
That is first COD_PAIS <= 98
and Also FEC_DATA < 20091024
Combinations And Result:
98, 20091024 FAIL
98, 20091023 PASS
99, ******** FAIL
97, ******** PASS
< 98, ******** PASS
So the below INSERT
fails with ORA-14400; because (98,20091024)
in INSERT
is EQUAL to the one in DDL
but NOT less than it.
SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
VALUES(98, 20091024, 'CTA'); 2
INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
*
ERROR at line 1:
ORA-14400: inserted partition key does not map to any partition
But, we I attempt (97,20091024), it goes through
SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
2 VALUES(97, 20091024, 'CTA');
1 row created.
First method you can try this
$department->department_name = $request->department_name;
$department->status = $request->status;
$department->save();
Another way to insert records into the database with create function
$department = new Department;
// Another Way to insert records
$department->create($request->all());
return redirect('admin/departments');
You need to set the filledby in Department model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Department extends Model
{
protected $fillable = ['department_name','status'];
}
Whenever I need this for just one cell, I use this:
with pd.option_context('display.max_colwidth', None):
display(df)
From the jQuery API Document
While JavaScript provides the
load
event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to.ready()
is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the
load
event instead.
Answer to the second question -
No, they are identical as long as you are not using jQuery in no conflict mode.
--device
works until your USB device gets unplugged/replugged and then it stops working. You have to use cgroup devices.allow get around it.
You could just use -v /dev:/dev
but that's unsafe as it maps all the devices from your host into the container, including raw disk devices and so forth. Basically this allows the container to gain root on the host, which is usually not what you want.
Using the cgroups approach is better in that respect and works on devices that get added after the container as started.
See details here: Accessing USB Devices In Docker without using --privileged
It's a bit hard to paste, but in a nutshell, you need to get the major number for your character device and send that to cgroup:
189 is the major number of /dev/ttyUSB*, which you can get with 'ls -l'. It may be different on your system than on mine:
root@server:~# echo 'c 189:* rwm' > /sys/fs/cgroup/devices/docker/$A*/devices.allow
(A contains the docker containerID)
Then start your container like this:
docker run -v /dev/bus:/dev/bus:ro -v /dev/serial:/dev/serial:ro -i -t --entrypoint /bin/bash debian:amd64
without doing this, any newly plugged or rebooting device after the container started, will get a new bus ID and will not be allowed access in the container.
Additionally, for our Android friends (API Level 8):
import android.util.Base64
...
Base64.encodeToString(bytes, Base64.DEFAULT);
For me it was because 2 linux VMs were both mapped to the same home file system. One VM was running git-1.7.1 an the other was running git-2.14
The VM running git-1.7.1 would always show 4 files as changed (even thought the contents and line endings were identical).
Once 'git status' was run on the VM running g-2.14, then both VMs would start reporting the repository as clean. 'git status' has side effects. It is not an immutable operation. And git-1.7.1 does not understand the world in the same way that git-2+ does.
is just going to look for a div with class="outer inner", is that correct?
No, '.outer .inner'
will look for all elements with the .inner class that also have an element with the .outer class as an ancestor. '.outer.inner'
(no space) would give the results you're thinking of.
'.outer > .inner'
will look for immediate children of an element with the .outer class for elements with the .inner class.
Both '.outer .inner'
and '.outer > .inner'
should work for your example, although the selectors are fundamentally different and you should be wary of this.
I know I'm late to the party but I thought I'd add what I ended up using for this - which is to simply check if the file upload input does not contain a truthy value with the not operator & JQuery like so:
if (!$('#videoUploadFile').val()) {
alert('Please Upload File');
}
Note that if this is in a form, you may also want to wrap it with the following handler to prevent the form from submitting:
$(document).on("click", ":submit", function (e) {
if (!$('#videoUploadFile').val()) {
e.preventDefault();
alert('Please Upload File');
}
}
I know this is not the problem you had, however another reason this could happen is you have a non background thread open in your application.
using System;
using System.Threading;
using System.Windows.Forms;
namespace Sandbox_Form
{
static class Program
{
private static Thread thread;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
thread = new Thread(BusyWorkThread);
thread.IsBackground = false;
thread.Start();
Application.Run(new Form());
}
public static void BusyWorkThread()
{
while (true)
{
Thread.Sleep(1000);
}
}
}
}
When IsBackground
is false
it will keep your program open till the thread completes, if you set IsBackground
to true
the thread will not keep the program open. Things like BackgroundWoker
, ThreadPool
, and Task
all internally use a thread with IsBackground
set to true
.
MessageBox.Show(" Value at 0,0" + DataGridView1.Rows[0].Cells[0].Value );
What is the exact error message? #1062 means duplicate entry violating a primary key constraint for a column -- which boils down to the point that you cannot have two of the same values in the column. The error message should tell you which of your columns is constrained, I'm guessing "shares".
Although side_effect
can achieve the goal, it is not so convenient to setup side_effect
function for each test case.
I write a lightweight Mock (which is called NextMock) to enhance the built-in mock to address this problem, here is a simple example:
from nextmock import Mock
m = Mock()
m.with_args(1, 2, 3).returns(123)
assert m(1, 2, 3) == 123
assert m(3, 2, 1) != 123
It also supports argument matcher:
from nextmock import Arg, Mock
m = Mock()
m.with_args(1, 2, Arg.Any).returns(123)
assert m(1, 2, 1) == 123
assert m(1, 2, "123") == 123
Hope this package could make testing more pleasant. Feel free to give any feedback.
Try this:
select col1, col2, 'ABC' as col3 from Table1 where col1 = 0;
You could use penlight library. This has a function for splitting string using delimiter which outputs list.
It has implemented many of the function that we may need while programming and missing in Lua.
Here is the sample for using it.
>
> stringx = require "pl.stringx"
>
> str = "welcome to the world of lua"
>
> arr = stringx.split(str, " ")
>
> arr
{welcome,to,the,world,of,lua}
>
You could do something like this:
htmlComponent.ts
htmlVariable: string = "<b>Some html.</b>";
//this is html in TypeScript code that you need to display
htmlComponent.html
<div [innerHtml]="htmlVariable"></div>
//this is how you display html code from TypeScript in your html
In Bootstrap v5 use: data-bs-interval="false"
<div id="carouselExampleCaptions" class="carousel" data-bs-ride="carousel" data-bs-interval="false">
Refer to this link: As there are various options to shut the warning off depending on the minSdkVersion, it is set below 20:
android {
defaultConfig {
...
minSdkVersion 15
targetSdkVersion 26
multiDexEnabled true
}
... }
dependencies { compile 'com.android.support:multidex:1.0.3' }
If you have a minSdkVersion greater than 20 in your build.gradle set use the following to shut down the warning:
android {
defaultConfig {
...
minSdkVersion 21
targetSdkVersion 26
multiDexEnabled true
}
... }
Update dependencies as follows:
dependencies {
implementation 'com.android.support:multidex:1.0.3'
}
Again the only difference is the keywords in dependencies:
minSdkVersion below 20: use compile
minSdkVersion above 20: use implementation
This is a great help. The code
UPDATE tbl_b b
SET ( column1, column2, column3)
= (a.column1, a.column2, a.column3)
FROM tbl_a a
WHERE b.id = 1
AND a.id = b.id;
works perfectly.
noted that you need a bracket "" in
From "tbl_a" a
to make it work.
I had to do this recently as well for both Mac and Linux OS's and after browsing through many posts and trying many things out, in my particular opinion I never got to where I wanted to which is: a simple enough to understand solution using well known and standard commands with simple patterns, one liner, portable, expandable to add in more constraints. Then I tried to looked at it with a different perspective, that's when I realized i could do without the "one liner" option if a "2-liner" met the rest of my criteria. At the end I came up with this solution I like that works in both Ubuntu and Mac which i wanted to share with everyone:
insertLine=$(( $(grep -n "foo" sample.txt | cut -f1 -d: | head -1) + 1 ))
sed -i -e "$insertLine"' i\'$'\n''bar'$'\n' sample.txt
In first command, grep looks for line numbers containing "foo", cut/head selects 1st occurrence, and the arithmetic op increments that first occurrence line number by 1 since I want to insert after the occurrence. In second command, it's an in-place file edit, "i" for inserting: an ansi-c quoting new line, "bar", then another new line. The result is adding a new line containing "bar" after the "foo" line. Each of these 2 commands can be expanded to more complex operations and matching.
n=1
c=0
while n>0:
for i in range(2,n):
if n%i == 0:
break
else:
print(n,'is a prime')
c=c+1
n=n+1
if c==1000:
break
Since PyYAML's yaml.load()
function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:
import yaml
with open('tree.yaml', 'r') as f:
doc = yaml.load(f)
To access branch1 text
you would use:
txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"
because, in your YAML document, the value of the branch1
key is under the treeroot
key.
You can use
$objWorksheet->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
$objWorksheet->getActiveSheet()->getColumnDimension('A')->setWidth(100);
or define auto-size:
$objWorksheet->getRowDimension('1')->setRowHeight(-1);
Another thing to note is Environment.getExternalStorageDirectory()
has been deprecated in API 29, so change this if you're using this to get the database path:
https://developer.android.com/reference/android/os/Environment#getExternalStorageDirectory()
This method was deprecated in API level 29.
To improve user privacy, direct access to shared/external storage devices is deprecated. When an app targets Build.VERSION_CODES.Q, the path returned from this method is no longer directly accessible to apps. Apps can continue to access content stored on shared/external storage by migrating to alternatives such as Context#getExternalFilesDir(String), MediaStore, or Intent#ACTION_OPEN_DOCUMENT.
Margin is usually used to create a space between the element itself and its surround.
for example I use it when I'm building a navbar to make it sticks to the edges of the screen and for no white gap.
I usually use when I've an element inside a border, <div>
or something similar, and I want to decrease its size but at the time I want to keep the distance or the margin between the other elements around it.
So briefly, it's situational; it depends on what you are trying to do.
This method holds instructions to paint this component. Actually, in Swing, you should change paintComponent() instead of paint(), as paint calls paintBorder(), paintComponent() and paintChildren(). You shouldn't call this method directly, you should call repaint() instead.
This method can't be overridden. It controls the update() -> paint() cycle. You should call this method to get a component to repaint itself. If you have done anything to change the look of the component, but not its size ( like changing color, animating, etc. ) then call this method.
For windows user, make sure to closely look at this section.
RewriteRule ^properties$ /property_available.php/$1 [NC,QSA]
As said in Apache documentation :
The mod_rewrite module uses a rule-based rewriting engine, based on a PCRE regular-expression parser, to rewrite requested URLs on the fly.
So ^properties$
means Apache will only look for URL that has exact match with properties
.
You might want to try this code.
RewriteRule properties /property_available.php/$1 [NC,QSA]
So Apache will see the URL that has properties
and rewrite it to /property_available.php/
While not exactly renaming, dplyr::select_all()
can be used to reformat column names. This example replaces spaces and periods with an underscore and converts everything to lower case:
iris %>%
select_all(~gsub("\\s+|\\.", "_", .)) %>%
select_all(tolower) %>%
head(2)
sepal_length sepal_width petal_length petal_width species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
printf and scanf function in C/C++ uses Microsoft C library and this library has no support for 10 byte long double. So when you are using printf and scanf function in your C/C++ code to print a long double as output and to take some input as a long double, it will always give you wrong result.
If you want to use long double then you have to use " __mingw_printf " and " __mingw_scanf " function instead of printf and scanf. It has support for 10 byte long double.
Or you can define two macro like this : " #define printf __mingw_printf " and " #define scanf __mingw_scanf "
Use standard format for long double : %Lf
Does it have to be an actual service? Can you just use the built in scheduled tasks in the windows control panel.
With the help of the of Guido mail provided by @kindall, we can understand the standard import process as trying to find the module in each member of sys.path
, and file as the result of this lookup (more details in PyMOTW Modules and Imports.). So if the module is located in an absolute path in sys.path
the result is absolute, but if it is located in a relative path in sys.path
the result is relative.
Now the site.py
startup file takes care of delivering only absolute path in sys.path
, except the initial ''
, so if you don't change it by other means than setting the PYTHONPATH (whose path are also made absolute, before prefixing sys.path
), you will get always an absolute path, but when the module is accessed through the current directory.
Now if you trick sys.path in a funny way you can get anything.
As example if you have a sample module foo.py
in /tmp/
with the code:
import sys
print(sys.path)
print (__file__)
If you go in /tmp you get:
>>> import foo
['', '/tmp', '/usr/lib/python3.3', ...]
./foo.py
When in in /home/user
, if you add /tmp
your PYTHONPATH
you get:
>>> import foo
['', '/tmp', '/usr/lib/python3.3', ...]
/tmp/foo.py
Even if you add ../../tmp
, it will be normalized and the result is the same.
But if instead of using PYTHONPATH
you use directly some funny path
you get a result as funny as the cause.
>>> import sys
>>> sys.path.append('../../tmp')
>>> import foo
['', '/usr/lib/python3.3', .... , '../../tmp']
../../tmp/foo.py
Guido explains in the above cited thread, why python do not try to transform all entries in absolute paths:
we don't want to have to call getpwd() on every import .... getpwd() is relatively slow and can sometimes fail outright,
So your path is used as it is.
If you need to open the DevTools press ctrl-shift-i.
If the DevTools window is already opened you can use the ctrl-shift-d shortcut; it switches the window into a detached mode.
For example in my case the electron application window (Chrome) is really small.
It's not possible to use any other suggestions except the ctrl-shift-d shortcut
The error message tells you exactly what's wrong. The Python interpreter needs to know the encoding of the non-ASCII character.
If you want to return U+00A3 then you can say
return u'\u00a3'
which represents this character in pure ASCII by way of a Unicode escape sequence. If you want to return a byte string containing the literal byte 0xA3, that's
return b'\xa3'
(where in Python 2 the b
is implicit; but explicit is better than implicit).
The linked PEP in the error message instructs you exactly how to tell Python "this file is not pure ASCII; here's the encoding I'm using". If the encoding is UTF-8, that would be
# coding=utf-8
or the Emacs-compatible
# -*- encoding: utf-8 -*-
If you don't know which encoding your editor uses to save this file, examine it with something like a hex editor and some googling. The Stack Overflow character-encoding tag has a tag info page with more information and some troubleshooting tips.
In so many words, outside of the 7-bit ASCII range (0x00-0x7F), Python can't and mustn't guess what string a sequence of bytes represents. https://tripleee.github.io/8bit#a3 shows 21 possible interpretations for the byte 0xA3 and that's only from the legacy 8-bit encodings; but it could also very well be the first byte of a multi-byte encoding. But in fact, I would guess you are actually using Latin-1, so you should have
# coding: latin-1
as the first or second line of your source file. Anyway, without knowledge of which character the byte is supposed to represent, a human would not be able to guess this, either.
A caveat: coding: latin-1
will definitely remove the error message (because there are no byte sequences which are not technically permitted in this encoding), but might produce completely the wrong result when the code is interpreted if the actual encoding is something else. You really have to know the encoding of the file with complete certainty when you declare the encoding.
In the spirit of changing the rendering instead of changing the content, the following CSS makes each newline behave like a <br>
:
white-space: pre;
white-space: pre-line;
Why two rules: pre-line
only affects newlines (thanks for the clue, @KevinPauli). IE6-7 and other old browsers fall back to the more extreme pre
which also includes nowrap
and renders multiple spaces. Details on these and other settings (pre-wrap
) at mozilla and css-tricks (thanks @Sablefoste).
While I'm generally averse to the S.O. predilection for second-guessing the question rather than answering it, in this case replacing newlines with <br>
markup may increase vulnerability to injection attack with unwashed user input. You're crossing a bright red line whenever you find yourself changing .text()
calls to .html()
which the literal question implies would have to be done. (Thanks @AlexS for highlighting this point.) Even if you rule out a security risk at the time, future changes could unwittingly introduce it. Instead, this CSS allows you to get hard line breaks without markup using the safer .text()
.
As has just happened to me - this can also happen when you add a required property to your model without updating your form. In this case the ValidationSummary will not list the error message.
Steps to follow Remove Modules in Android Studio:3.1.4.
Goto Project-->Right Click on Module (FolderIcon-GreywithGreenColorDot) -->Load/UnLoadModules in PopUp -->Select Which Module to Unload in PopUpWindow
Again RightClick on Module (FolderIcon-OrangeColor) -->Remove module.
Finally, RightClick again on Module (FolderIcon-GreyColor) -->Delete.
Note:Incase Project Enabled with Git please remove module from settings.gradle, otherwise deleted module.iml will show in project module list(Reference Link).gradle.xml which is located in project/.idea/gradle.xml--remove a module from here.
Hope it helps. Thank-you.
Not a barplot
solution but using lattice
and barchart
:
library(lattice)
barchart(Species~Reason,data=Reasonstats,groups=Catergory,
scales=list(x=list(rot=90,cex=0.8)))
font-weight: 900;
I had a different issue with Font Awesome 5. Default font-weight should be 900 for FontAwesome icons but I overwrote it to 400 for span and i tags. It just worked, when I corrected it.
Here is the issue reference in their Github page, https://github.com/FortAwesome/Font-Awesome/issues/11946
I hope it will help someone.
window.WindowStyle = WindowStyle.None;
window.ResizeMode = ResizeMode.NoResize;
window.Left = 0;
window.Top = 0;
window.Width = SystemParameters.VirtualScreenWidth;
window.Height = SystemParameters.VirtualScreenHeight;
window.Topmost = true;
Works with multiple screens
This is how you should setup Eclipse Debugger for remote debugging:
Eclipse Settings:
1.Click the Run Button
2.Select the Debug Configurations
3.Select the “Remote Java Application”
4.New Configuration
For JBoss:
1.Change the /path/toJboss/jboss-eap-6.1/bin/standalone.conf
in your vm as follows:
Uncomment the following line by removing the #:
JAVA_OPTS="$JAVA_OPTS -agentlib:jdwp=transport=dt_socket,address=8787,server=y,suspend=n"
For Tomcat :
In catalina.bat file :
Step 1:
CATALINA_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"
Step 2:
JPDA_OPTS="-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n"
Step 3: Run Tomcat from command prompt like below:
catalina.sh jpda start
Then you need to set breakpoints in the Java classes you desire to debug.
Use a simple for
loop:
seq = ['abc123', 'def456', 'ghi789']
sub = 'abc'
for text in seq:
if sub in text:
print(text)
yields
abc123
If you run pub build --mode=debug
the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug
is used.
Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline
Yes, it is possible since lists are mutable.
Look at the built-in enumerate()
function to get an idea how to iterate over the list and find each entry's index (which you can then use to assign to the specific list item).
from inside an activity that calls a layout and a textview, this click listener works:
setContentView(R.layout.your_layout);
TextView tvGmail = (TextView) findViewById(R.id.tvGmail);
String TAG = "yourLogCatTag";
tvGmail.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
Log.d(TAG,"GMAIL account selected");
} catch (Exception except) {
Log.e(TAG,"Ooops GMAIL account selection problem "+except.getMessage());
}
}
});
the text view is declared like this (default wizard):
<TextView
android:id="@+id/tvGmail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/menu_id_google"
android:textSize="30sp" />
and in the strings.xml file
<string name="menu_id_google">Google ID (Gmail)</string>
You have to specify project_id
:
reverse('edit_project', kwargs={'project_id':4})
Doc here
Got everything sorted - see the last few lines for code - (bounds.extend(myLatLng); map.fitBounds(bounds);
)
function initialize() {
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(
document.getElementById("map_canvas"),
myOptions);
setMarkers(map, beaches);
}
var beaches = [
['Bondi Beach', -33.890542, 151.274856, 4],
['Coogee Beach', -33.923036, 161.259052, 5],
['Cronulla Beach', -36.028249, 153.157507, 3],
['Manly Beach', -31.80010128657071, 151.38747820854187, 2],
['Maroubra Beach', -33.950198, 151.159302, 1]
];
function setMarkers(map, locations) {
var image = new google.maps.MarkerImage('images/beachflag.png',
new google.maps.Size(20, 32),
new google.maps.Point(0,0),
new google.maps.Point(0, 32));
var shadow = new google.maps.MarkerImage('images/beachflag_shadow.png',
new google.maps.Size(37, 32),
new google.maps.Point(0,0),
new google.maps.Point(0, 32));
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
shadow: shadow,
icon: image,
shape: shape,
title: beach[0],
zIndex: beach[3]
});
bounds.extend(myLatLng);
}
map.fitBounds(bounds);
}
From the hint from Michael Kopaniov, below works
df.where(df("id").isNotNull).show
Here is an overlay using a pseudo-element (eg: no need to add more markup to do it)
.box {_x000D_
background: 0 0 url(http://ianfarb.com/wp-content/uploads/2013/10/nicholas-hodag.jpg);_x000D_
width: 300px;_x000D_
height: 200px;_x000D_
}_x000D_
_x000D_
.box:after {_x000D_
content: "";_x000D_
display: block;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
background: rgba(0, 0, 0, 0.4);_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
You can use this:
list=$(find /home/user/Desktop -name '*.pdf' -o -name '*.txt' -o -name '*.bmp')
Besides, you might want to use -iname
instead of -name
to catch files with ".PDF" (upper-case) extension as well.
Use set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "/some/full/path/to/bin")
df2 <- data.frame(apply(df1, 2, function(x) as.numeric(as.character(x))))
similar to dhw's answer but you don't have to worry about setting the link as global in all the function because that is kind of difficult:
just use this code in your config file:
$sv_connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$db_connection = mysqli_select_db ($sv_connection, $dbname);
mysqli_set_charset($sv_connection, 'utf8'); //optional
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
function mysqljx_query($q){
global $sv_connection;
return mysqli_query($sv_connection, $q);
}
function mysqljx_fetch_array($r){
return mysqli_fetch_array($r);
}
function mysqljx_fetch_assoc($r){
return mysqli_fetch_assoc($r);
}
function mysqljx_num_rows($r){
return mysqli_num_rows($r);
}
function mysqljx_insert_id(){
global $sv_connection;
return mysqli_insert_id($sv_connection);
}
function mysqljx_real_escape_string($string){
global $sv_connection;
return mysqli_real_escape_string($sv_connection, $string);
}
-now do a search for php files that contain "mysql_" (i used total commander for that - Alt+F7, search for "*.php", find text "mysql_", Start search, Feed to listbox)
-drag&drop them all in Notepad++, there u press CTRL+H, Find what: "mysql_", Replace with "mysqljx_", "Replace All in All Opened Documents"
if you are worried that you have other functions than the ones listed above just replace one by one ("mysql_query" with "mysqljx_query", then mysql_fetch_array with "mysqljx_fetch_array" etc..) and then search again for "mysql_" and if its still there its a uncovered function and you can just add it same as the rest..
that is it
Default escape character in Java is '\'.
However, Java properties file has format key=value, it should be considering everything after the first equal as value.
Raising an event when a property changes is precisely what INotifyPropertyChanged does. There's one required member to implement INotifyPropertyChanged and that is the PropertyChanged event. Anything you implemented yourself would probably be identical to that implementation, so there's no advantage to not using it.
I realize this is an old post, but I ran into the same problem and don't see the correct answer so I will give it a try
Python Error:
_csv.Error: new-line character seen in unquoted field
Caused by trying to read Macintosh (pre OS X formatted) CSV files. These are text files that use CR for end of line. If using MS Office make sure you select either plain CSV format or CSV (MS-DOS). Do not use CSV (Macintosh) as save-as type.
My preferred EOL version would be LF (Unix/Linux/Apple), but I don't think MS Office provides the option to save in this format.
staticmethod
objects apparently have a __func__
attribute storing the original raw function (makes sense that they had to). So this will work:
class Klass(object):
@staticmethod # use as decorator
def stat_func():
return 42
_ANS = stat_func.__func__() # call the staticmethod
def method(self):
ret = Klass.stat_func()
return ret
As an aside, though I suspected that a staticmethod object had some sort of attribute storing the original function, I had no idea of the specifics. In the spirit of teaching someone to fish rather than giving them a fish, this is what I did to investigate and find that out (a C&P from my Python session):
>>> class Foo(object):
... @staticmethod
... def foo():
... return 3
... global z
... z = foo
>>> z
<staticmethod object at 0x0000000002E40558>
>>> Foo.foo
<function foo at 0x0000000002E3CBA8>
>>> dir(z)
['__class__', '__delattr__', '__doc__', '__format__', '__func__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> z.__func__
<function foo at 0x0000000002E3CBA8>
Similar sorts of digging in an interactive session (dir
is very helpful) can often solve these sorts of question very quickly.
Just put the following lines at the beginning of any file you want to disable these warnings for.
# pylint: disable=missing-module-docstring
# pylint: disable=missing-class-docstring
# pylint: disable=missing-function-docstring
Interop with other languages founded on the DLR
is #1 reason I can think of. You can't pass them a Dictionary<string, object>
as it's not an IDynamicMetaObjectProvider
. Another added benefit is that it implements INotifyPropertyChanged
which means in the databinding world of WPF it also has added benefits beyond what Dictionary<K,V>
can provide you.
You don't need one unless your class maintains unmanaged resources like Windows file handles.
<style>
.col {display:table-cell;max-width:50px;width:50px;overflow:hidden;white-space: nowrap;}
</style>
<table>
<tr>
<td class="col">123456789123456789</td>
</tr>
</table>
displays 123456
You can try this:
char tab[7]={'a','b','t','u','a','y','t'};
printf("%d\n",sizeof(tab)/sizeof(tab[0]));
Using C++11:
#include <map>
using namespace std;
map<int, char> m = {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}};
Using Boost.Assign:
#include <map>
#include "boost/assign.hpp"
using namespace std;
using namespace boost::assign;
map<int, char> m = map_list_of (1, 'a') (3, 'b') (5, 'c') (7, 'd');
Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.
This is wrong. It will just kill the session when the associated client (webbrowser) has not accessed the website for more than 15 minutes. The activity certainly counts, exactly as you initially expected, seeing your attempt to solve this.
The HttpSession#setMaxInactiveInterval()
doesn't change much here by the way. It does exactly the same as <session-timeout>
in web.xml
, with the only difference that you can change/set it programmatically during runtime. The change by the way only affects the current session instance, not globally (else it would have been a static
method).
To play around and experience this yourself, try to set <session-timeout>
to 1 minute and create a HttpSessionListener
like follows:
@WebListener
public class HttpSessionChecker implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent event) {
System.out.printf("Session ID %s created at %s%n", event.getSession().getId(), new Date());
}
public void sessionDestroyed(HttpSessionEvent event) {
System.out.printf("Session ID %s destroyed at %s%n", event.getSession().getId(), new Date());
}
}
(if you're not on Servlet 3.0 yet and thus can't use @WebListener
, then register in web.xml
as follows):
<listener>
<listener-class>com.example.HttpSessionChecker</listener-class>
</listener>
Note that the servletcontainer won't immediately destroy sessions after exactly the timeout value. It's a background job which runs at certain intervals (e.g. 5~15 minutes depending on load and the servletcontainer make/type). So don't be surprised when you don't see destroyed
line in the console immediately after exactly one minute of inactivity. However, when you fire a HTTP request on a timed-out-but-not-destroyed-yet session, it will be destroyed immediately.
Just because java's implementation of Cloneable is broken it doesn't mean you can't create one of your own.
If OP real purpose was to create a deep clone, i think that it is possible to create an interface like this:
public interface Cloneable<T> {
public T getClone();
}
then use the prototype constructor mentioned before to implement it:
public class AClass implements Cloneable<AClass> {
private int value;
public AClass(int value) {
this.vaue = value;
}
protected AClass(AClass p) {
this(p.getValue());
}
public int getValue() {
return value;
}
public AClass getClone() {
return new AClass(this);
}
}
and another class with an AClass object field:
public class BClass implements Cloneable<BClass> {
private int value;
private AClass a;
public BClass(int value, AClass a) {
this.value = value;
this.a = a;
}
protected BClass(BClass p) {
this(p.getValue(), p.getA().getClone());
}
public int getValue() {
return value;
}
public AClass getA() {
return a;
}
public BClass getClone() {
return new BClass(this);
}
}
In this way you can easely deep clone an object of class BClass without need for @SuppressWarnings or other gimmicky code.
Have look at WebLookAndFeel at https://github.com/mgarin/weblaf/
WebTextField txtName = new com.alee.laf.text.WebTextField();
txtName.setHideInputPromptOnFocus(false);
txtName.setInputPrompt("Name");
txtName.setInputPromptFont(new java.awt.Font("Ubuntu", 0, 18));
txtName.setInputPromptForeground(new java.awt.Color(102, 102, 102));
txtName.setInputPromptPosition(0);
You can use it only in body tag or in tables. Something like this:
<table width="100%" background="YOUR_IMAGE_URL" style="STYLES YOU WANT (i.e. background-repeat)">
This worked for me.
Create Table as select (CTAS) is possible in Hive.
You can try out below command:
CREATE TABLE new_test
row format delimited
fields terminated by '|'
STORED AS RCFile
AS select * from source where col=1
Create table like is also possible in Hive.
Relative paths can be used, but they can be tricky. The best solution is to know where your files are being saved, that is, print the folder:
import java.io.File;
import java.util.*;
public class Hangman1 {
public static void main(String[] args) throws Exception {
File myFile = new File("word.txt");
System.out.println("Attempting to read from file in: "+myFile.getCanonicalPath());
Scanner input = new Scanner(myFile);
String in = "";
in = input.nextLine();
}
}
This code should print the folder where it is looking for. Place the file there and you'll be good to go.
With lattice
:
library(lattice)
df <- data.frame(time = 1:10,
a = cumsum(rnorm(10)),
b = cumsum(rnorm(10)),
c = cumsum(rnorm(10)))
form <- as.formula(paste(paste(names(df)[- 1], collapse = ' + '),
'time', sep = '~'))
xyplot(form, data = df, type = 'b', outer = TRUE)
Its Simple Use .Select function.
DataRow[] foundRows=table.Select("Date = '1/31/1979' or OrderID = 2", "CompanyName ASC");
DataTable dt = foundRows.CopyToDataTable();
And it's done......Happy Coding
The OPTIONS is from http://www.w3.org/TR/cors/ See http://metajack.im/2010/01/19/crossdomain-ajax-for-xmpp-http-binding-made-easy/ for a bit more info
this tells the script where is python directory !
#! /usr/bin/env python
This will give you the working directory of the current file.
File.dirname(__FILE__)
Example:
current_file: "/Users/nemrow/SITM/folder1/folder2/amazon.rb"
result: "/Users/nemrow/SITM/folder1/folder2"
Try http://www.sql-server-helper.com/tips/date-formats.aspx. Lists all formats needed. In this case select Convert(varchar(10),CONVERT(date,YourDateColumn,106),103) change 103 to 104 id you need dd.mm.yyyy
var bar= $(#foo).find("option:selected").val();
Unless you redirect stdout and stderr as the accepted answer suggests, this is not possible with execSync or spawnSync. Without redirecting stdout and stderr those commands only return stdout and stderr when the command is completed.
To do this without redirecting stdout and stderr, you are going to need to use spawn to do this but it's pretty straight forward:
var spawn = require('child_process').spawn;
//kick off process of listing files
var child = spawn('ls', ['-l', '/']);
//spit stdout to screen
child.stdout.on('data', function (data) { process.stdout.write(data.toString()); });
//spit stderr to screen
child.stderr.on('data', function (data) { process.stdout.write(data.toString()); });
child.on('close', function (code) {
console.log("Finished with code " + code);
});
I used an ls command that recursively lists files so that you can test it quickly. Spawn takes as first argument the executable name you are trying to run and as it's second argument it takes an array of strings representing each parameter you want to pass to that executable.
However, if you are set on using execSync and can't redirect stdout or stderr for some reason, you can open up another terminal like xterm and pass it a command like so:
var execSync = require('child_process').execSync;
execSync("xterm -title RecursiveFileListing -e ls -latkR /");
This will allow you to see what your command is doing in the new terminal but still have the synchronous call.
There are two methods to get the mod time, os.path.getmtime() or os.stat(), but the ctime is not reliable cross-platform (see below).
getmtime(path)
Return the time of last modification of path. The return value is a number giving the
number of seconds since the epoch (see the time module). Raise os.error if the file does
not exist or is inaccessible. New in version 1.5.2. Changed in version 2.3: If
os.stat_float_times() returns True, the result is a floating point number.
stat(path)
Perform a stat() system call on the given path. The return value is an object whose
attributes correspond to the members of the stat structure, namely: st_mode (protection
bits), st_ino (inode number), st_dev (device), st_nlink (number of hard links), st_uid
(user ID of owner), st_gid (group ID of owner), st_size (size of file, in bytes),
st_atime (time of most recent access), st_mtime (time of most recent content
modification), st_ctime (platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows):
>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
(33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
>>> statinfo.st_size
926L
>>>
In the above example you would use statinfo.st_mtime or statinfo.st_ctime to get the mtime and ctime, respectively.
rows and cols are required attributes, so you should have them whether you really need them or not. They set the number of rows and number of columns respectively.
It will bust the cache once, after the client has downloaded the resource every other response will be served from client cache unless:
This question has many, many duplicates, including questions not mentioning the Chai assertion library. Here are the basics collected together:
The assertion must call the function, instead of it evaluating immediately.
assert.throws(x.y.z);
// FAIL. x.y.z throws an exception, which immediately exits the
// enclosing block, so assert.throw() not called.
assert.throws(()=>x.y.z);
// assert.throw() is called with a function, which only throws
// when assert.throw executes the function.
assert.throws(function () { x.y.z });
// if you cannot use ES6 at work
function badReference() { x.y.z }; assert.throws(badReference);
// for the verbose
assert.throws(()=>model.get(z));
// the specific example given.
homegrownAssertThrows(model.get, z);
// a style common in Python, but not in JavaScript
You can check for specific errors using any assertion library:
assert.throws(() => x.y.z);
assert.throws(() => x.y.z, ReferenceError);
assert.throws(() => x.y.z, ReferenceError, /is not defined/);
assert.throws(() => x.y.z, /is not defined/);
assert.doesNotThrow(() => 42);
assert.throws(() => x.y.z, Error);
assert.throws(() => model.get.z, /Property does not exist in model schema./)
should.throws(() => x.y.z);
should.throws(() => x.y.z, ReferenceError);
should.throws(() => x.y.z, ReferenceError, /is not defined/);
should.throws(() => x.y.z, /is not defined/);
should.doesNotThrow(() => 42);
should.throws(() => x.y.z, Error);
should.throws(() => model.get.z, /Property does not exist in model schema./)
expect(() => x.y.z).to.throw();
expect(() => x.y.z).to.throw(ReferenceError);
expect(() => x.y.z).to.throw(ReferenceError, /is not defined/);
expect(() => x.y.z).to.throw(/is not defined/);
expect(() => 42).not.to.throw();
expect(() => x.y.z).to.throw(Error);
expect(() => model.get.z).to.throw(/Property does not exist in model schema./);
You must handle exceptions that 'escape' the test
it('should handle escaped errors', function () {
try {
expect(() => x.y.z).not.to.throw(RangeError);
} catch (err) {
expect(err).to.be.a(ReferenceError);
}
});
This can look confusing at first. Like riding a bike, it just 'clicks' forever once it clicks.
I think it is totally independent. Just install them, then you have the commands e.g. /usr/bin/python2.5
and /usr/bin/python2.6
. Link /usr/bin/python
to the one you want to use as default.
All the libraries are in separate folders (named after the version) anyway.
If you want to compile the versions manually, this is from the readme file of the Python source code:
Installing multiple versions
On Unix and Mac systems if you intend to install multiple versions of Python using the same installation prefix (--prefix argument to the configure script) you must take care that your primary python executable is not overwritten by the installation of a different version. All files and directories installed using "make altinstall" contain the major and minor version and can thus live side-by-side. "make install" also creates ${prefix}/bin/python3 which refers to ${prefix}/bin/pythonX.Y. If you intend to install multiple versions using the same prefix you must decide which version (if any) is your "primary" version. Install that version using "make install". Install all other versions using "make altinstall".
For example, if you want to install Python 2.5, 2.6 and 3.0 with 2.6 being the primary version, you would execute "make install" in your 2.6 build directory and "make altinstall" in the others.
There are three unique situations:
Margin="a,b,c,d"
.Margin="a,b"
.Margin="a"
.If there are 4 numbers, then its left
, top
, right
, bottom
(a clockwise circle starting from the middle left margin). First number is always the "West" like "WPF":
<object Margin="left,top,right,bottom"/>
Example: if we use Margin="10,20,30,40"
it generates:
If there are 2 numbers, then the first is left & right margin thickness, the second is top & bottom margin thickness. First number is always the "West" like "WPF":
<object Margin="a,b"/> // Equivalent to Margin="a,b,a,b".
Example: if we use Margin="10,30"
, the left & right margin are both 10, and the top & bottom are both 30.
If there is 1 number, then the number is repeated (its essentially a border thickness).
<object Margin="a"/> // Equivalent to Margin="a,a,a,a".
Example: if we use Margin="20"
it generates:
Have been working on a large-scale WPF application for the past 5 years with over 100 screens. Part of a team of 5 WPF/C#/Java devs. We eventually settled on either using 1 number (for border thickness) or 4 numbers. We never use 2. It is consistent, and seems to be a good way to reduce cognitive load when developing.
The rule:
All width numbers start on the left (the "West" like "WPF") and go clockwise (if two numbers, only go clockwise twice, then mirror the rest).
Creating a text file in unix can be done through a text editor (vim, emacs, gedit, etc). But what you want might be something like this
echo "insert text here" > myfile.txt
That will put the text 'insert text here' into a file myfile.txt. To verify that this worked use the command 'cat'.
cat myfile.txt
If you want to append to a file use this
echo "append this text" >> myfile.txt
var yearsToAdd = 5;
var current = new Date().toISOString().split('T')[0];
var addedYears = Number(this.minDate.split('-')[0]) + yearsToAdd + '-12-31';
Here's what I did to solve this problem
You can just as easily access each element in the list using e.g. path[[1]]
. You can't put a set of matrices into an atomic vector and access each element. A matrix is an atomic vector with dimension attributes. I would use the list structure returned by split
, it's what it was designed for. Each list element can hold data of different types and sizes so it's very versatile and you can use *apply
functions to further operate on each element in the list. Example below.
# For reproducibile data
set.seed(1)
# Make some data
userid <- rep(1:2,times=4)
data1 <- replicate(8 , paste( sample(letters , 3 ) , collapse = "" ) )
data2 <- sample(10,8)
df <- data.frame( userid , data1 , data2 )
# Split on userid
out <- split( df , f = df$userid )
#$`1`
# userid data1 data2
#1 1 gjn 3
#3 1 yqp 1
#5 1 rjs 6
#7 1 jtw 5
#$`2`
# userid data1 data2
#2 2 xfv 4
#4 2 bfe 10
#6 2 mrx 2
#8 2 fqd 9
Access each element using the [[
operator like this:
out[[1]]
# userid data1 data2
#1 1 gjn 3
#3 1 yqp 1
#5 1 rjs 6
#7 1 jtw 5
Or use an *apply
function to do further operations on each list element. For instance, to take the mean of the data2
column you could use sapply like this:
sapply( out , function(x) mean( x$data2 ) )
# 1 2
#3.75 6.25
This should work as well
text = 'the car? was big and* red!'
newtext = re.sub( '[^a-z0-9]', ' ', text)
print(newtext)
the car was big and red
Define this in your String.xml file and name the array what you want, such as "Weight"
<string-array name="Weight">
<item>Kg</item>
<item>Gram</item>
<item>Tons</item>
</string-array>
and this code in your layout.xml
<Spinner
android:id="@+id/fromspin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:entries="@array/Weight"
/>
In your java file, getActivity
is used in fragment; if you write that code in activity, then remove getActivity
.
a = (Spinner) findViewById(R.id.fromspin);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),
R.array.weight, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
a.setAdapter(adapter);
a.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (a.getSelectedItem().toString().trim().equals("Kilogram")) {
if (!b.getText().toString().isEmpty()) {
float value1 = Float.parseFloat(b.getText().toString());
float kg = value1;
c.setText(Float.toString(kg));
float gram = value1 * 1000;
d.setText(Float.toString(gram));
float carat = value1 * 5000;
e.setText(Float.toString(carat));
float ton = value1 / 908;
f.setText(Float.toString(ton));
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
});
// Inflate the layout for this fragment
return v;
}
This is a response I got from their Premium Services
Hello,
This is actually a issue with the way SSL validates names containing a period, '.', > character. We've documented this behavior here:
http://docs.amazonwebservices.com/AmazonS3/latest/dev/BucketRestrictions.html
The only straight-forward fix for this is to use a bucket name that does not contain that character. You might instead use a bucket named 'furniture-retailcatalog-us'. This would allow you use HTTPS with
https://furniture-retailcatalog-us.s3.amazonaws.com/
You could, of course, put a CNAME DNS record to make that more friendly. For example,
images-furniture.retailcatalog.us IN CNAME furniture-retailcatalog-us.s3.amazonaws.com.
Hope that helps. Let us know if you have any other questions.
Amazon Web Services
Unfortunately your "friendly" CNAME will cause host name mismatch when validating the certificate, therefore you cannot really use it for a secure connection. A big missing feature of S3 is accepting custom certificates for your domains.
UPDATE 10/2/2012
From @mpoisot:
The link Amazon provided no longer says anything about https. I poked around in the S3 docs and finally found a small note about it on the Virtual Hosting page: http://docs.amazonwebservices.com/AmazonS3/latest/dev/VirtualHosting.html
UPDATE 6/17/2013
From @Joseph Lust:
Just got it! Check it out and sign up for an invite: http://aws.amazon.com/cloudfront/custom-ssl-domains
There's a jquery plugin http://www.asual.com/jquery/address/
I think this is what you need.
The <f:viewParam>
manages the setting, conversion and validation of GET parameters. It's like the <h:inputText>
, but then for GET parameters.
The following example
<f:metadata>
<f:viewParam name="id" value="#{bean.id}" />
</f:metadata>
does basically the following:
id
.required
, validator
and converter
attributes and nest a <f:converter>
and <f:validator>
in it like as with <h:inputText>
)#{bean.id}
value, or if the value
attribute is absent, then set it as request attribtue on name id
so that it's available by #{id}
in the view.So when you open the page as foo.xhtml?id=10
then the parameter value 10
get set in the bean this way, right before the view is rendered.
As to validation, the following example sets the param to required="true"
and allows only values between 10 and 20. Any validation failure will result in a message being displayed.
<f:metadata>
<f:viewParam id="id" name="id" value="#{bean.id}" required="true">
<f:validateLongRange minimum="10" maximum="20" />
</f:viewParam>
</f:metadata>
<h:message for="id" />
You can use the <f:viewAction>
for this.
<f:metadata>
<f:viewParam id="id" name="id" value="#{bean.id}" required="true">
<f:validateLongRange minimum="10" maximum="20" />
</f:viewParam>
<f:viewAction action="#{bean.onload}" />
</f:metadata>
<h:message for="id" />
with
public void onload() {
// ...
}
The <f:viewAction>
is however new since JSF 2.2 (the <f:viewParam>
already exists since JSF 2.0). If you can't upgrade, then your best bet is using <f:event>
instead.
<f:event type="preRenderView" listener="#{bean.onload}" />
This is however invoked on every request. You need to explicitly check if the request isn't a postback:
public void onload() {
if (!FacesContext.getCurrentInstance().isPostback()) {
// ...
}
}
When you would like to skip "Conversion/Validation failed" cases as well, then do as follows:
public void onload() {
FacesContext facesContext = FacesContext.getCurrentInstance();
if (!facesContext.isPostback() && !facesContext.isValidationFailed()) {
// ...
}
}
Using <f:event>
this way is in essence a workaround/hack, that's exactly why the <f:viewAction>
was introduced in JSF 2.2.
You can "pass-through" the view parameters in navigation links by setting includeViewParams
attribute to true
or by adding includeViewParams=true
request parameter.
<h:link outcome="next" includeViewParams="true">
<!-- Or -->
<h:link outcome="next?includeViewParams=true">
which generates with the above <f:metadata>
example basically the following link
<a href="next.xhtml?id=10">
with the original parameter value.
This approach only requires that next.xhtml
has also a <f:viewParam>
on the very same parameter, otherwise it won't be passed through.
The <f:viewParam>
can also be used in combination with "plain HTML" GET forms.
<f:metadata>
<f:viewParam id="query" name="query" value="#{bean.query}" />
<f:viewAction action="#{bean.search}" />
</f:metadata>
...
<form>
<label for="query">Query</label>
<input type="text" name="query" value="#{empty bean.query ? param.query : bean.query}" />
<input type="submit" value="Search" />
<h:message for="query" />
</form>
...
<h:dataTable value="#{bean.results}" var="result" rendered="#{not empty bean.results}">
...
</h:dataTable>
With basically this @RequestScoped
bean:
private String query;
private List<Result> results;
public void search() {
results = service.search(query);
}
Note that the <h:message>
is for the <f:viewParam>
, not the plain HTML <input type="text">
! Also note that the input value displays #{param.query}
when #{bean.query}
is empty, because the submitted value would otherwise not show up at all when there's a validation or conversion error. Please note that this construct is invalid for JSF input components (it is doing that "under the covers" already).
I have encountered this with Maven projects too. This is what I had to do to get around the problem:
First update your web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Servlet 3.0 Web Application</display-name>
Then right click on your project and select Properties -> Project Facets In there you will see the version of your Dynamic Web Module. This needs to change from version 2.3 or whatever to version 2.5 or above (I chose 3.0).
However to do this I had to uncheck the tick box for Dynamic Web Module -> Apply, then do a Maven Update on the project. Go back into the Project Facets window and it should already match your web.xml configuration - 3.0 in my case. You should be able to change it if not.
If this does not work for you then try right-clicking on the Dynamic Web Module Facet and select change version (and ensure it is not locked).
Or you can follow this steps:
don't forget to update your project
Hope that works!
You're probably better off using an HtmlTextWriter
or an XMLWriter
than a plain StringWriter
. They will take care of escaping for you, as well as making sure the document is well-formed.
This page shows the basics of using the HtmlTextWriter
class, the gist of which being:
StringWriter stringWriter = new StringWriter();
using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
{
writer.AddAttribute(HtmlTextWriterAttribute.Class, classValue);
writer.RenderBeginTag(HtmlTextWriterTag.Div); // Begin #1
writer.AddAttribute(HtmlTextWriterAttribute.Href, urlValue);
writer.RenderBeginTag(HtmlTextWriterTag.A); // Begin #2
writer.AddAttribute(HtmlTextWriterAttribute.Src, imageValue);
writer.AddAttribute(HtmlTextWriterAttribute.Width, "60");
writer.AddAttribute(HtmlTextWriterAttribute.Height, "60");
writer.AddAttribute(HtmlTextWriterAttribute.Alt, "");
writer.RenderBeginTag(HtmlTextWriterTag.Img); // Begin #3
writer.RenderEndTag(); // End #3
writer.Write(word);
writer.RenderEndTag(); // End #2
writer.RenderEndTag(); // End #1
}
// Return the result.
return stringWriter.ToString();
I'm using
Sheet1.Range("E2", "E3000").NumberFormat = "dd/mm/yyyy hh:mm:ss"
to format a column
So I guess
Sheet1.Range("E2", "E3000").NumberFormat = "MMM dd yyyy"
would do the trick for you.
More: NumberFormat function.
I have used all of Sam's recommendations above, but I found that the VM command line options are no longer supported as described. (I received an error when used)
As an alternative, I was able to reduce gradle dramatically by adding the following line to the "gradle.properties" file
org.gradle.jvmargs=-Xms512m -Xmx1024m
As of A.S. ver 1.3, the file is located in the same folder level as "gradle.build".
The above configuration is a "memory stack" of 512 meg, and "memory heap" of 1024 meg.
I tested this on a small project, using settings where both memory sizes were set to 256 meg. It limited the JVM sizes as expected. In all my tests, I restarted A.S. to force the JVM to restart.
Hopefully, this will save others dealing with this issue from getting those "Get yourself a better computer" responses. :-)
Use your jquery like this
$('.home').css({'background-image':'url(images/tabs3.png)'});