Try to check Signing settings in Build settings for your project and target. Be sure that code signing identity section has correct identities for Debug and Release.
For pipeline:
pipeline {
environment {
BRANCH_NAME = "${GIT_BRANCH.split("/")[1]}"
}
}
The warning from your compiler is telling you that your format specifier doesn't match the data type you're passing to it.
Try using %lx
or %llx
. For more portability, include inttypes.h
and use the PRIx64
macro.
For example: printf("val = 0x%" PRIx64 "\n", val);
(note that it's string concatenation)
To checkout the branch via Jenkins scripts use:
stage('Checkout SCM') {
git branch: 'branchName', credentialsId: 'your_credentials', url: "giturlrepo"
}
The auto_increment
property only works for numeric columns (integer and floating point), not char
columns:
CREATE TABLE discussion_topics (
topic_id INT NOT NULL AUTO_INCREMENT,
project_id char(36) NOT NULL,
topic_subject VARCHAR(255) NOT NULL,
topic_content TEXT default NULL,
date_created DATETIME NOT NULL,
date_last_post DATETIME NOT NULL,
created_by_user_id char(36) NOT NULL,
last_post_user_id char(36) NOT NULL,
posts_count char(36) default NULL,
PRIMARY KEY (topic_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
You can't do it (yet) with string interpolation. Your best bet is still going to be NSString formatting:
println(NSString(format:"%.2f", sqrt(2.0)))
Extrapolating from python, it seems like a reasonable syntax might be:
@infix func % (value:Double, format:String) -> String {
return NSString(format:format, value)
}
Which then allows you to use them as:
M_PI % "%5.3f" // "3.142"
You can define similar operators for all of the numeric types, unfortunately I haven't found a way to do it with generics.
Swift 5 Update
As of at least Swift 5, String
directly supports the format:
initializer, so there's no need to use NSString
and the @infix
attribute is no longer needed which means the samples above should be written as:
println(String(format:"%.2f", sqrt(2.0)))
func %(value:Double, format:String) -> String {
return String(format:format, value)
}
Double.pi % "%5.3f" // "3.142"
Calling m.check(side), meaning you are running actual code, but you can't run code outside main() - you can only define variables. In C++, code can only appear inside function bodies or in variable initializes.
This solved the problem for me (Ubuntu 16.04):
sudo apt-get install build-essential libssl-dev libffi-dev python-dev python3-dev
and then it was working like this:
pip install cryptography
pip install pyopenssl ndg-httpsclient pyasn1
{
int main(void);
should be
int main(void)
{
Then I let you fix the next compilation errors of your program...
Your string is wider than your format width of 2. So there's no padding to be done.
At least in Visual C++: printf (and other ACSII functions): %s represents an ASCII string %S is a Unicode string wprintf (and other Unicode functions): %s is a Unicode string %S is an ASCII string
As far as no compiler warnings, printf uses a variable argument list, with only the first argument able to be type checked. The compiler is not designed to parse the format string and type check the parameters that match. In cases of functions like printf, that is up to the programmer
There is no format specifier for bool. You can print it using some of the existing specifiers for printing integral types or do something more fancy:
printf("%s", x?"true":"false");
Encapsulation: Hiding implementation details (NOTE: data AND/OR methods) such that only what is sensibly readable/writable/usable by externals is accessible to them, everything else is "untouchable" directly.
Abstraction: This sometimes refers specifically to a type that cannot be instantiated and which provides a template for other types that can be, usually via subclassing. More generally "abstraction" refers to making/having something that is less detailed, less specific, less granular.
There is some similarity, overlap between the concepts but the best way to remember it is like this: Encapsulation is more about hiding the details, whereas abstraction is more about generalizing the details.
No, there is no such printf width specifier to print floating-point with maximum precision. Let me explain why.
The maximum precision of float
and double
is variable, and dependent on the actual value of the float
or double
.
Recall float
and double
are stored in sign.exponent.mantissa format. This means that there are many more bits used for the fractional component for small numbers than for big numbers.
For example, float
can easily distinguish between 0.0 and 0.1.
float r = 0;
printf( "%.6f\n", r ) ; // 0.000000
r+=0.1 ;
printf( "%.6f\n", r ) ; // 0.100000
But float
has no idea of the difference between 1e27
and 1e27 + 0.1
.
r = 1e27;
printf( "%.6f\n", r ) ; // 999999988484154753734934528.000000
r+=0.1 ;
printf( "%.6f\n", r ) ; // still 999999988484154753734934528.000000
This is because all the precision (which is limited by the number of mantissa bits) is used up for the large part of the number, left of the decimal.
The %.f
modifier just says how many decimal values you want to print from the float number as far as formatting goes. The fact that the accuracy available depends on the size of the number is up to you as the programmer to handle. printf
can't/doesn't handle that for you.
Normally your requirements.txt
file would look something like this:
package-one==1.9.4
package-two==3.7.1
package-three==1.0.1
...
To specify a Github repo, you do not need the package-name==
convention.
The examples below update package-two
using a GitHub repo. The text between @
and #
denotes the specifics of the package.
41b95ec
in the context of updated requirements.txt
):package-one==1.9.4
git+git://github.com/path/to/package-two@41b95ec#egg=package-two
package-three==1.0.1
master
):git+git://github.com/path/to/package-two@master#egg=package-two
0.1
):git+git://github.com/path/to/[email protected]#egg=package-two
3.7.1
):git+git://github.com/path/to/package-two@releases/tag/v3.7.1#egg=package-two
Note that #egg=package-two
is not a comment here, it is to explicitly state the package name
This blog post has some more discussion on the topic.
git rev-parse
is an ancillary plumbing
command primarily used for manipulation.
One common usage of git rev-parse
is to print the SHA1 hashes given a revision specifier. In addition, it has various options to format this output such as --short
for printing a shorter unique SHA1.
There are other use cases as well (in scripts and other tools built on top of git) that I've used for:
--verify
to verify that the specified object is a valid git object.--git-dir
for displaying the abs/relative path of the the .git
directory.--is-inside-git-dir
or within a work-tree using --is-inside-work-tree
--is-bare-repository
--branches
), tags (--tags
) and the refs can also be filtered based on the remote (using --remote
)--parse-opt
to normalize arguments in a script (kind of similar to getopt
) and print an output string that can be used with eval
Massage
just implies that it is possible to convert the info from one form into another i.e. a transformation command. These are some quick examples I can think of:
A..B
for git log
or git diff
into the equivalent arguments for the underlying plumbing command as B ^A
It is possible to construct a struct inside the function arguments:
function({ .variable = PUT_DATA_HERE });
The format string attack on printf you mentioned isn't specific to the "%x" formatting - in any case where printf has more formatting parameters than passed variables, it will read values from the stack that do not belong to it. You will get the same issue with %d for example. %x is useful when you want to see those values as hex.
As explained in previous answers, %08x will produce a 8 digits hex number, padded by preceding zeros.
Using the formatting in your code example in printf, with no additional parameters:
printf ("%08x %08x %08x %08x");
Will fetch 4 parameters from the stack and display them as 8-digits padded hex numbers.
p
is the conversion specifier to print pointers. Use this.
int a = 42;
printf("%p\n", (void *) &a);
Remember that omitting the cast is undefined behavior and that printing with p
conversion specifier is done in an implementation-defined manner.
SSL development libraries have to be installed
CentOS:
$ yum install openssl-devel libffi-devel
Ubuntu:
$ apt-get install libssl-dev libffi-dev
OS X (with Homebrew installed):
$ brew install openssl
For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).
This can be caused in many ways:
#include
the header that defines it.#ifndef BLAH_H
) are defective (your #ifndef BLAH_H
doesn't match your #define BALH_H
due to a typo or copy+paste mistake).#define MYHEADER_H
, even if they are in separate directories)new Vector()
should be new Vector<int>()
)NamespaceA::NamespaceB
, AND a <global scope>::NamespaceB
, if you are already within NamespaceA
, it'll look in NamespaceA::NamespaceB
and not bother checking <global scope>::NamespaceB
) unless you explicitly access it.To explicitly access something in the global namespace, prefix it with ::
, as if the global namespace is a namespace with no name (e.g. ::MyType
or ::MyNamespace::MyType
).
From the Linux manual page:
h A following integer conversion corresponds to a short int or unsigned short int argument, or a fol- lowing n conversion corresponds to a pointer to a short int argument.
So to print an unsigned short integer, the format string should be "%hu"
.
Try __weak
if you get any warning regarding retain cycle else use __block
Person *strongPerson = [Person new];
__weak Person *weakPerson = person;
Now you can refer weakPerson
object inside block.
For variables, specifies that the type of the variable that is being declared will be automatically deduced from its initializer. For functions, specifies that the return type is a trailing return type or will be deduced from its return statements (since C++14).
Syntax
auto variable initializer (1) (since C++11)
auto function -> return type (2) (since C++11)
auto function (3) (since C++14)
decltype(auto) variable initializer (4) (since C++14)
decltype(auto) function (5) (since C++14)
auto :: (6) (concepts TS)
cv(optional) auto ref(optional) parameter (7) (since C++14)
Explanation
1) When declaring variables in block scope, in namespace scope, in initialization statements of for loops, etc., the keyword auto may be used as the type specifier.
Once the type of the initializer has been determined, the compiler determines the type that will replace the keyword auto using the rules for template argument deduction from a function call (see template argument deduction#Other contexts for details). The keyword auto may be accompanied by modifiers, such as const or &, which will participate in the type deduction. For example, given const auto& i = expr;
, the type of i is exactly the type of the argument u in an imaginary template template<class U> void f(const U& u)
if the function call f(expr)
was compiled. Therefore, auto&& may be deduced either as an lvalue reference or rvalue reference according to the initializer, which is used in range-based for loop.
If auto is used to declare multiple variables, the deduced types must match. For example, the declaration auto i = 0, d = 0.0;
is ill-formed, while the declaration auto i = 0, *p = &i;
is well-formed and the auto is deduced as int.
2) In a function declaration that uses the trailing return type syntax, the keyword auto does not perform automatic type detection. It only serves as a part of the syntax.
3) In a function declaration that does not use the trailing return type syntax, the keyword auto indicates that the return type will be deduced from the operand of its return statement using the rules for template argument deduction.
4) If the declared type of the variable is decltype(auto), the keyword auto is replaced with the expression (or expression list) of its initializer, and the actual type is deduced using the rules for decltype.
5) If the return type of the function is declared decltype(auto), the keyword auto is replaced with the operand of its return statement, and the actual return type is deduced using the rules for decltype.
6) A nested-name-specifier of the form auto:: is a placeholder that is replaced by a class or enumeration type following the rules for constrained type placeholder deduction.
7) A parameter declaration in a lambda expression. (since C++14) A function parameter declaration. (concepts TS)
Notes
Until C++11, auto had the semantic of a storage duration specifier.
Mixing auto variables and functions in one declaration, as in auto f() -> int, i = 0;
is not allowed.
For more info : http://en.cppreference.com/w/cpp/language/auto
I was searching for the same issue and was able to center align the text in a NSAttributedString this way:
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init] ;
[paragraphStyle setAlignment:NSTextAlignmentCenter];
NSMutableAttributedString *attribString = [[NSMutableAttributedString alloc]initWithString:string];
[attribString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [string length])];
access private members outside class ....only for study purpose .... This program accepts all the below conditions "I dont want to create member function for above class A. And also i dont want to inherit the above class A. I dont want to change the specifier of iData."
//here member function is used only to input and output the private values ... //void hack() is defined outside the class...
//GEEK MODE....;)
#include<iostream.h>
#include<conio.h>
class A
{
private :int iData,x;
public: void get() //enter the values
{cout<<"Enter iData : ";
cin>>iData;cout<<"Enter x : ";cin>>x;}
void put() //displaying values
{cout<<endl<<"sum = "<<iData+x;}
};
void hack(); //hacking function
void main()
{A obj;clrscr();
obj.get();obj.put();hack();obj.put();getch();
}
void hack() //hack begins
{int hck,*ptr=&hck;
cout<<endl<<"Enter value of private data (iData or x) : ";
cin>>hck; //enter the value assigned for iData or x
for(int i=0;i<5;i++)
{ptr++;
if(*ptr==hck)
{cout<<"Private data hacked...!!!\nChange the value : ";
cin>>*ptr;cout<<hck<<" Is chaged to : "<<*ptr;
return;}
}cout<<"Sorry value not found.....";
}
The explanation from Scott Meyers in Effective C++ might help understand when to use them:
Public inheritance should model "is-a relationship," whereas private inheritance should be used for "is-implemented-in-terms-of" - so you don't have to adhere to the interface of the superclass, you're just reusing the implementation.
Your format specifier is incorrect. From the printf()
man page on my machine:
0
A zero '0
' character indicating that zero-padding should be used rather than blank-padding. A '-
' overrides a '0
' if both are used;Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);
Precision: An optional period, '
.
', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;
For your case, your format would be %09.3f
:
#include <stdio.h>
int main(int argc, char **argv)
{
printf("%09.3f\n", 4917.24);
return 0;
}
Output:
$ make testapp
cc testapp.c -o testapp
$ ./testapp
04917.240
Note that this answer is conditional on your embedded system having a printf()
implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.
Firstly, as Etienne says, float
in C# is Single
. It is just the C# keyword for that data type.
So you can definitely do this:
float f = 13.5f;
string s = f.ToString("R");
Secondly, you have referred a couple of times to the number's "format"; numbers don't have formats, they only have values. Strings have formats. Which makes me wonder: what is this thing you have that has a format but is not a string? The closest thing I can think of would be decimal
, which does maintain its own precision; however, calling simply decimal.ToString
should have the effect you want in that case.
How about including some example code so we can see exactly what you're doing, and why it isn't achieving what you want?
character varying(n)
, varchar(n)
- (Both the same). value will be truncated to n characters without raising an error.
character(n)
, char(n)
- (Both the same). fixed-length and will pad with blanks till the end of the length.
text
- Unlimited length.
Example:
Table test:
a character(7)
b varchar(7)
insert "ok " to a
insert "ok " to b
We get the results:
a | (a)char_length | b | (b)char_length
----------+----------------+-------+----------------
"ok "| 7 | "ok" | 2
Ok, POD means plain old data. That usually refers to structs
without any methods because these types are then used to structure multiple data that belong together.
As for structs not having methods: I have seen more than once that a struct had methods, and I don't feel that this would be unnatural.
Format %lf
is a perfectly correct printf
format for double
, exactly as you used it. There's nothing wrong with your code.
Format %lf
in printf
was not supported in old (pre-C99) versions of C language, which created superficial "inconsistency" between format specifiers for double
in printf
and scanf
. That superficial inconsistency has been fixed in C99.
You are not required to use %lf
with double
in printf
. You can use %f
as well, if you so prefer (%lf
and %f
are equivalent in printf
). But in modern C it makes perfect sense to prefer to use %f
with float
, %lf
with double
and %Lf
with long double
, consistently in both printf
and scanf
.
Was having this issue testing long doubles, and alas, I came across a fix! You have to compile your project with -D__USE_MINGW_ANSI_STDIO:
Jason Huntley@centurian /home/developer/dependencies/Python-2.7.3/test $ gcc main.c
Jason Huntley@centurian /home/developer/dependencies/Python-2.7.3/test $ a.exe c=0.000000
Jason Huntley@centurian /home/developer/dependencies/Python-2.7.3/test $ gcc main.c -D__USE_MINGW_ANSI_STDIO
Jason Huntley@centurian /home/developer/dependencies/Python-2.7.3/test $ a.exe c=42.000000
Code:
Jason Huntley@centurian /home/developer/dependencies/Python-2.7.3/test
$ cat main.c
#include <stdio.h>
int main(int argc, char **argv)
{
long double c=42;
c/3;
printf("c=%Lf\n",c);
return 0;
}
You don't need to use numbers to indicate positioning. By default, the position of the argument is simply the order in which it appears in the string.
Here's an example of the proper way to use this:
String result = String.format("The format method is %s!", "great");
// result now equals "The format method is great!".
You will always use a %
followed by some other characters to let the method know how it should display the string. %s
is probably the most common, and it just means that the argument should be treated as a string.
I won't list every option, but I'll give a few examples just to give you an idea:
// we can specify the # of decimals we want to show for a floating point:
String result = String.format("10 / 3 = %.2f", 10.0 / 3.0);
// result now equals "10 / 3 = 3.33"
// we can add commas to long numbers:
result = String.format("Today we processed %,d transactions.", 1000000);
// result now equals "Today we processed 1,000,000 transactions."
String.format
just uses a java.util.Formatter
, so for a full description of the options you can see the Formatter javadocs.
And, as BalusC mentions, you will see in the documentation that is possible to change the default argument ordering if you need to. However, probably the only time you'd need / want to do this is if you are using the same argument more than once.
First of all let me say one thing there is no such term as "Access specifier" in java. We should call everything as "Modifiers". As we know that final, static, synchronised, volatile.... are called as modifiers, even Public, private, protected, default, abstract should also be called as modifiers . Default is such a modifiers where physical existence is not there but no modifiers is placed then it should be treated as default modifiers.
To justify this take one example:
public class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
Output will be: Hello Java
Now change public to private and see what compiler error you get: It says "Modifier private is not allowed here" What conclusion is someone can be wrong or some tutorial can be wrong but compiler cannot be wrong. So we can say there is no term access specifier in java everything is modifiers.
Nothing printed. The argument must be a pointer to a signed int, where the number of characters written so far is stored.
#include <stdio.h>
int main()
{
int val;
printf("blah %n blah\n", &val);
printf("val = %d\n", val);
return 0;
}
The previous code prints:
blah blah
val = 5
Sounds like you're expecting size_t
to be the same as unsigned long
(possibly 64 bits) when it's actually an unsigned int
(32 bits). Try using %zu
in both cases.
I'm not entirely certain though.
$('a[data-category="music"]')
It works. See Attribute Equals Selector [name=”value”].
Will it warn you if you pass a 32-bit unsigned integer to a %lu format? It should be fine since the conversion is well-defined and doesn't lose any information.
I've heard that some platforms define macros in <inttypes.h>
that you can insert into the format string literal but I don't see that header on my Windows C++ compiler, which implies it may not be cross-platform.
There isn't any in printf
- the two are synonyms.
>>> from datetime import datetime
>>> print(datetime.today().strftime("%H:%M %p"))
15:31 AM
Try replacing %I
with %H
.
By using "header guards":
#ifndef MYCLASS_H
#define MYCLASS_H
// This is unnecessary, see comments.
//#pragma once
// MyClass.h
#include <winsock2.h>
class MyClass
{
// methods
public:
MyClass(unsigned short port);
virtual ~MyClass(void);
};
#endif
Where is the documentation which lists the format specifiers supported by the
Date()
object?
I stumbled across this today and was quite surprised that no one took the time to answer this simple question. True, there are many libraries out there to help with date manipulation. Some are better than others. But that wasn't the question asked.
AFAIK, pure JavaScript doesn't support format specifiers the way you have indicated you'd like to use them. But it does support methods for formatting dates and/or times, such as .toLocaleDateString()
, .toLocaleTimeString()
, and .toUTCString()
.
The Date
object reference I use most frequently is on the w3schools.com website (but a quick Google search will reveal many more that may better meet your needs).
Also note that the Date Object Properties section provides a link to prototype
, which illustrates some ways you can extend the Date object with custom methods. There has been some debate in the JavaScript community over the years about whether or not this is best practice, and I am not advocating for or against it, just pointing out its existence.
Label1.Text = dt.ToString("dd MMM yyyy | hh:mm | ff | zzz | zz | z");
will output:
07 Mai 2009 | 08:16 | 13 | +02:00 | +02 | +2
I'm in Denmark, my Offset from GMT is +2 hours, witch is correct.
if you need to get the CLIENT Offset, I recommend that you check a little trick that I did. The Page is in a Server in UK where GMT is +00:00 and, as you can see you will get your local GMT Offset.
Regarding you comment, I did:
DateTime dt1 = DateTime.Now;
DateTime dt2 = dt1.ToUniversalTime();
Label1.Text = dt1.ToString("dd MMM yyyy | hh:mm | ff | zzz | zz | z");
Label2.Text = dt2.ToString("dd MMM yyyy | hh:mm | FF | ZZZ | ZZ | Z");
and I get this:
07 Mai 2009 | 08:24 | 14 | +02:00 | +02 | +2
07 Mai 2009 | 06:24 | 14 | ZZZ | ZZ | Z
I get no Exception, just ... it does nothing with capital Z :(
I'm sorry, but am I missing something?
Reading carefully the MSDN on Custom Date and Time Format Strings
there is no support for uppercase 'Z'.
You should add that you have to add an extra ' to escape an exising ' in SQL Server:
smith's -> smith''s
This will give you exactly the strings that you asked for:
string s = "String goes here";
string lineAlignedRight = String.Format("{0,27}", s);
string lineAlignedCenter = String.Format("{0,-27}",
String.Format("{0," + ((27 + s.Length) / 2).ToString() + "}", s));
string lineAlignedLeft = String.Format("{0,-27}", s);
this error basically comes when you use the object before using it.
I know it's an old thread, but I just looked into schemas myself and think the following could be another good candidate for schema usage:
In a Datawarehouse, with data coming from different sources, you can use a different schema for each source, and then e.g. control access based on the schemas. Also avoids the possible naming collisions between the various source, as another poster replied above.
Why not just do this?
double f = 359.01335;
printf("%g", round(f * 1000.0) / 1000.0);
File outputfile = new File("image.jpg");
ImageIO.write(bufferedImage, "jpg", outputfile);
Here is my solution, there is no way to use momemt.js.Here is DataTable with Two DatePickers for DateRange (To and From) Filter.
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex) {
var min = $('#min').datepicker("getDate");
var max = $('#max').datepicker("getDate");
var startDate = new Date(data[4]);
if (min == null && max == null) { return true; }
if (min == null && startDate <= max) { return true; }
if (max == null && startDate >= min) { return true; }
if (startDate <= max && startDate >= min) { return true; }
return false;
}
);
If you only have one occurrence of the target string you can use:
str[target] = ''
or
str.sub(target, '')
If you have multiple occurrences of target use:
str.gsub(target, '')
For instance:
asdf = 'foo bar'
asdf['bar'] = ''
asdf #=> "foo "
asdf = 'foo bar'
asdf.sub('bar', '') #=> "foo "
asdf = asdf + asdf #=> "foo barfoo bar"
asdf.gsub('bar', '') #=> "foo foo "
If you need to do in-place substitutions use the "!"
versions of gsub!
and sub!
.
For me in IntelliJ it was showing me a popup to import the existing project as gradle project. I just clicked ok on it and then the folder structure appeared properly.
Change the access modifier of
counter
topublic volatile
As other people have mentioned, this on its own isn't actually safe at all. The point of volatile
is that multiple threads running on multiple CPUs can and will cache data and re-order instructions.
If it is not volatile
, and CPU A increments a value, then CPU B may not actually see that incremented value until some time later, which may cause problems.
If it is volatile
, this just ensures the two CPUs see the same data at the same time. It doesn't stop them at all from interleaving their reads and write operations which is the problem you are trying to avoid.
lock(this.locker) this.counter++
;
This is safe to do (provided you remember to lock
everywhere else that you access this.counter
). It prevents any other threads from executing any other code which is guarded by locker
.
Using locks also, prevents the multi-CPU reordering problems as above, which is great.
The problem is, locking is slow, and if you re-use the locker
in some other place which is not really related then you can end up blocking your other threads for no reason.
Interlocked.Increment(ref this.counter);
This is safe, as it effectively does the read, increment, and write in 'one hit' which can't be interrupted. Because of this, it won't affect any other code, and you don't need to remember to lock elsewhere either. It's also very fast (as MSDN says, on modern CPUs, this is often literally a single CPU instruction).
I'm not entirely sure however if it gets around other CPUs reordering things, or if you also need to combine volatile with the increment.
InterlockedNotes:
As volatile
doesn't prevent these kinds of multithreading issues, what's it for? A good example is saying you have two threads, one which always writes to a variable (say queueLength
), and one which always reads from that same variable.
If queueLength
is not volatile, thread A may write five times, but thread B may see those writes as being delayed (or even potentially in the wrong order).
A solution would be to lock, but you could also use volatile in this situation. This would ensure that thread B will always see the most up-to-date thing that thread A has written. Note however that this logic only works if you have writers who never read, and readers who never write, and if the thing you're writing is an atomic value. As soon as you do a single read-modify-write, you need to go to Interlocked operations or use a Lock.
In case you'd like to do it with async:
const request = async <T>(param1: string, param2: number) => {
const res = await func();
return res.response() as T;
}
And a more complex pattern, in case you'd like to wrap your function inside a generic counterpart, such as memoization (Example uses fast-memoize):
const request = memoize(
async <T>(
url: string,
token?: string
) => {
// Perform your code here
}
);
See how you define the generic after the memoizing function.
I often need to run more code per condition, by using: ( , , )
multiple code elements can execute:
var a = 2;
var b = 3;
var c = 0;
( a < b ? ( alert('hi'), a=3, b=2, c=a*b ) : ( alert('by'), a=4, b=10, c=a/b ) );
The most concise solution if you need the dates to be in Date format:
library(zoo)
month <- "2000-03"
as.Date(as.yearmon(month))
[1] "2000-03-01"
as.Date
will fix the first day of each month to a yearmon object for you.
You could also check the request accept content type as specified in the rfc. That way you can render by default HTML and where your client accept application/jason you can return json in your response without a template being required
It will be really easy to solve your problem with the library I created. It is called Atributika.
let calculatedCoffee: Int = 768
let g = Style("g").font(.boldSystemFont(ofSize: 12)).foregroundColor(.red)
let all = Style.font(.systemFont(ofSize: 12))
let str = "\(calculatedCoffee)<g>g</g>".style(tags: g)
.styleAll(all)
.attributedString
label.attributedText = str
You can find it here https://github.com/psharanda/Atributika
Local Computer FQDN via dotNet class
[System.Net.Dns]::GetHostEntry([string]$env:computername).HostName
or
[System.Net.Dns]::GetHostEntry([string]"localhost").HostName
Reference:
note: GetHostByName method is obsolete
Local computer FQDN via WMI query
$myFQDN=(Get-WmiObject win32_computersystem).DNSHostName+"."+(Get-WmiObject win32_computersystem).Domain
Write-Host $myFQDN
Reference:
To copy artifact in specified location use copy
instead of get.
mvn org.apache.maven.plugins:maven-dependency-plugin:3.1.2:copy \
-DrepoUrl=someRepositoryUrl \
-Dartifact="com.acme:foo:RELEASE:jar" -Dmdep.stripVersion -DoutputDirectory=/tmp/
In Java 8 atomic classes have been extended with two interesting functions:
Both are using the updateFunction to perform update of the atomic value. The difference is that the first one returns old value and the second one return the new value. The updateFunction may be implemented to do more complex "compare and set" operations than the standard one. For example it can check that atomic counter doesn't go below zero, normally it would require synchronization, and here the code is lock-free:
public class Counter {
private final AtomicInteger number;
public Counter(int number) {
this.number = new AtomicInteger(number);
}
/** @return true if still can decrease */
public boolean dec() {
// updateAndGet(fn) executed atomically:
return number.updateAndGet(n -> (n > 0) ? n - 1 : n) > 0;
}
}
The code is taken from Java Atomic Example.
While rolling stone's answer is good, straightforward and functional, I think there are two things it does not solve.
Introduce the content types framework, which exposes some objects that allow us to create a "generic foreign key" on the PhoneNumber model. Then, we can define the reverse relationship on Dude and Business
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db import models
class PhoneNumber(models.Model):
number = models.CharField()
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
owner = GenericForeignKey()
class Dude(models.Model):
numbers = GenericRelation(PhoneNumber)
class Business(models.Model):
numbers = GenericRelation(PhoneNumber)
See the docs for details, and perhaps check out this article for a quick tutorial.
Also, here is an article that argues against the use of Generic FKs.
Steps to upload project to git:-
step1-open cmd and change current working directory to your project location.
step2-Initialize your project directory as a Git repository.
$ git init
step3-Add files in your local repository.
$ add .
step4-Commit the files that you've staged in your local repository.
$ git commit -m "First commit"
step5-Copy the remote repository url.
step6-add the remote repository url as origin in your local location.
$ git add origin copied_remote_repository_url
step7-confirm your origin is updated ot not.
$ git remote show origin
step8-push the changed to your github repository
$ git push origin master.
In Web.API this attribute can be added using Microsoft.AspNet.WebApi.Cors
as detailed at http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
In MVC you could create a filter attribute to do this work for you:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,
AllowMultiple = true, Inherited = true)]
public class EnableCorsAttribute : FilterAttribute, IActionFilter {
private const string IncomingOriginHeader = "Origin";
private const string OutgoingOriginHeader = "Access-Control-Allow-Origin";
private const string OutgoingMethodsHeader = "Access-Control-Allow-Methods";
private const string OutgoingAgeHeader = "Access-Control-Max-Age";
public void OnActionExecuted(ActionExecutedContext filterContext) {
// Do nothing
}
public void OnActionExecuting(ActionExecutingContext filterContext)
{
var isLocal = filterContext.HttpContext.Request.IsLocal;
var originHeader =
filterContext.HttpContext.Request.Headers.Get(IncomingOriginHeader);
var response = filterContext.HttpContext.Response;
if (!String.IsNullOrWhiteSpace(originHeader) &&
(isLocal || IsAllowedOrigin(originHeader))) {
response.AddHeader(OutgoingOriginHeader, originHeader);
response.AddHeader(OutgoingMethodsHeader, "GET,POST,OPTIONS");
response.AddHeader(OutgoingAgeHeader, "3600");
}
}
protected bool IsAllowedOrigin(string origin) {
// ** replace with your own logic to check the origin header
return true;
}
}
Then either enable it for specific actions / controllers:
[EnableCors]
public class SecurityController : Controller {
// *snip*
[EnableCors]
public ActionResult SignIn(Guid key, string email, string password) {
Or add it for all controllers in Global.asax.cs
protected void Application_Start() {
// *Snip* any existing code
// Register global filter
GlobalFilters.Filters.Add(new EnableCorsAttribute());
RegisterGlobalFilters(GlobalFilters.Filters);
// *snip* existing code
}
you can use editor.fontSize
into your setting.json
file of the editor.
for example :
{
"editor.fontSize": 14
}
I was trying to select an area of svg with a rectangle and get all the elements from it. For this, element.getBoundingClientRect() worked perfectly for me. It returns current coordinates of svg elements regardless of whether svg is scaled or transformed.
I have done quite a bit of what you're talking about, and SOAP interoperability between platforms has one cardinal rule: CONTRACT FIRST. Do not derive your WSDL from code and then try to generate a client on a different platform. Anything more than "Hello World" type functions will very likely fail to generate code, fail to talk at runtime or (my favorite) fail to properly send or receive all of the data without raising an error.
That said, WSDL is complicated, nasty stuff and I avoid writing it from scratch whenever possible. Here are some guidelines for reliable interop of services (using Web References, WCF, Axis2/Java, WS02, Ruby, Python, whatever):
</rant>
:)
client text protocol
POST http://127.0.0.1/bom/create HTTP/1.1
Content-Type: application/json
User-Agent: PostmanRuntime/7.25.0
Accept: */*
Postman-Token: 50ecfbfe-741f-4a2b-a3d3-cdf162ada27f
Host: 127.0.0.1
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 405
{
"fwoid": 1,
"list": [
{
"bomIndex": "10001",
"desc": "?GH 1.25 13pin ???? ??",
"pn": "084.0001.0036",
"preUse": 1,
"type": "?? ???-??PCB??"
},
{
"bomIndex": "10002",
"desc": "????-?????",
"pn": "Z.08.013.0051",
"preUse": 1,
"type": "E060A0302301"
}
]
}
HTTP/1.1 200 OK
Connection: keep-alive
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Content-Type: application/json
Date: Mon, 01 Jun 2020 11:23:42 GMT
Content-Length: 40
{"code":"0","message":"BOM????"}
a springboot Controller code as below:
@PostMapping("/bom/create")
@ApiOperation(value = "??BOM")
@BusinessOperation(module = "BOM",methods = "??BOM")
public JsonResult save(@RequestBody BOMSaveQuery query)
{
return bomService.saveBomList(query);
}
when i debug on loopback interface,it works ok. while deploy on internet server via bat command, i got an error
ServletInvocableHandlerMethod - Could not resolve parameter [0] in public XXXController.save(com.h2.mes.query.BOMSaveQuery): JSON parse error: Invalid UTF-8 middle byte 0x3f; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 middle byte 0x3f
at [Source: (PushbackInputStream); line: 9, column: 32] (through reference chain: com.h2.mes.query.BOMSaveQuery["list"]->java.util.ArrayList[0]->com.h2.mes.vo.BOMVO["type"])
2020-06-01 15:37:50.251 MES [XNIO-1 task-13] WARN o.s.w.s.m.s.DefaultHandlerExceptionResolver - Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Invalid UTF-8 middle byte 0x3f; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 middle byte 0x3f
at [Source: (PushbackInputStream); line: 9, column: 32] (through reference chain: com.h2.mes.query.BOMSaveQuery["list"]->java.util.ArrayList[0]->com.h2.mes.vo.BOMVO["type"])]
2020-06-01 15:37:50.251 MES [XNIO-1 task-13] DEBUG o.s.web.servlet.DispatcherServlet - Completed 400 BAD_REQUEST
2020-06-01 15:37:50.251 MES [XNIO-1 task-13] DEBUG o.s.web.servlet.DispatcherServlet - "ERROR" dispatch for POST "/error", parameters={}
add a jvm arguement works for me. java -Dfile.encoding=UTF-8
In my case adding multiDexEnabled true in Android/build/build.gradle file compiled the files.
I will look into removing this in the future, as in the documentation it says 'Before configuring your app to enable use of 64K or more method references, you should take steps to reduce the total number of references called by your app code, including methods defined by your app code or included libraries.'
defaultConfig {
applicationId "com.peoplesenergyapp"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
multiDexEnabled true // <-add this
}
This seems to be similar to this issue: False "Property does not exist on type 'never'" when changing value inside callback with strictNullChecks
, which is closed as a duplicate of this issue (discussion): Trade-offs in Control Flow Analysis.
That discussion is pretty long, if you can't find a good solution there you can try this:
if (instance == null) {
console.log('Instance is null or undefined');
} else {
console.log(instance!.name); // ok now
}
from superuser accepted answer:
sudo mysql -u root
use mysql;
update user set plugin='' where User='root';
flush privileges;
exit;
If the user name that is in the connection string has access to more then one database you have to specify the database you want the connection string to connect to. If your user has only one database available then you are correct that it doesn't matter. But it is good practice to put this in your connection string.
as your service is already setup, simply add a broadcast receiver in your service:
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
//action for sms received
}
else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
//action for phone state changed
}
}
};
in your service's onCreate
do this:
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction("your_action_strings"); //further more
filter.addAction("your_action_strings"); //further more
registerReceiver(receiver, filter);
and in your service's onDestroy
:
unregisterReceiver(receiver);
and you are good to go to receive broadcast for what ever filters you mention in onCreate
. Make sure to add any permission if required. for e.g.
<uses-permission android:name="android.permission.RECEIVE_SMS" />
Here is another simple solution using np.histogram()
method.
myarray = np.random.random(100)
results, edges = np.histogram(myarray, normed=True)
binWidth = edges[1] - edges[0]
plt.bar(edges[:-1], results*binWidth, binWidth)
You can indeed check that the total sums up to 1 with:
> print sum(results*binWidth)
1.0
You can do it with 2 images only. 1 blank stars, 1 filled stars.
Overlay filled image on the top of the other one. and convert rating number into percentage and use it as width of fillter image.
.containerdiv {
border: 0;
float: left;
position: relative;
width: 300px;
}
.cornerimage {
border: 0;
position: absolute;
top: 0;
left: 0;
overflow: hidden;
}
img{
max-width: 300px;
}
My solution is based on dsuess user solution, which didn't work in IE for me, because I had to click one more time in the textbox to be able to type in. Therefore I adapted it only to Chrome:
$(window).on('load', function () {
if (navigator.userAgent.indexOf("Chrome") != -1) {
$('#myTextBox').attr('readonly', 'true');
$('#myTextBox').addClass("forceWhiteBackground");
$('#myTextBox').focus(function () {
$('#myTextBox').removeAttr('readonly');
$('#myTextBox').removeClass('forceWhiteBackground');
});
}
});
In your css add this:
.forceWhiteBackground {
background-color:white !important;
}
To find which field has invalid characters:
SELECT * FROM Staging.APARMRE1 FOR XML AUTO, TYPE
You can test it with this query:
SELECT top 1 'char 31: '+char(31)+' (hex 0x1F)' field
from sysobjects
FOR XML AUTO, TYPE
The result will be:
Msg 6841, Level 16, State 1, Line 3 FOR XML could not serialize the data for node 'field' because it contains a character (0x001F) which is not allowed in XML. To retrieve this data using FOR XML, convert it to binary, varbinary or image data type and use the BINARY BASE64 directive.
It is very useful when you write xml files and get error of invalid characters when validate it.
The "no version information available" means that the library version number is lower on the shared object. For example, if your major.minor.patch number is 7.15.5 on the machine where you build the binary, and the major.minor.patch number is 7.12.1 on the installation machine, ld will print the warning.
You can fix this by compiling with a library (headers and shared objects) that matches the shared object version shipped with your target OS. E.g., if you are going to install to RedHat 3.4.6-9 you don't want to compile on Debian 4.1.1-21. This is one of the reasons that most distributions ship for specific linux distro numbers.
Otherwise, you can statically link. However, you don't want to do this with something like PAM, so you want to actually install a development environment that matches your client's production environment (or at least install and link against the correct library versions.)
Advice you get to rename the .so files (padding them with version numbers,) stems from a time when shared object libraries did not use versioned symbols. So don't expect that playing with the .so.n.n.n naming scheme is going to help (much - it might help if you system has been trashed.)
You last option will be compiling with a library with a different minor version number, using a custom linking script: http://www.redhat.com/docs/manuals/enterprise/RHEL-4-Manual/gnu-linker/scripts.html
To do this, you'll need to write a custom script, and you'll need a custom installer that runs ld against your client's shared objects, using the custom script. This requires that your client have gcc or ld on their production system.
print didn't transition from statement to function until Python 3.0. If you're using older Python then you can suppress the newline with a trailing comma like so:
print "Foo %10s bar" % baz,
I think you are wrapping your exception in another exception (which isn't in your code above). If you try out this code:
public static void main(String[] args) {
try {
throw new RuntimeException("Cannot move file");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
}
}
...you will see a popup that says exactly what you want.
However, to solve your problem (the wrapped exception) you need get to the "root" exception with the "correct" message. To do this you need to create a own recursive method getRootCause
:
public static void main(String[] args) {
try {
throw new Exception(new RuntimeException("Cannot move file"));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,
"Error: " + getRootCause(ex).getMessage());
}
}
public static Throwable getRootCause(Throwable throwable) {
if (throwable.getCause() != null)
return getRootCause(throwable.getCause());
return throwable;
}
Note: Unwrapping exceptions like this however, sort of breaks the abstractions. I encourage you to find out why the exception is wrapped and ask yourself if it makes sense.
I guess because CSS already has text-align:right
, AFAIK, Bootstrap doesn't have a special class for it.
Bootstrap does have "pull-right" for floating divs, etc. to the right.
Bootstrap 2.3 just came out and added text alignment styles:
Bootstrap 2.3 released (2013-02-07)
In Java 8 it can be done with:
String s = "edcba".chars()
.sorted()
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
A slightly shorter alternative that works with a Stream of Strings of length one (each character in the unsorted String is converted into a String in the Stream) is:
String sorted =
Stream.of("edcba".split(""))
.sorted()
.collect(Collectors.joining());
I tried this and everything worked by changing the npm directory.
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
export PATH=~/.npm-global/bin:$PATH
source ~/.profile
npm install -g jshint
ng --version
You are mixing the deprecated mysql extension with mysqli.
Try something like:
$sql = mysqli_query($success, "SELECT * FROM login WHERE username = '".$_POST['username']."' and password = '".md5($_POST['password'])."'");
$row = mysqli_num_rows($sql);
I use simple grep
inside function in bash script to receive properties from .properties
file.
This properties file I use in two places - to setup dev environment and as application parameters.
I believe that grep
may work slow in big loops but it solves my needs when I want to prepare dev
environment.
Hope, someone will find this useful.
Example:
File: setup.sh
#!/bin/bash
ENV=${1:-dev}
function prop {
grep "${1}" env/${ENV}.properties|cut -d'=' -f2
}
docker create \
--name=myapp-storage \
-p $(prop 'app.storage.address'):$(prop 'app.storage.port'):9000 \
-h $(prop 'app.storage.host') \
-e STORAGE_ACCESS_KEY="$(prop 'app.storage.access-key')" \
-e STORAGE_SECRET_KEY="$(prop 'app.storage.secret-key')" \
-e STORAGE_BUCKET="$(prop 'app.storage.bucket')" \
-v "$(prop 'app.data-path')/storage":/app/storage \
myapp-storage:latest
docker create \
--name=myapp-database \
-p "$(prop 'app.database.address')":"$(prop 'app.database.port')":5432 \
-h "$(prop 'app.database.host')" \
-e POSTGRES_USER="$(prop 'app.database.user')" \
-e POSTGRES_PASSWORD="$(prop 'app.database.pass')" \
-e POSTGRES_DB="$(prop 'app.database.main')" \
-e PGDATA="/app/database" \
-v "$(prop 'app.data-path')/database":/app/database \
postgres:9.5
File: env/dev.properties
app.data-path=/apps/myapp/
#==========================================================
# Server properties
#==========================================================
app.server.address=127.0.0.70
app.server.host=dev.myapp.com
app.server.port=8080
#==========================================================
# Backend properties
#==========================================================
app.backend.address=127.0.0.70
app.backend.host=dev.myapp.com
app.backend.port=8081
app.backend.maximum.threads=5
#==========================================================
# Database properties
#==========================================================
app.database.address=127.0.0.70
app.database.host=database.myapp.com
app.database.port=5432
app.database.user=dev-user-name
app.database.pass=dev-password
app.database.main=dev-database
#==========================================================
# Storage properties
#==========================================================
app.storage.address=127.0.0.70
app.storage.host=storage.myapp.com
app.storage.port=4569
app.storage.endpoint=http://storage.myapp.com:4569
app.storage.access-key=dev-access-key
app.storage.secret-key=dev-secret-key
app.storage.region=us-east-1
app.storage.bucket=dev-bucket
Usage:
./setup.sh dev
The following is not exactly the same but similar, I was searching for a snippet to add a call to the interface method, but found this question, so I decided to add this snippet for those who were searching for it like me and found this question:
public class MyClass
{
//... class code goes here
public interface DataLoadFinishedListener {
public void onDataLoadFinishedListener(int data_type);
}
private DataLoadFinishedListener m_lDataLoadFinished;
public void setDataLoadFinishedListener(DataLoadFinishedListener dlf){
this.m_lDataLoadFinished = dlf;
}
private void someOtherMethodOfMyClass()
{
m_lDataLoadFinished.onDataLoadFinishedListener(1);
}
}
Usage is as follows:
myClassObj.setDataLoadFinishedListener(new MyClass.DataLoadFinishedListener() {
@Override
public void onDataLoadFinishedListener(int data_type) {
}
});
import time
current = time.time()
...job...
end = time.time()
diff = end - current
would that work for you?
I had the same problem before after tried to upgrade tensorflow, I solved it by reinstalling Tensorflow and Keras.
pip uninstall tensorflow
pip uninstall keras
Then:
pip install tensorflow
pip install keras
Anonymous FTP usage is covered by RFC 1635: How to Use Anonymous FTP:
What is Anonymous FTP?
Anonymous FTP is a means by which archive sites allow general access to their archives of information. These sites create a special account called "anonymous".
…
Traditionally, this special anonymous user account accepts any string as a password, although it is common to use either the password "guest" or one's electronic mail (e-mail) address. Some archive sites now explicitly ask for the user's e-mail address and will not allow login with the "guest" password. Providing an e-mail address is a courtesy that allows archive site operators to get some idea of who is using their services.
These are general recommendations, though. Each FTP server may have its own guidelines.
For sample use of the ftp
command on anonymous FTP access, see appendix A:
atlas.arc.nasa.gov% ftp naic.nasa.gov Connected to naic.nasa.gov. 220 naic.nasa.gov FTP server (Wed May 4 12:15:15 PDT 1994) ready. Name (naic.nasa.gov:amarine): anonymous 331 Guest login ok, send your complete e-mail address as password. Password: 230----------------------------------------------------------------- 230-Welcome to the NASA Network Applications and Info Center Archive 230- 230- Access to NAIC's online services is also available through: 230- 230- Gopher - naic.nasa.gov (port 70) 230- World-Wide-Web - http://naic.nasa.gov/naic/naic-home.html 230- 230- If you experience any problems please send email to 230- 230- [email protected] 230- 230- or call +1 (800) 858-9947 230----------------------------------------------------------------- 230- 230-Please read the file README 230- it was last modified on Fri Dec 10 13:06:33 1993 - 165 days ago 230 Guest login ok, access restrictions apply. ftp> cd files/rfc 250-Please read the file README.rfc 250- it was last modified on Fri Jul 30 16:47:29 1993 - 298 days ago 250 CWD command successful. ftp> get rfc959.txt 200 PORT command successful. 150 Opening ASCII mode data connection for rfc959.txt (147316 bytes). 226 Transfer complete. local: rfc959.txt remote: rfc959.txt 151249 bytes received in 0.9 seconds (1.6e+02 Kbytes/s) ftp> quit 221 Goodbye. atlas.arc.nasa.gov%
See also the example session at the University of Edinburgh site.
The maximum SqlDbType.VarChar size is 2147483647.
If you would use a generic oledb connection instead of sql, I found here there is also a LongVarChar datatype. Its max size is 2147483647.
cmd.Parameters.Add("@blah", OleDbType.LongVarChar, -1).Value = "very big string";
Boilerplate in software development can mean different things to different people but generally means the block of code that is used over and over again.
In MEAN stack development, this term refers to code generation through use of template. It's easier than hand coding the entire application from scratch and it gives the code block consistency and fewer bugs as it is clean, tested and proven code and it's open source so it is constantly getting updated or fixed therefore it saves a lot of time as using framework or code generator. For more information about MEAN stack, click here.
range()
can only work with integers, but dividing with the /
operator always results in a float value:
>>> 450 / 10
45.0
>>> range(450 / 10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer
Make the value an integer again:
for i in range(int(c / 10)):
or use the //
floor division operator:
for i in range(c // 10):
array.each do |element|
element.do_stuff
end
or
for element in array do
element.do_stuff
end
If you need index, you can use this:
array.each_with_index do |element,index|
element.do_stuff(index)
end
I also had the problem, hence me stumbling on this post. I added the following line of code before and after a Copy / Delete.
Delete
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
Copy
File.Copy(file, dest, true);
File.SetAttributes(dest, FileAttributes.Normal);
I had the same error everything was correct like the setting the folder permissions.
It looks like an bug in php in my case because when i delete my PHPSESSID cookie it was working again so aperently something was messed up and the session got removed but the cookie was still active so php had to define the cause differently and checking first if the session file is still they and give another error and not the permission error
In my case I had to implement MainActivity
as Serializable
too. Cause I needed to start a service from my MainActivity
:
public class MainActivity extends AppCompatActivity implements Serializable {
...
musicCover = new MusicCover(); // A Serializable Object
...
sIntent = new Intent(MainActivity.this, MusicPlayerService.class);
sIntent.setAction(MusicPlayerService.ACTION_INITIALIZE_COVER);
sIntent.putExtra(MusicPlayerService.EXTRA_COVER, musicCover);
startService(sIntent);
}
@media queries serve this purpose. Here's an example:
@media only screen and (max-width: 991px) and (min-width: 769px){
/* CSS that should be displayed if width is equal to or less than 991px and larger
than 768px goes here */
}
@media only screen and (max-width: 991px){
/* CSS that should be displayed if width is equal to or less than 991px goes here */
}
You should be using IllegalArgumentException
(IAE), not NullPointerException
(NPE) for the following reasons:
First, the NPE JavaDoc explicitly lists the cases where NPE is appropriate. Notice that all of them are thrown by the runtime when null
is used inappropriately. In contrast, the IAE JavaDoc couldn't be more clear: "Thrown to indicate that a method has been passed an illegal or inappropriate argument." Yup, that's you!
Second, when you see an NPE in a stack trace, what do you assume? Probably that someone dereferenced a null
. When you see IAE, you assume the caller of the method at the top of the stack passed in an illegal value. Again, the latter assumption is true, the former is misleading.
Third, since IAE is clearly designed for validating parameters, you have to assume it as the default choice of exception, so why would you choose NPE instead? Certainly not for different behavior -- do you really expect calling code to catch NPE's separately from IAE and do something different as a result? Are you trying to communicate a more specific error message? But you can do that in the exception message text anyway, as you should for all other incorrect parameters.
Fourth, all other incorrect parameter data will be IAE, so why not be consistent? Why is it that an illegal null
is so special that it deserves a separate exception from all other types of illegal arguments?
Finally, I accept the argument given by other answers that parts of the Java API use NPE in this manner. However, the Java API is inconsistent with everything from exception types to naming conventions, so I think just blindly copying (your favorite part of) the Java API isn't a good enough argument to trump these other considerations.
The method version
on ionic
object returns the current version in string
format.
web.xml
they are in the servlet container configuration files (server.xml
on tomcat)No. But the default servlet (mapped in a web.xml at a common location in your servlet container) should preferably disable file listings (so that users don't see the contents of your web folders):
listings true
Gets the time to wait while trying to establish a connection before terminating the attempt and generating an error. (MSDN, SqlConnection.ConnectionTimeout Property, 2013)
I wanna Disable an Input Field on a form and when i submit the form the values from the disabled form is not submitted.
Use Case: i am trying to get Lat Lng from Google Map and wanna Display it.. but dont want the user to edit it.
You can use the readonly
property in your input field
<input type="text" readonly="readonly" />
There's a much, much easier way. Do this:
MyComponent.vue
<template>
stuff here
</template>
<script>
import $ from 'jquery';
import 'selectize';
$(function() {
// use jquery
$('body').css('background-color', 'orange');
// use selectize, s jquery plugin
$('#myselect').selectize( options go here );
});
</script>
Make sure JQuery is installed first with npm install jquery
. Do the same with your plugin.
I have not yet seen a problem with the limit that did not involve large files stored within the document itself. There are already a variety of databases which are very efficient at storing/retrieving large files; they are called operating systems. The database exists as a layer over the operating system. If you are using a NoSQL solution for performance reasons, why would you want to add additional processing overhead to the access of your data by putting the DB layer between your application and your data?
JSON is a text format. So, if you are accessing your data through JSON, this is especially true if you have binary files because they have to be encoded in uuencode, hexadecimal, or Base 64. The conversion path might look like
binary file <> JSON (encoded) <> BSON (encoded)
It would be more efficient to put the path (URL) to the data file in your document and keep the data itself in binary.
If you really want to keep these files of unknown length in your DB, then you would probably be better off putting these in GridFS and not risking killing your concurrency when the large files are accessed.
This answer is an attempt to address: how to control java version system-wide (not just in currently running shell) when several versions of JDK are installed for development purposes on macOS El Capitan or newer (Sierra, High Sierra, Mojave). As far as I can tell, none of the current answers do that (*).
As a developer, I use several JDKs, and I want to switch from one to the other easily. Usually I have the latest stable one for general use, and others for tests. But I don't want the system (e.g. when I start my IDE) to use the latest "early access" version I have for now. I want to control system's default, and that should be latest stable.
The following approach works with Java 7 to 12 at least (early access at the time of this writing), with Oracle JDK or OpenJDK (including builds by AdoptOpenJDK produced after mid-October 2018).
/Library/Java/JavaVirtualMachines
. The system will pick the highest version by default. Contents/Info.plist
to Info.plist.disabled
. That JDK can still be used when $JAVA_HOME
points to it, or explicitly referenced in a script or configuration. It will simply be ignored by system's java
command.System launcher will use the JDK with highest version among those that have an Info.plist
file.
When working in a shell with alternate JDK, pick your method among existing answers (jenv
, or custom aliases/scripts around /usr/libexec/java_home
, etc).
Details of investigation in this gist.
(*) Current answers are either obsolete (no longer valid for macOS El Capitan or Sierra), or only address a single JDK, or do not address the system-wide aspect. Many explain how to change $JAVA_HOME
, but this only affects the current shell and what is launched from there. It won't affect an application started from OS launcher (unless you change the right file and logout/login, which is tedious). Same for jenv, it's cool and all, but as far as I can tell it merely changes environment variables, so it has the same limitation.
SHA isn't encryption, it's a one-way hash function. AES (Advanced_Encryption_Standard) is a symmetric encryption standard.
https://mathoverflow.net/questions/16393/finding-a-cycle-of-fixed-length I like this solution the best specially for 4 length:)
Also phys wizard says u have to do O(V^2). I believe that we need only O(V)/O(V+E). If the graph is connected then DFS will visit all nodes. If the graph has connected sub graphs then each time we run a DFS on a vertex of this sub graph we will find the connected vertices and wont have to consider these for the next run of the DFS. Therefore the possibility of running for each vertex is incorrect.
You had better use find_library command instead of link_directories. Concretely speaking there are two ways:
designate the path within the command
find_library(NAMES gtest PATHS path1 path2 ... pathN)
set the variable CMAKE_LIBRARY_PATH
set(CMAKE_LIBRARY_PATH path1 path2)
find_library(NAMES gtest)
the reason is as flowings:
Note This command is rarely necessary and should be avoided where there are other choices. Prefer to pass full absolute paths to libraries where possible, since this ensures the correct library will always be linked. The find_library() command provides the full path, which can generally be used directly in calls to target_link_libraries(). Situations where a library search path may be needed include: Project generators like Xcode where the user can switch target architecture at build time, but a full path to a library cannot be used because it only provides one architecture (i.e. it is not a universal binary).
Libraries may themselves have other private library dependencies that expect to be found via RPATH mechanisms, but some linkers are not able to fully decode those paths (e.g. due to the presence of things like $ORIGIN).
If a library search path must be provided, prefer to localize the effect where possible by using the target_link_directories() command rather than link_directories(). The target-specific command can also control how the search directories propagate to other dependent targets.
<input type='text'
name='t1'
id='t1'
maxlength=10
placeholder='typing some text' >
<p></p>
This is the text box, it has a fixed length of 10 characters, and if you can try but this text box does not contain maximum length 10 character
use this dependency:
toast: ^0.1.3
then import the dependency of toast in the page :
import 'package:toast/toast.dart';
then on onTap() of the widget:
Toast.show("Toast plugin app", context,duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
Expanding on StanleyH's answer, and trying to find the minimum required, here is what I implemented:
JavaScript (called once from somewhere like $(document).ready()
):
function doubleScroll(){
$(".topScrollVisible").scroll(function(){
$(".tableWrapper")
.scrollLeft($(".topScrollVisible").scrollLeft());
});
$(".tableWrapper").scroll(function(){
$(".topScrollVisible")
.scrollLeft($(".tableWrapper").scrollLeft());
});
}
HTML (note that the widths will change the scroll bar length):
<div class="topScrollVisible" style="overflow-x:scroll">
<div class="topScrollTableLength" style="width:1520px; height:20px">
</div>
</div>
<div class="tableWrapper" style="overflow:auto; height:100%;">
<table id="myTable" style="width:1470px" class="myTableClass">
...
</table>
That's it.
if you just need it for db-related stuff, some OR Mappers (e.g. NHibernate) support transactinos out of the box per default.
For me, using OS X Catalina:
Changing from AllowOverride None
to AllowOverride All
is the one that works.
httpd.conf
is located on /etc/apache2/httpd.conf
.
Env: PHP7. MySQL8.
The sp_xml_preparedocument
stored procedure will parse the XML and the OPENXML
rowset provider will show you a relational view of the XML data.
For details and more examples check the OPENXML documentation.
As for your question,
DECLARE @XML XML
SET @XML = '<rows><row>
<IdInvernadero>8</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>8</IdCaracteristica1>
<IdCaracteristica2>8</IdCaracteristica2>
<Cantidad>25</Cantidad>
<Folio>4568457</Folio>
</row>
<row>
<IdInvernadero>3</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>1</IdCaracteristica1>
<IdCaracteristica2>2</IdCaracteristica2>
<Cantidad>72</Cantidad>
<Folio>4568457</Folio>
</row></rows>'
DECLARE @handle INT
DECLARE @PrepareXmlStatus INT
EXEC @PrepareXmlStatus= sp_xml_preparedocument @handle OUTPUT, @XML
SELECT *
FROM OPENXML(@handle, '/rows/row', 2)
WITH (
IdInvernadero INT,
IdProducto INT,
IdCaracteristica1 INT,
IdCaracteristica2 INT,
Cantidad INT,
Folio INT
)
EXEC sp_xml_removedocument @handle
Here is a script I run to restart adb (Android Debug Bridge) server:
#!/usr/bin/env bash
## Summary: restart adb (Android Debug Brdige) server.
## adb binary full path
ADB_BIN=./adb
if pgrep adb >/dev/null 2>&1
then
echo "adb is running"
echo "terminating adb ..."
$ADB_BIN kill-server
if pgrep adb >/dev/null 2>&1
then
echo "did not work"
echo "kill adb processes by killall"
killall -9 adb
else
echo "terminated"
fi
else
echo "adb is not running"
fi
echo "starting adb ..."
$ADB_BIN start-server
echo "adb process:"
echo `pgrep adb`
echo "done"
# END
Read this Bug Issue: http://bugs.jquery.com/ticket/11586
Quoting the RFC 2616 Fielding
The
DELETE
method requests that the origin server delete the resource identified by the Request-URI.
So you need to pass the data in the URI
$.ajax({
url: urlCall + '?' + $.param({"Id": Id, "bolDeleteReq" : bolDeleteReq}),
type: 'DELETE',
success: callback || $.noop,
error: errorCallback || $.noop
});
Use the constructor that takes a File
and a boolean
FileOutputStream(File file, boolean append)
and set the boolean to true
. That way, the data you write will be appended to the end of the file, rather than overwriting what was already there.
Template argument deduction for class templates
[*this]{ std::cout << could << " be " << useful << '\n'; }
[[fallthrough]]
, [[nodiscard]]
, [[maybe_unused]]
attributes
using
in attributes to avoid having to repeat an attribute namespace.
Compilers are now required to ignore non-standard attributes they don't recognize.
Simple static_assert(expression);
with no string
no throw
unless throw()
, and throw()
is noexcept(true)
.
std::tie
with auto
const auto [it, inserted] = map.insert( {"foo", bar} );
it
and inserted
with deduced type from the pair
that map::insert
returns.std::array
s and relatively flat structsif (init; condition)
and switch (init; condition)
if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
if(decl)
to cases where decl
isn't convertible-to-bool sensibly.Generalizing range-based for loops
Fixed order-of-evaluation for (some) expressions with some modifications
.then
on future work.Forward progress guarantees (FPG) (also, FPGs for parallel algorithms)
u8'U', u8'T', u8'F', u8'8'
character literals (string already existed)
inherited constructors fixes to some corner cases (see P0136R0 for examples of behavior changes)
std::string
like reference-to-character-array or substringstring const&
again. Also can make parsing a bajillion times faster."hello world"sv
char_traits
std::byte
off more than they could chew.
std::invoke
std::apply
std::make_from_tuple
, std::apply
applied to object construction
is_invocable
, is_invocable_r
, invoke_result
result_of
is_invocable<Foo(Args...), R>
is "can you call Foo
with Args...
and get something compatible with R
", where R=void
is default.invoke_result<Foo, Args...>
is std::result_of_t<Foo(Args...)>
but apparently less confusing?[class.directory_iterator]
and [class.recursive_directory_iterator]
fstream
s can be opened with path
s, as well as with const path::value_type*
strings.
for_each_n
reduce
transform_reduce
exclusive_scan
inclusive_scan
transform_exclusive_scan
transform_inclusive_scan
Added for threading purposes, exposed even if you aren't using them threaded
atomic<T>
::is_always_lockfree
std::lock
pain when locking more than one mutex at a time.std
algorithms, and related machinery[func.searchers]
and [alg.search]
std::function
for allocatorsstd::sample
, sampling from a range?
try_emplace
and insert_or_assign
Splicing for map<>
, unordered_map<>
, set<>
, and unordered_set<>
non-const .data()
for string.
non-member std::size
, std::empty
, std::data
std::begin
/end
The emplace
family of functions now returns a reference to the created object.
unique_ptr<T[]>
fixes and other unique_ptr
tweaks.weak_from_this
and some fixed to shared from thisstd
datatype improvements:{}
construction of std::tuple
and other improvementsC++17 library is based on C11 instead of C99
Reserved std[0-9]+
for future standard libraries
std
implementations exposedstd::clamp()
std::clamp( a, b, c ) == std::max( b, std::min( a, c ) )
roughlygcd
and lcm
std::uncaught_exceptions
std::as_const
std::bool_constant
_v
template variablesstd::void_t<T>
std::owner_less<void>
std::less<void>
, but for smart pointers to sort based on contentsstd::chrono
polishstd::conjunction
, std::disjunction
, std::negation
exposedstd::not_fn
std
std::less
.<codecvt>
memory_order_consume
result_of
, replaced with invoke_result
shared_ptr::unique
, it isn't very threadsafeIsocpp.org has has an independent list of changes since C++14; it has been partly pillaged.
Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.
Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.
Additional entries pillaged from SD-6 feature-test list.
clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.
these slides had some features missing elsewhere.
While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:
register
, keyword reserved for future usebool b; ++b;
<functional>
stuff, random_shuffle
std::function
There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:
P0505R0 (constexpr chrono)
P0418R2 (atomic tweaks)
P0512R0 (template argument deduction tweaks)
P0490R0 (structured binding tweaks)
P0513R0 (changes to std::hash
)
P0502R0 (parallel exceptions)
P0509R1 (updating restrictions on exception handling)
P0012R1 (make exception specifications be part of the type system)
P0510R0 (restrictions on variants)
P0504R0 (tags for optional/variant/any)
P0497R0 (shared ptr tweaks)
P0508R0 (structured bindings node handles)
P0521R0 (shared pointer use count and unique changes?)
https://isocpp.org/files/papers/p0636r0.html
I used the svn2git script and works like a charm.
You might find it very useful to sample Redis keys and group them by type. Salvatore has written a tool called redis-sampler that issues about 10000 RANDOMKEY
commands followed by a TYPE
on retrieved keys. In a matter of seconds, or minutes, you should get a fairly accurate view of the distribution of key types.
I've written an extension (unfortunately not anywhere open-source because it's work related), that adds a bit of introspection of key names via regexs that give you an idea of what kinds of application keys (according to whatever naming structure you're using), are stored in Redis. Combined with the more general output of redis-sampler, this should give you an extremely good idea of what's going on.
If you are going to be doing this a lot, it might be good to define a utility function that will let you use arbitrary brace substitutes instead, like
def custom_format(string, brackets, *args, **kwargs):
if len(brackets) != 2:
raise ValueError('Expected two brackets. Got {}.'.format(len(brackets)))
padded = string.replace('{', '{{').replace('}', '}}')
substituted = padded.replace(brackets[0], '{').replace(brackets[1], '}')
formatted = substituted.format(*args, **kwargs)
return formatted
>>> custom_format('{{[cmd]} process 1}', brackets='[]', cmd='firefox.exe')
'{{firefox.exe} process 1}'
Note that this will work either with brackets being a string of length 2 or an iterable of two strings (for multi-character delimiters).
It's platform-specific. But you can cast it to a known type.
printf("%lld\n", (long long) time(NULL));
I have another solution. If Alpha and Beta are your only extra class then why not make a static variable with the image of the class.
Like in Alpha class :
public class Alpha{
public static Alpha alpha;
public Alpha(){
this.alpha = this;
}
Now you you can call the function in Beta class by just using these lines :
new Alpha();
Alpha.alpha.DoSomethingAlpha();
You may already know that putting your Button inside of a ToolBar gives you this behavior, but if you want something that will work across ALL current themes with any sort of predictability, you'll need to create a new ControlTemplate.
Prashant's solution does not work with a Button not in a toolbar when the Button has focus. It also doesn't work 100% with the default theme in XP -- you can still see faint gray borders when your container Background is white.
The issue is how you're attempting to get the value. Things like...
if ( document.frm_new_user_request.u_isid.value == '' )
won't work. You need to find the element you want to get the value of first. It's not quite like a server side language where you can type in an object's reference name and a period to get or assign values.
document.getElementById('[id goes here]').value;
will work. Note: JavaScript is case-sensitive
I would recommend using:
var variablename = document.getElementById('[id goes here]');
or
var variablename = document.getElementById('[id goes here]').value;
Pandas DataFrames have the to_pickle
function which is useful for saving a DataFrame:
import pandas as pd
a = pd.DataFrame({'A':[0,1,0,1,0],'B':[True, True, False, False, False]})
print a
# A B
# 0 0 True
# 1 1 True
# 2 0 False
# 3 1 False
# 4 0 False
a.to_pickle('my_file.pkl')
b = pd.read_pickle('my_file.pkl')
print b
# A B
# 0 0 True
# 1 1 True
# 2 0 False
# 3 1 False
# 4 0 False
An option that hasn't been mentioned is using flex. By applying flex: 1
to the a
tag, it expands to fit the container.
div {_x000D_
height: 100px;_x000D_
width: 100px;_x000D_
display: flex;_x000D_
border: 1px solid;_x000D_
}_x000D_
_x000D_
a {_x000D_
flex: 1;_x000D_
}
_x000D_
<div>_x000D_
<a href="http://google.co.uk">Link</a>_x000D_
</div>
_x000D_
This code below works for me. I always use only single quotes, and it works fine. I suggest you should use only single quotes or only double quotes, but not mixed up.
$.ajax({
url: 'YourRestEndPoint',
headers: {
'Authorization':'Basic xxxxxxxxxxxxx',
'X-CSRF-TOKEN':'xxxxxxxxxxxxxxxxxxxx',
'Content-Type':'application/json'
},
method: 'POST',
dataType: 'json',
data: YourData,
success: function(data){
console.log('succes: '+data);
}
});
Thanks Hong, that was exactly the problem I was running into. The error you get suggests that the number of rows is wrong, but the problem is actually that the model has been trained using a command that ends up with the wrong names for parameters.
This is really a critical detail that is entirely non-obvious for lm and so on. Some of the tutorial make reference to doing lines like lm(olive$Area@olive$Palmitic)
- ending up with variable names of olive$Area NOT Area, so creating an entry using anewdata<-data.frame(Palmitic=2)
can't then be used. If you use lm(Area@Palmitic,data=olive)
then the variable names are right and prediction works.
The real problem is that the error message does not indicate the problem at all:
Warning message: 'anewdata' had 1 rows but variable(s) found to have X rows
Kotlin version below (Updated version of @paul-burke response:
fun openPDFDocument(context: Context, filename: String) {
//Create PDF Intent
val pdfFile = File(Environment.getExternalStorageDirectory().absolutePath + "/" + filename)
val pdfIntent = Intent(Intent.ACTION_VIEW)
pdfIntent.setDataAndType(Uri.fromFile(pdfFile), "application/pdf")
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
//Create Viewer Intent
val viewerIntent = Intent.createChooser(pdfIntent, "Open PDF")
context.startActivity(viewerIntent)
}
you can use following helper function:
function content(divSelector, value) {
document.querySelector(divSelector).innerHTML = value;
}
content('#content',"whatever");
Where #content
must be valid CSS selector
Here is working example.
Additionaly - today (2018.07.01) I made speed comparison for jquery and pure js solutions ( MacOs High Sierra 10.13.3 on Chrome 67.0.3396.99 (64-bit), Safari 11.0.3 (13604.5.6), Firefox 59.0.2 (64-bit) ):
document.getElementById("content").innerHTML = "whatever"; // pure JS
$('#content').html('whatever'); // jQuery
The jquery solution was slower than pure js solution: 69% on firefox, 61% on safari, 56% on chrome. The fastest browser for pure js was firefox with 560M operations per second, the second was safari 426M, and slowest was chrome 122M.
So the winners are pure js and firefox (3x faster than chrome!)
You can test it in your machine: https://jsperf.com/js-jquery-html-content-change
Update Model from Database doesn't works for me.
I had to remove the conflicted entity, then execute Update Model from Database, lastly rebuild the solution. After that, everything works fine.
JDK9+ solution using java.time.Duration
Duration.ofNanos(1_000_000L).toSeconds()
https://docs.oracle.com/javase/9/docs/api/java/time/Duration.html#ofNanos-long-
https://docs.oracle.com/javase/9/docs/api/java/time/Duration.html#toSeconds--
The graphicx
package provides the command \resizebox{width}{height}{object}
:
\documentclass{article}
\usepackage{graphicx}
\begin{document}
\hrule
%%%
\makeatletter%
\setlength{\@tempdima}{\the\columnwidth}% the, well columnwidth
\settowidth{\@tempdimb}{(\ref{Equ:TooLong})}% the width of the "(1)"
\addtolength{\@tempdima}{-\the\@tempdimb}% which cannot be used for the math
\addtolength{\@tempdima}{-1em}%
% There is probably some variable giving the required minimal distance
% between math and label, but because I do not know it I used 1em instead.
\addtolength{\@tempdima}{-1pt}% distance must be greater than "1em"
\xdef\Equ@width{\the\@tempdima}% space remaining for math
\begin{equation}%
\resizebox{\Equ@width}{!}{$\displaystyle{% to get everything inside "big"
A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z}$}%
\label{Equ:TooLong}%
\end{equation}%
\makeatother%
%%%
\hrule
\end{document}
In my case, I was referencing an integer id
column on a string user_id
column. I changed:
$table->string('user_id')
to:
$table->integer('user_id')->unsigned();
Hope it helps someone!
The options already listed are very good, however here a few more on this topic that I've researched and came across.
1) http://perfectionkills.com/exploring-canvas-drawing-techniques/
2) http://mcc.id.au/2010/signature.html
3) https://zipso.net/a-simple-touchscreen-sketchpad-using-javascript-and-html5/
And as always you may want to save the canvas to image:
http://www.html5canvastutorials.com/advanced/html5-canvas-save-drawing-as-an-image/
good luck and happy signing
You could do this two different ways. One is by using "as"
has_many :tasks, :as => :jobs
or
def jobs
self.tasks
end
Obviously the first one would be the best way to handle it.
if you are already using jQuery in your build just do this:
$(yourObject).length
It works nicely for me on objects, and I already had jQuery as a dependancy.
Try this:
foreach (var dept in employees.SelectMany(e => e.Departments))
{
dept.SomeProperty = null;
collection.Add(dept);
}
Yes you can negate the test as SiegeX has already pointed out.
However you shouldn't use regular expressions for this - it can fail if your path contains special characters. Try this instead:
[[ ":$PATH:" != *":$1:"* ]]
If you are using BIDS with SQL 2008 R2 you can only get the "Report Data" menu by clicking inside the actual report layout itself.
Click inside the actual report layout.
Now select "View" from the main menu bar.
Now select "Report Data" which is the last item.
Although all the answers given are correct, in fact they do not completely answer the question which was about using the [] construct and more generally filling the array with objects.
A more relevant answer can be found in how to build arrays of objects in PHP without specifying an index number? which clearly shows how to solve the problem.
All you have to do is create a subset of your dataframe where the isin method evaluates to False:
df = df[df['Column Name'].isin(['Value']) == False]
You cannot insert data because you have a quota of 0 on the tablespace. To fix this, run
ALTER USER <user> quota unlimited on <tablespace name>;
or
ALTER USER <user> quota 100M on <tablespace name>;
as a DBA user (depending on how much space you need / want to grant).
It works for me:
>>> def pyth_test (x1, x2):
... print x1 + x2
...
>>> pyth_test(1,2)
3
Make sure you define the function before you call it.
Just to make a more comprehensive answer, the C way of iterating over a string can apply in Python, if you really wanna force a square peg into a round hole.
i = 0
while i < len(str):
print str[i]
i += 1
But then again, why do that when strings are inherently iterable?
for i in str:
print i
box-sizing support is pretty good actually: http://caniuse.com/#search=box-sizing
So unless you target IE7, you should be able to solve this kind of issues using this property. A layer such as sass or less makes it easier to handle prefixed rules like that, btw.
Try this method to get path of original
image captured by camera.
public String getOriginalImagePath() {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, null, null, null);
int column_index_data = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToLast();
return cursor.getString(column_index_data);
}
This method will return path of the last image captured by camera. So this path would be of original image not of thumbnail bitmap.
You can just put r
in front of the string with your actual path, which denotes a raw string. For example:
data = open(r"C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener")
Others have already said that date literals in SQL Server require being surrounded with single quotes, but I wanted to add that you can solve your month/day mixup problem two ways (that is, the problem where 25 is seen as the month and 5 the day) :
Use an explicit Convert(datetime, 'datevalue', style)
where style is one of the numeric style codes, see Cast and Convert. The style parameter isn't just for converting dates to strings but also for determining how strings are parsed to dates.
Use a region-independent format for dates stored as strings. The one I use is 'yyyymmdd hh:mm:ss', or consider ISO format, yyyy-mm-ddThh:mi:ss.mmm
. Based on experimentation, there are NO other language-invariant format string. (Though I think you can include time zone at the end, see the above link).
If elem.find()
is not working for you, check that you are including JQuery script before angular script....
If your VARCHAR
column contains empty strings (which are not the same as NULL
for PostgreSQL as you might recall) you will have to use something in the line of the following to set a default:
ALTER TABLE presales ALTER COLUMN code TYPE NUMERIC(10,0)
USING COALESCE(NULLIF(code, '')::NUMERIC, 0);
(found with the help of this answer)
You can add org.apache.http
by using below code in app:Build gradle
dependencies {
compile 'org.apache.httpcomponents:httpclient:4.5'
}
Remember in Java a quoted String is still a String object. Therefore you can use the String function contains() to test for a range of Strings or integers using this method:
if ("A C Viking G M Ocelot".contains(mAnswer)) {...}
for numbers it's a tad more involved but still works:
if ("1 4 5 9 10 17 23 96457".contains(String.valueOf(mNumAnswer))) {...}
I see everyone here "took the long route!". As long as you are using MVC
, I strongly recommend you to use the easiest method over all which is Newtonsoft.JSON
... Also If you dont wanna use libraries check the answer links below. I took a good research time for this to solve the issue for my self and these are the solutions I found;
First implement the Newtonsoft.Json:
using Newtonsoft.Json;
Prepare your Ajax request:
$.ajax({
dataType: "json",
contentType: "application/json",
type: 'POST',
url: '/Controller/Action',
data: { 'items': JSON.stringify(lineItems), 'id': documentId }
});
Then go for your result class:
public ActionResult SaveData(string incoming, int documentId){
// DeSerialize into your Model as your Model Array
LineItem[] jsr = JsonConvert.DeserializeObject<LineItem[]>(Temp);
foreach(LineItem item in jsr){
// save some stuff
}
return Json(new { success = true, message = "Some message" });
}
See the trick up there? Instead of using JsonResult
I used regular ActionResult
with a string which includes json string. Then deserialized into my Model
so I can use this in any action method I have.
Plus sides of this method is :
JSON.stringify(Model)
Down sides of this method is :
Also check these questions and answers which are really helpfull:
https://stackoverflow.com/a/45682516/861019
another method :
https://stackoverflow.com/a/31656160/861019
and another method :
Even you don't need to run the loop for that.
You can delete all the node_modules by using the only single command:-
npm uninstall `ls -1 node_modules | tr '/\n' ' '`
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.
I am not a linux guru, but I believe you want to pipe your list of output files to xargs rm -rf
. I have used something like this in the past with good results. Test on a sample directory first!
EDIT - I might have misunderstood, based on the other answers that are appearing. If you can use wildcards, great. I assumed that your original list that you displayed was generated by a program to give you your "selection", so I thought piping to xargs
would be the way to go.
C99 has a boolean datatype, actually, but if you must use older versions, just define a type:
typedef enum {false=0, true=1} bool;
After converting your varchar2
date to a true date
datatype, then convert back to varchar2
with the desired mask:
to_char(to_date('01/02/2012','MM/DD/YYYY'),'WW')
If you want the week number in a number
datatype, you can wrap the statement in to_number()
:
to_number(to_char(to_date('01/02/2012','MM/DD/YYYY'),'WW'))
However, you have several week number options to consider:
WW Week of year (1-53) where week 1 starts on the first day of the year and continues to the seventh day of the year.
W Week of month (1-5) where week 1 starts on the first day of the month and ends on the seventh.
IW Week of year (1-52 or 1-53) based on the ISO standard.
if your setup
myApp
|
|__ public
| |
| |__ stylesheets
| | |
| | |__ style.css
| |
| |___ img
| |
| |__ logo.png
|
|__ app.js
then,
put in app.js
app.use('/static', express.static('public'));
and refer to your style.css: (in some .pug file):
link(rel='stylesheet', href='/static/stylesheets/style.css')
In addition to Benjamin's answer (which I've only skimmed), you need to make sure that your files are actually stored using the proper encoding (that would be UTF-8 for source code, JSPs etc., but note that Java Properties files must be encoded as ISO 8859-1 by definition).
The problem with this is that it's not possible to tell what encoding has been used to store a file. Your only option is to open the file using a specific encoding, and checking whether or not the content makes sense. You can also try to convert the file from the assumed encoding to the desired encoding using iconv - if that produces an error, your assumption was incorrect. So if you assume that hello.jsp is encoded as UTF-8, run "iconv -f UTF-16 -t UTF-8 hello.jsp" and check for errors.
If you should find out that your files are not properly encoded, you need to find out why. It's probably the editor or IDE you used to create the file. In case of Eclipse (and STS), make sure the Text File Encoding (Preferences / General / Workspace) is set to UTF-8 (it unfortunately defaults to your system's platform encoding).
What makes encoding problems so difficult to debug is that there's so many components involved (text editor, borwser, plus each and every software component in between, in some cases including a database), and each of them has the potential to introduce an error.
Not sure this is what you're looking for, but I had a bit different goal is to check if remote image exists and I will not have 403 error, so you could use something like below:
public static boolean linkExists(String URLName){
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
Look at my project CalcBinding, which provides to you writing complex expressions in Path property value, including static properties, source properties, Math and other. So, you can write this:
<TextBox Text="{c:Binding local:VersionManager.FilterString}"/>
Goodluck!
The difference between those will depend largely on what browser you are currently referring to. Each one implements these properties differently, or not at all. Quirksmode has great documentation regarding browser differences in regards to W3C standards like the DOM and JavaScript Events.
You could use flatMap. It can filter and map in one.
$scope.appIds = $scope.applicationsHere.flatMap(obj => obj.selected ? obj.id : [])
If you need an instance of HashMap, the best way is:
fileParameters = new HashMap<String,String>();
Since Map is an interface, you need to pick some class that instantiates it if you want to create an empty instance. HashMap seems as good as any other - so just use that.
Here's another approach.
git checkout {SOURCE_BRANCH} # switch to Source branch.
git checkout {COMMIT_HASH} # go back to the desired commit.
git checkout -b {temp_branch} # create a new temporary branch from {COMMIT_HASH} snapshot.
git checkout {TARGET_BRANCH} # switch to Target branch.
git merge {temp_branch} # merge code to your Target branch.
git branch -d {temp_branch} # delete the temp branch.
You should use setStroke
to set a stroke of the Graphics2D
object.
The example at http://www.java2s.com gives you some code examples.
The following code produces the image below:
import java.awt.*;
import java.awt.geom.Line2D;
import javax.swing.*;
public class FrameTest {
public static void main(String[] args) {
JFrame jf = new JFrame("Demo");
Container cp = jf.getContentPane();
cp.add(new JComponent() {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(10));
g2.draw(new Line2D.Float(30, 20, 80, 90));
}
});
jf.setSize(300, 200);
jf.setVisible(true);
}
}
(Note that the setStroke
method is not available in the Graphics
object. You have to cast it to a Graphics2D
object.)
This post has been rewritten as an article here.
For starters:
<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.
This would be the optimal solution:
<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
There is nothing like LINQ for Java.
...
Edit
Now with Java 8 we are introduced to the Stream API, this is a similar kind of thing when dealing with collections, but it is not quite the same as Linq.
If it is an ORM you are looking for, like Entity Framework, then you can try Hibernate
:-)
try this :
driver = webdriver.Chrome(ChromeDriverManager().install())
Chrome dev tools now allows you to save the console output to a file natively
Chrome Developer instructions here.
Remove the () from your expressions that are not working will get the desired results you need.
but.setAttribute("onclick",callJavascriptFunction);
but.onclick= callJavascriptFunction;
document.getElementById("but").onclick=callJavascriptFunction;
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
I had a similar problem recently, and here's what I did:
SELECT
columnname as 'Original_Value',
LEN(LTRIM(columnname)) as 'Orig_Val_Char_Count',
N'['+columnname+']' as 'UnicodeStr_Value',
LEN(N'['+columnname+']')-2 as 'True_Char_Count'
FROM mytable
The first two columns look at the original value and count the characters (minus leading/trailing spaces).
I needed to compare that with the true count of characters, which is why I used the second LEN function. It sets the column value to a string, forces that string to Unicode, and then counts the characters.
By using the brackets, you ensure that any leading or trailing spaces are also counted as characters; of course, you don't want to count the brackets themselves, so you subtract 2 at the end.
If key is present table.put(key, val)
will just overwrite the value else it'll create a new entry. Poof! and you are done. :)
you can get the value from a map by using key is table.get(key);
That's about it
Whether it's trivial or hard to crack, I'm not sure that it really makes much of a difference.
The likelihood of your app being cracked is far more proportional to its usefulness rather than the strength of the product key handling.
Personally, I think there are two classes of user. Those who pay. Those who don't. The ones that do will likely do so with even the most trivial protection. Those who don't will wait for a crack or look elsewhere. Either way, it won't get you any more money.
You did forget to include stdafx.h
in your source (as I cannot see it your code). If you didn't, then make sure #include "stdafx.h"
is the first line in your .cpp
file, otherwise you will see the same error even if you've included "stdafx.h"
in your source file (but not in the very beginning of the file).
public double RoundDown(double number, int decimalPlaces)
{
return Math.Floor(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);
}
You can use the shift keyword (operator?) to iterate through them. Example:
#!/bin/bash
function print()
{
while [ $# -gt 0 ]
do
echo $1;
shift 1;
done
}
print $*;
For me the error was quite simple based on what @alfred_m said..... tomcat had 2 jars conflicting having same set of Class names and configuration.
What happened was ..............I copied my existing project to make a new project out of the existing project. but without making required changes, I started working on other project. Henec 2 projects had same classes and configuration files, resulting into conflict.
Deleted the copied project and things started working!!!!
this will work for all sort of youtube url :
if url could be
youtube.com/?v=_RCIP6OrQrE
youtube.com/v/_RCIP6OrQrE
youtube.com/watch?v=_RCIP6OrQrE
youtube.com/watch?v=_RCIP6OrQrE&feature=whatever&this=that
Pattern p = Pattern.compile("http.*\\?v=([a-zA-Z0-9_\\-]+)(?:&.)*");
String url = "http://www.youtube.com/watch?v=_RCIP6OrQrE";
Matcher m = p.matcher(url.trim()); //trim to remove leading and trailing space if any
if (m.matches()) {
url = m.group(1);
}
System.out.println(url);
this will extract video id from your url
further reference
... and getting back to easy ... for simple scripts you can use:
import sys
needs = (3, 9) # or whatever
pvi = sys.version_info.major, sys.version_info.minor
later in your code
try:
assert pvi >= needs
except:
print("will fail!")
# etc.
I changed all space areas to  , just like that and it worked without problem.
val.replace(" ", " ");
I hope it helps someone.
There is another library called arrow
really great to make manipulation on python date.
import arrow
import datetime
a = arrow.get('24052010', 'DMYYYY').date()
print(isinstance(a, datetime.date)) # True
For doing "normal" hash table lookups on basically any kind of data - this one by Paul Hsieh is the best I've ever used.
http://www.azillionmonkeys.com/qed/hash.html
If you care about cryptographically secure or anything else more advanced, then YMMV. If you just want a kick ass general purpose hash function for a hash table lookup, then this is what you're looking for.
I tried flutter clean
and that didn't work for me. Then I went to wipe the emulator's data and voila, the cached issue was gone. If you have Android Studio you can launch the AVD Manager by following this Create and Manage virtual machine. Otherwise you can wipe the emulator's data using the emulator.exe command line that's included in the android SDK. Simply follow this instructions here Start the emulator from the command line.
You need to define a Theme for your AlertDialog and reference it in your Activity's theme. The attribute is alertDialogTheme
and not alertDialogStyle
. Like this:
<style name="Theme.YourTheme" parent="@android:style/Theme.Holo">
...
<item name="android:alertDialogTheme">@style/YourAlertDialogTheme</item>
</style>
<style name="YourAlertDialogTheme">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
<item name="android:windowMinWidthMajor">@android:dimen/dialog_min_width_major</item>
<item name="android:windowMinWidthMinor">@android:dimen/dialog_min_width_minor</item>
<item name="android:windowTitleStyle">...</item>
<item name="android:textAppearanceMedium">...</item>
<item name="android:borderlessButtonStyle">...</item>
<item name="android:buttonBarStyle">...</item>
</style>
You'll be able to change color and text appearance for the title, the message and you'll have some control on the background of each area. I wrote a blog post detailing the steps to style an AlertDialog.
First of all check latest Chrome version (This is your browser Chrome version) link
Download same version of Chrome Web Driver from this link
Do not download latest Chrome Web Driver if it does not match your Chrome Browser version.
Note: When I write this message, latest Chrome Browser version is 84 but latest Chrome Driver version is 85. I am using Chrome Driver version 84 so that Chrome Driver and Chrome Browser versions are the same.
Depends on what you mean by emptying. If you just want an empty string, you could do
buffer[0] = 0;
If you want to set every element to zero, do
memset(buffer, 0, 80);
You don't need a CTE for this
UPDATE PEDI_InvoiceDetail
SET
DocTotal = v.DocTotal
FROM
PEDI_InvoiceDetail
inner join
(
SELECT InvoiceNumber, SUM(Sale + VAT) AS DocTotal
FROM PEDI_InvoiceDetail
GROUP BY InvoiceNumber
) v
ON PEDI_InvoiceDetail.InvoiceNumber = v.InvoiceNumber
To build and install modern Git on CentOS 6:
yum install -y curl-devel expat-devel gettext-devel openssl-devel zlib-devel gcc perl-ExtUtils-MakeMaker
export GIT_VERSION=2.6.4
mkdir /root/git
cd /root/git
wget "https://www.kernel.org/pub/software/scm/git/git-${GIT_VERSION}.tar.gz"
tar xvzf "git-${GIT_VERSION}.tar.gz"
cd git-${GIT_VERSION}
make prefix=/usr/local all
make prefix=/usr/local install
yum remove -y git
git --version # should be GIT_VERSION
The problem appears to be that the global symbol clear
is already in use and your function doesn't succeed in overriding it. If you change that name to something else (I used blah
), it works just fine:
Live: Version using clear
which fails | Version using blah
which works
<html>
<head>
<title>lala</title>
</head>
<body>
<h1 onmouseover="go('The dog is in its shed')" onmouseout="blah()">lalala</h1>
<div id="goy"></div>
<script type="text/javascript">
function go(what) {
document.getElementById("goy").innerHTML = what;
}
function blah() {
document.getElementById("goy").innerHTML = "";
}
</script>
</body>
</html>
This is a great illustration of the fundamental principal: Avoid global variables wherever possible. The global namespace in browsers is incredibly crowded, and when conflicts occur, you get weird bugs like this.
A corollary to that is to not use old-style onxyz=...
attributes to hook up event handlers, because they require globals. Instead, at least use code to hook things up: Live Copy
<html>
<head>
<title>lala</title>
</head>
<body>
<h1 id="the-header">lalala</h1>
<div id="goy"></div>
<script type="text/javascript">
// Scoping function makes the declarations within
// it *not* globals
(function(){
var header = document.getElementById("the-header");
header.onmouseover = function() {
go('The dog is in its shed');
};
header.onmouseout = clear;
function go(what) {
document.getElementById("goy").innerHTML = what;
}
function clear() {
document.getElementById("goy").innerHTML = "";
}
})();
</script>
</body>
</html>
...and even better, use DOM2's addEventListener
(or attachEvent
on IE8 and earlier) so you can have multiple handlers for an event on an element.
Just 2 things I think make it ALWAYS preferable to use a # Temp Table rather then a CTE are:
You can not put a primary key on a CTE so the data being accessed by the CTE will have to traverse each one of the indexes in the CTE's tables rather then just accessing the PK or Index on the temp table.
Because you can not add constraints, indexes and primary keys to a CTE they are more prone to bugs creeping in and bad data.
-onedaywhen yesterday
Here is an example where #table constraints can prevent bad data which is not the case in CTE's
DECLARE @BadData TABLE (
ThisID int
, ThatID int );
INSERT INTO @BadData
( ThisID
, ThatID
)
VALUES
( 1, 1 ),
( 1, 2 ),
( 2, 2 ),
( 1, 1 );
IF OBJECT_ID('tempdb..#This') IS NOT NULL
DROP TABLE #This;
CREATE TABLE #This (
ThisID int NOT NULL
, ThatID int NOT NULL
UNIQUE(ThisID, ThatID) );
INSERT INTO #This
SELECT * FROM @BadData;
WITH This_CTE
AS (SELECT *
FROM @BadData)
SELECT *
FROM This_CTE;
EDIT:
So which am I supposed to use? The proper 4 letter extension suggested by the creator, or the 3 letter extension found in the wild west of the internet?
This question could be:
A request for advice; or
A natural expression of that particular emotion which is experienced, while one is observing that some official recommendation is being disregarded—prominently, or even predominantly.
People differ in their predilection for following:
Official advice; or
The preponderance of practice.
Of course, I am unlikely to influence you, regarding which of these two paths you prefer to take!
In what follows (and, in the spirit of science), I merely make an hypothesis, about what (merely as a matter of fact) led the majority of people to use the 3-letter extension. And, I focus on efficient causes.
By this, I do not intend moral exhortation. As you may recall, the fact that something is, does not imply that it should be.
Whatever your personal inclination, be it to follow one path or the other, I do not object.
(End of edit.)
The suggestion, that this preference (in real life usage) was caused by a 8.3 character DOS-ish limitation, IMO is a red herring (erroneous and misleading).
As of August, 2016, the Google search counts for YML and YAML were approximately 6,000,000 and 4,100,000 (to two digits of precision). Furthermore, the "YAML" count was unfairly high because it included mention of the language by name, beyond its use as an extension.
As of July, 2018, the Google's search counts for YML and YAML were approximately 8,100,000 and 4,100,000 (again, to two digits of precision). So, in the last two years, YML has essentially doubled in popularity, but YAML has stayed the same.
Another cultural measure is websites which attempt to explain file extensions. For example, on the FilExt website (as of July, 2018), the page for YAML results in: "Ooops! The FILEXT.com database does not have any information on file extension .YAML."
Whereas, it has an entry for YML, which gives: "YAML...uses a text file and organizes it into a format which is Human-readable. 'database.yml' is a typical example when YAML is used by Ruby on Rails to connect to a database."
As of November, 2014, Wikipedia's article on extension YML still stated that ".yml" is "the file extension for the YAML file format" (emphasis added). Its YAML article lists both extensions, without expressing a preference.
The extension ".yml" is sufficiently clear, is more brief (thus easier to type and recognize), and is much more common.
Of course, both of these extensions could be viewed as abbreviations of a long, possible extension, ".yamlaintmarkuplanguage". But programmers (and users) don't want to type all of that!
Instead, we programmers (and users) want to type as little as possible, and still yet be unambiguous and clear. And we want to see what kind of file it is, as quickly as possible, without reading a longer word. Typing just how many characters accomplishes both of these goals? Isn't the answer three (3)? In other words, YML?
Wikipedia's Category:Filename_extensions page lists entries for .a, .o and .Z. Somehow, it missed .c and .h (used by the C language). These example single-letter extensions help us to see that extensions should be as long as necessary, but no longer (to half-quote Albert Einstein).
Instead, notice that, in general, few extensions start with "Y". Commonly, on the other hand, the letter X is used for a great variety of meanings including "cross," "extensible," "extreme," "variable," etc. (e.g. in XML). So starting with "Y" already conveys much information (in terms of information theory), whereas starting with "X" does not.
Linguistically speaking, therefore, the acronym "XML" has (in a way) only two informative letters ("M" and "L"). "YML", instead, has three informative letters ("M", "L" and "Y"). Indeed, the existing set of acronyms beginning with Y seems extremely small. By implication, this is why a four letter YAML file extension feels greatly overspecified.
Perhaps this is why we see in practice that the "linguistic" pressure (in natural use) to lengthen the abbreviation in question to four (4) characters is weak, and the "linguistic" pressure to shorten this abbreviation to three (3) characters is strong.
Purely as a result, probably, of these factors (and not as an official endorsement), I would note that the YAML.org website's latest news item (from November, 2011) is all about a project written in JavaScript, JS-YAML, which, itself, internally prefers to use the extension ".yml".
The above-mentioned factors may have been the main ones; nevertheless, all the factors (known or unknown) have resulted in the abbreviated, three (3) character extension becoming the one in predominant use for YAML—despite the inventors' preference.
".YML" seems to be the de facto standard. Yet the same inventors were perceptive and correct, about the world's need for a human-readable data language. And we should thank them for providing it.
We can't because it's expected/required by our customers.
Try to add auth method explicitly as below, because sometimes it is required:
session.setConfig("PreferredAuthentications", "password");
If you use a pem file to authenticate u can use the following command (which will exclude files with something extension):
rsync -Lavz -e "ssh -i <full-path-to-pem> -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" --exclude "*.something" --progress <path inside local host> <user>@<host>:<path inside remote host>
The -L means follow links (copy files not links). Use full path to your pem file and not relative.
Using sshfs is not recommended since it works slowly. Also, the combination of find and scp that was presented above is also a bad idea since it will open a ssh session per file which is too expensive.
Proper HTML way: just surround your button with anchor element and add attribute target="_blank". It is as simple as that:
<a ng-href="{{yourDynamicURL}}" target="_blank">
<h1>Open me in new Tab</h1>
</a>
where you can set in the controller:
$scope.yourDynamicURL = 'https://stackoverflow.com';
There are a lot of things to consider when validating a phone number if you really think about it. (especially international) so using a package is better than the accepted answer by far, and if you want something simple like a regex I would suggest using something better than what @SlateEntropy suggested. (something like A comprehensive regex for phone number validation)
Works with single ax or with matrix of ax (subplots)
from matplotlib import pyplot as plt
import numpy as np
def show_values_on_bars(axs):
def _show_on_single_plot(ax):
for p in ax.patches:
_x = p.get_x() + p.get_width() / 2
_y = p.get_y() + p.get_height()
value = '{:.2f}'.format(p.get_height())
ax.text(_x, _y, value, ha="center")
if isinstance(axs, np.ndarray):
for idx, ax in np.ndenumerate(axs):
_show_on_single_plot(ax)
else:
_show_on_single_plot(axs)
fig, ax = plt.subplots(1, 2)
show_values_on_bars(ax)
Try > workdirectory/filename.txt
This would:
You can consider it equivalent to:
rm -f workdirectory/filename.txt; touch workdirectory/filename.txt
I found a function that can plot the confusion matrix which generated from sklearn
.
import numpy as np
def plot_confusion_matrix(cm,
target_names,
title='Confusion matrix',
cmap=None,
normalize=True):
"""
given a sklearn confusion matrix (cm), make a nice plot
Arguments
---------
cm: confusion matrix from sklearn.metrics.confusion_matrix
target_names: given classification classes such as [0, 1, 2]
the class names, for example: ['high', 'medium', 'low']
title: the text to display at the top of the matrix
cmap: the gradient of the values displayed from matplotlib.pyplot.cm
see http://matplotlib.org/examples/color/colormaps_reference.html
plt.get_cmap('jet') or plt.cm.Blues
normalize: If False, plot the raw numbers
If True, plot the proportions
Usage
-----
plot_confusion_matrix(cm = cm, # confusion matrix created by
# sklearn.metrics.confusion_matrix
normalize = True, # show proportions
target_names = y_labels_vals, # list of names of the classes
title = best_estimator_name) # title of graph
Citiation
---------
http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html
"""
import matplotlib.pyplot as plt
import numpy as np
import itertools
accuracy = np.trace(cm) / np.sum(cm).astype('float')
misclass = 1 - accuracy
if cmap is None:
cmap = plt.get_cmap('Blues')
plt.figure(figsize=(8, 6))
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
if target_names is not None:
tick_marks = np.arange(len(target_names))
plt.xticks(tick_marks, target_names, rotation=45)
plt.yticks(tick_marks, target_names)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
thresh = cm.max() / 1.5 if normalize else cm.max() / 2
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
if normalize:
plt.text(j, i, "{:0.4f}".format(cm[i, j]),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
else:
plt.text(j, i, "{:,}".format(cm[i, j]),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass))
plt.show()
If you are trying to run the macro from your personal workbook it might not work as opening an Excel file with a VBScript doesnt automatically open your PERSONAL.XLSB. you will need to do something like this:
Dim oFSO
Dim oShell, oExcel, oFile, oSheet
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oShell = CreateObject("WScript.Shell")
Set oExcel = CreateObject("Excel.Application")
Set wb2 = oExcel.Workbooks.Open("C:\..\PERSONAL.XLSB") 'Specify foldername here
oExcel.DisplayAlerts = False
For Each oFile In oFSO.GetFolder("C:\Location\").Files
If LCase(oFSO.GetExtensionName(oFile)) = "xlsx" Then
With oExcel.Workbooks.Open(oFile, 0, True, , , , True, , , , False, , False)
oExcel.Run wb2.Name & "!modForm"
For Each oSheet In .Worksheets
oSheet.SaveAs "C:\test\" & oFile.Name & "." & oSheet.Name & ".txt", 6
Next
.Close False, , False
End With
End If
Next
oExcel.Quit
oShell.Popup "Conversion complete", 10
So at the beginning of the loop it is opening personals.xlsb and running the macro from there for all the other workbooks. Just thought I should post in here just in case someone runs across this like I did but cant figure out why the macro is still not running.
When you do a cmp a,b
, the flags are set as if you had calculated a - b
.
Then the jmp
-type instructions check those flags to see if the jump should be made.
In other words, the first block of code you have (with my comments added):
cmp al,dl ; set flags based on the comparison
jg label1 ; then jump based on the flags
would jump to label1
if and only if al
was greater than dl
.
You're probably better off thinking of it as al > dl
but the two choices you have there are mathematically equivalent:
al > dl
al - dl > dl - dl (subtract dl from both sides)
al - dl > 0 (cancel the terms on the right hand side)
You need to be careful when using jg
inasmuch as it assumes your values were signed. So, if you compare the bytes 101 (101 in two's complement) with 200 (-56 in two's complement), the former will actually be greater. If that's not what was desired, you should use the equivalent unsigned comparison.
See here for more detail on jump selection, reproduced below for completeness. First the ones where signed-ness is not appropriate:
+--------+------------------------------+-------------+--------------------+
|Instr | Description | signed-ness | Flags |
+--------+------------------------------+-------------+--------------------+
| JO | Jump if overflow | | OF = 1 |
+--------+------------------------------+-------------+--------------------+
| JNO | Jump if not overflow | | OF = 0 |
+--------+------------------------------+-------------+--------------------+
| JS | Jump if sign | | SF = 1 |
+--------+------------------------------+-------------+--------------------+
| JNS | Jump if not sign | | SF = 0 |
+--------+------------------------------+-------------+--------------------+
| JE/ | Jump if equal | | ZF = 1 |
| JZ | Jump if zero | | |
+--------+------------------------------+-------------+--------------------+
| JNE/ | Jump if not equal | | ZF = 0 |
| JNZ | Jump if not zero | | |
+--------+------------------------------+-------------+--------------------+
| JP/ | Jump if parity | | PF = 1 |
| JPE | Jump if parity even | | |
+--------+------------------------------+-------------+--------------------+
| JNP/ | Jump if no parity | | PF = 0 |
| JPO | Jump if parity odd | | |
+--------+------------------------------+-------------+--------------------+
| JCXZ/ | Jump if CX is zero | | CX = 0 |
| JECXZ | Jump if ECX is zero | | ECX = 0 |
+--------+------------------------------+-------------+--------------------+
Then the unsigned ones:
+--------+------------------------------+-------------+--------------------+
|Instr | Description | signed-ness | Flags |
+--------+------------------------------+-------------+--------------------+
| JB/ | Jump if below | unsigned | CF = 1 |
| JNAE/ | Jump if not above or equal | | |
| JC | Jump if carry | | |
+--------+------------------------------+-------------+--------------------+
| JNB/ | Jump if not below | unsigned | CF = 0 |
| JAE/ | Jump if above or equal | | |
| JNC | Jump if not carry | | |
+--------+------------------------------+-------------+--------------------+
| JBE/ | Jump if below or equal | unsigned | CF = 1 or ZF = 1 |
| JNA | Jump if not above | | |
+--------+------------------------------+-------------+--------------------+
| JA/ | Jump if above | unsigned | CF = 0 and ZF = 0 |
| JNBE | Jump if not below or equal | | |
+--------+------------------------------+-------------+--------------------+
And, finally, the signed ones:
+--------+------------------------------+-------------+--------------------+
|Instr | Description | signed-ness | Flags |
+--------+------------------------------+-------------+--------------------+
| JL/ | Jump if less | signed | SF <> OF |
| JNGE | Jump if not greater or equal | | |
+--------+------------------------------+-------------+--------------------+
| JGE/ | Jump if greater or equal | signed | SF = OF |
| JNL | Jump if not less | | |
+--------+------------------------------+-------------+--------------------+
| JLE/ | Jump if less or equal | signed | ZF = 1 or SF <> OF |
| JNG | Jump if not greater | | |
+--------+------------------------------+-------------+--------------------+
| JG/ | Jump if greater | signed | ZF = 0 and SF = OF |
| JNLE | Jump if not less or equal | | |
+--------+------------------------------+-------------+--------------------+
It is best to use character set utf8mb4
with the collation utf8mb4_unicode_ci
.
The character set, utf8
, only supports a small amount of UTF-8 code points, about 6% of possible characters. utf8
only supports the Basic Multilingual Plane (BMP). There 16 other planes. Each plane contains 65,536 characters. utf8mb4
supports all 17 planes.
MySQL will truncate 4 byte UTF-8 characters resulting in corrupted data.
The utf8mb4
character set was introduced in MySQL 5.5.3 on 2010-03-24.
Some of the required changes to use the new character set are not trivial:
ROW_FORMAT=DYNAMIC
NOTE: Switching to Barracuda
from Antelope
, may require restarting the MySQL service more than once. innodb_file_format_max
does not change until after the MySQL service has been restarted to: innodb_file_format = barracuda
.
MySQL uses the old Antelope
InnoDB file format. Barracuda
supports dynamic row formats, which you will need if you do not want to hit the SQL errors for creating indexes and keys after you switch to the charset: utf8mb4
The following scenario has been tested on MySQL 5.6.17: By default, MySQL is configured like this:
SHOW VARIABLES;
innodb_large_prefix = OFF
innodb_file_format = Antelope
Stop your MySQL service and add the options to your existing my.cnf:
[client]
default-character-set= utf8mb4
[mysqld]
explicit_defaults_for_timestamp = true
innodb_large_prefix = true
innodb_file_format = barracuda
innodb_file_format_max = barracuda
innodb_file_per_table = true
# Character collation
character_set_server=utf8mb4
collation_server=utf8mb4_unicode_ci
Example SQL CREATE statement:
CREATE TABLE Contacts (
id INT AUTO_INCREMENT NOT NULL,
ownerId INT DEFAULT NULL,
created timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
modified timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
contact VARCHAR(640) NOT NULL,
prefix VARCHAR(128) NOT NULL,
first VARCHAR(128) NOT NULL,
middle VARCHAR(128) NOT NULL,
last VARCHAR(128) NOT NULL,
suffix VARCHAR(128) NOT NULL,
notes MEDIUMTEXT NOT NULL,
INDEX IDX_CA367725E05EFD25 (ownerId),
INDEX created (created),
INDEX modified_idx (modified),
INDEX contact_idx (contact),
PRIMARY KEY(id)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB ROW_FORMAT=DYNAMIC;
INDEX contact_idx (contact)
if ROW_FORMAT=DYNAMIC
is removed from the CREATE statement.NOTE: Changing the index to limit to the first 128 characters on contact
eliminates the requirement for using Barracuda with ROW_FORMAT=DYNAMIC
INDEX contact_idx (contact(128)),
Also note: when it says the size of the field is VARCHAR(128)
, that is not 128 bytes. You can use have 128, 4 byte characters or 128, 1 byte characters.
This INSERT
statement should contain the 4 byte 'poo' character in the 2 row:
INSERT INTO `Contacts` (`id`, `ownerId`, `created`, `modified`, `contact`, `prefix`, `first`, `middle`, `last`, `suffix`, `notes`) VALUES
(1, NULL, '0000-00-00 00:00:00', '2014-08-25 03:00:36', '1234567890', '12345678901234567890', '1234567890123456789012345678901234567890', '1234567890123456789012345678901234567890', '12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678', '', ''),
(2, NULL, '0000-00-00 00:00:00', '2014-08-25 03:05:57', 'poo', '12345678901234567890', '', '', '', '', ''),
(3, NULL, '0000-00-00 00:00:00', '2014-08-25 03:05:57', 'poo', '12345678901234567890', '', '', '123', '', '');
You can see the amount of space used by the last
column:
mysql> SELECT BIT_LENGTH(`last`), CHAR_LENGTH(`last`) FROM `Contacts`;
+--------------------+---------------------+
| BIT_LENGTH(`last`) | CHAR_LENGTH(`last`) |
+--------------------+---------------------+
| 1024 | 128 | -- All characters are ASCII
| 4096 | 128 | -- All characters are 4 bytes
| 4024 | 128 | -- 3 characters are ASCII, 125 are 4 bytes
+--------------------+---------------------+
In your database adapter, you may want to set the charset and collation for your connection:
SET NAMES 'utf8mb4' COLLATE 'utf8mb4_unicode_ci'
In PHP, this would be set for: \PDO::MYSQL_ATTR_INIT_COMMAND
References:
Perhaps the whole column full of random numbers is not the best way to do it, but it seems like probably the most practical as @mariusnn mentioned.
On that note, this stomped me for a while with Office 2010, and while generally answers like the one in lifehacker work,I just wanted to share an extra step required for the numbers to be unique:
=rand()
in the first cell of the new column - this will generate a random number between 0 and 1Fill the column with that formula. The easiest way to do this may be to:
Now you should have a column of identical numbers, even though they are all generated randomly.
The trick here is to recalculate them! Go to the Formulas tab and then click on Calculate Now (or press F9).
Now all the numbers in the column will be actually generated randomly.
Go to the Home tab and click on Sort & Filter. Choose whichever order you want (Smallest to Largest or Largest to Smallest) - whichever one will give you a random order with respect to the original order. Then click OK when the Sort Warning prompts you to Expand the selection.
Your list should be randomized now! You can get rid of the column of random numbers if you want.
I used JSONObject as shown below in Servlet.
JSONObject jsonReturn = new JSONObject();
NhAdminTree = AdminTasks.GetNeighborhoodTreeForNhAdministrator( connection, bwcon, userName);
map = new HashMap<String, String>();
map.put("Status", "Success");
map.put("FailureReason", "None");
map.put("DataElements", "2");
jsonReturn = new JSONObject();
jsonReturn.accumulate("Header", map);
List<String> list = new ArrayList<String>();
list.add(NhAdminTree);
list.add(userName);
jsonReturn.accumulate("Elements", list);
The Servlet returns this JSON object as shown below:
response.setContentType("application/json");
response.getWriter().write(jsonReturn.toString());
This Servlet is called from Browser using AngularJs as below
$scope.GetNeighborhoodTreeUsingPost = function(){
alert("Clicked GetNeighborhoodTreeUsingPost : " + $scope.userName );
$http({
method: 'POST',
url : 'http://localhost:8080/EPortal/xlEPortalService',
headers: {
'Content-Type': 'application/json'
},
data : {
'action': 64,
'userName' : $scope.userName
}
}).success(function(data, status, headers, config){
alert("DATA.header.status : " + data.Header.Status);
alert("DATA.header.FailureReason : " + data.Header.FailureReason);
alert("DATA.header.DataElements : " + data.Header.DataElements);
alert("DATA.elements : " + data.Elements);
}).error(function(data, status, headers, config) {
alert(data + " : " + status + " : " + headers + " : " + config);
});
};
This code worked and it is showing correct data in alert dialog box:
Data.header.status : Success
Data.header.FailureReason : None
Data.header.DetailElements : 2
Data.Elements : Coma seperated string values i.e. NhAdminTree, userName
I really recommend using the String.StartsWith method over the Regex.IsMatch if you only plan to check the beginning of a string.
In your case you should use regular expressions only if you plan implementing more complex string comparison in the future.
Assuming t1 is the folder with files in it, and t2 is the empty directory. What you want is something like this:
sudo cp -R t1/* t2/
Bear in mind, for the first example, t1 and t2 have to be the full paths, or relative paths (based on where you are). If you want, you can navigate to the empty folder (t2) and do this:
sudo cp -R t1/* ./
Or you can navigate to the folder with files (t1) and do this:
sudo cp -R ./* t2/
Note: The * sign (or wildcard) stands for all files and folders. The -R flag means recursively (everything inside everything).
There're several open-source libraries which allow console table formatting, ranging from simple (like the code samples in the answers here) to more advanced.
Judging by NuGet stats, the most popular library for formatting tables is ConsoleTable. Tables are constructed like this (from the readme file):
var table = new ConsoleTable("one", "two", "three");
table.AddRow(1, 2, 3)
.AddRow("this line should be longer", "yes it is", "oh");
Tables can be formatted using one of the predefined styles. It'll look like this:
--------------------------------------------------
| one | two | three |
--------------------------------------------------
| 1 | 2 | 3 |
--------------------------------------------------
| this line should be longer | yes it is | oh |
--------------------------------------------------
This library expects single-line cells with no formatting.
There're a couple of libraries based on ConsoleTable with slightly extended feature sets, like more line styles.
If you need more complex formatting, you can use CsConsoleFormat.† Here's a table generated from a process list (from a sample project):
new Grid { Stroke = StrokeHeader, StrokeColor = DarkGray }
.AddColumns(
new Column { Width = GridLength.Auto },
new Column { Width = GridLength.Auto, MaxWidth = 20 },
new Column { Width = GridLength.Star(1) },
new Column { Width = GridLength.Auto }
)
.AddChildren(
new Cell { Stroke = StrokeHeader, Color = White }
.AddChildren("Id"),
new Cell { Stroke = StrokeHeader, Color = White }
.AddChildren("Name"),
new Cell { Stroke = StrokeHeader, Color = White }
.AddChildren("Main Window Title"),
new Cell { Stroke = StrokeHeader, Color = White }
.AddChildren("Private Memory"),
processes.Select(process => new[] {
new Cell { Stroke = StrokeRight }
.AddChildren(process.Id),
new Cell { Stroke = StrokeRight, Color = Yellow, TextWrap = TextWrapping.NoWrap }
.AddChildren(process.ProcessName),
new Cell { Stroke = StrokeRight, Color = White, TextWrap = TextWrapping.NoWrap }
.AddChildren(process.MainWindowTitle),
new Cell { Stroke = LineThickness.None, Align = HorizontalAlignment.Right }
.AddChildren(process.PrivateMemorySize64.ToString("n0")),
})
)
The end result will look like this:
It supports any kind of table lines (several included and customizable), multi-line cells with word wrap, colors, columns growing based on content or percentage, text alignment etc.
† CsConsoleFormat was developed by me.
You can deploy an images folder as a separate webapp and define the location of that folder to be anywhere in the file system.
Create a Context element in an XML file in the directory $CATALINA_HOME/conf/[enginename]/[hostname]/
where enginename might be 'Catalina' and hostname might be 'localhost'.
Name the file based on the path URL you want the images to be viewed from, so if your webapp has path 'blog', you might name the XML file blog#images.xml
and so that your images would be visible at example.com/blog/images/
The content of the XML file should be <Context docBase="/filesystem/path/to/images"/>
Be careful not to undeploy this webapp, as that could delete all your images!
You have to trigger the change event of the input element because ng-model listens to input events and the scope will be updated. However, the regular jQuery trigger didn't work for me. But here is what works like a charm
$("#myInput")[0].dispatchEvent(new Event("input", { bubbles: true })); //Works
Following didn't work
$("#myInput").trigger("change"); // Did't work for me
You can read more about creating and dispatching synthetic events.
Mac version. From terminal run:
open /Applications/Google\ Chrome.app/ --args --allow-file-access-from-files
We use these settings:
etc/my.cnf
innodb_buffer_pool_size = 384M
key_buffer = 256M
query_cache_size = 1M
query_cache_limit = 128M
thread_cache_size = 8
max_connections = 400
innodb_lock_wait_timeout = 100
for a server with the following specifications:
Dell Server
CPU cores: Two
Processor(s): 1x Dual Xeon
Clock Speed: >= 2.33GHz
RAM: 2 GBytes
Disks: 1×250 GB SATA
You can break up long lines with the caret ^
as long as you remember that the caret and the newline following it are completely removed. So, if there should be a space where you're breaking the line, include a space. (More on that below.)
Example:
copy file1.txt file2.txt
would be written as:
copy file1.txt^
file2.txt
All the docker:
start | restart | stop | rm --force | kill
commands
may not work if the container is stuck. You can always restart the docker daemon. However, if you have other containers running, that may not be the option. What you can do is:
ps aux | grep <<container id>> | awk '{print $1 $2}'
The output contains:
<<user>><<process id>>
Then kill the process associated with the container like so:
sudo kill -9 <<process id from above command>>
That will kill the container and you can start a new container with the right image.
Because of the condition in while
, the loop might never break:
while (entry != null) {
// If entry never becomes null here, loop will never break.
}
Instead of the null
check there, you can try this:
ZipEntry entry = null;
while ((entry = zip.getNextEntry()) != null) {
// Rest of your code
}
This unfortunately breaks other things. Here is the fix I found on another site that seemed to work for me:
I'd say leave the X-UA-Compatible
as "IE=8"
and add the following code to the bottom of your master page:
<script language="javascript">
/* IE11 Fix for SP2010 */
if (typeof(UserAgentInfo) != 'undefined' && !window.addEventListener)
{
UserAgentInfo.strBrowser=1;
}
</script>
This fixes a bug in core.js
which incorrectly calculates that sets UserAgentInfo.strBrowse=3
for IE11 and thus supporting addEventListener
. I'm not entirely sure on the details other than that but the combination of keeping IE=8 and using this script is working for me. Fingers crossed until I find the next IE11/SharePoint "bug"!
The function which you are specifying as initSelection
is called with the initial value
as argument. So if value
is empty, the function is not called.
When you specifiy value='[{"id":"IN","name":"India"}]'
instead of data-initvalue
the function gets called and the selection can get initialized.
The Html.TextboxFor
always creates a textbox (<input type="text" ...
).
While the EditorFor looks at the type and meta information, and can render another control or a template you supply.
For example for DateTime properties you can create a template that uses the jQuery DatePicker.
It is general syntax
driver.find_element_by_id('Locator value').clear();
driver.find_element_by_name('Locator value').clear();
Use setCustomValidity
:
document.addEventListener("DOMContentLoaded", function() {
var elements = document.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("This field cannot be left blank");
}
};
elements[i].oninput = function(e) {
e.target.setCustomValidity("");
};
}
})
I changed to vanilla JavaScript from Mootools as suggested by @itpastorn in the comments, but you should be able to work out the Mootools equivalent if necessary.
I've updated the code here as setCustomValidity
works slightly differently to what I understood when I originally answered. If setCustomValidity
is set to anything other than the empty string it will cause the field to be considered invalid; therefore you must clear it before testing validity, you can't just set it and forget.
As pointed out in @thomasvdb's comment below, you need to clear the custom validity in some event outside of invalid
otherwise there may be an extra pass through the oninvalid
handler to clear it.
Assuming you're on at least 3.2, there's a built in for this:
int.from_bytes( bytes, byteorder, *, signed=False )
...
The argument bytes must either be a bytes-like object or an iterable producing bytes.
The byteorder argument determines the byte order used to represent the integer. If byteorder is "big", the most significant byte is at the beginning of the byte array. If byteorder is "little", the most significant byte is at the end of the byte array. To request the native byte order of the host system, use sys.byteorder as the byte order value.
The signed argument indicates whether two’s complement is used to represent the integer.
## Examples:
int.from_bytes(b'\x00\x01', "big") # 1
int.from_bytes(b'\x00\x01', "little") # 256
int.from_bytes(b'\x00\x10', byteorder='little') # 4096
int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) #-1024
You can query Active directory via JNDI and run LDAP operations
http://docs.oracle.com/javase/tutorial/jndi/ldap/authentication.html
http://docs.oracle.com/javase/tutorial/jndi/ldap/operations.html
http://mhimu.wordpress.com/2009/03/18/active-directory-authentication-using-javajndi/
function isDecimal(n){
if(n == "")
return false;
var strCheck = "0123456789";
var i;
for(i in n){
if(strCheck.indexOf(n[i]) == -1)
return false;
}
return true;
}
I think best way is check if request is of type "OPTIONS" return 200 from middle ware. It worked for me.
express.use('*',(req,res,next) =>{
if (req.method == "OPTIONS") {
res.status(200);
res.send();
}else{
next();
}
});
If we use runnable method SwingUtilities.invokeLater() while using Document listener application is getting stuck sometimes and taking time to update the result(As per my experiment). Instead of that we can also use KeyReleased event for text field change listener as mentioned here.
usernameTextField.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
JTextField textField = (JTextField) e.getSource();
String text = textField.getText();
textField.setText(text.toUpperCase());
}
});
The semantics of Having
To better understand having, you need to see it from a theoretical point of view.
A group by is a query that takes a table and summarizes it into another table. You summarize the original table by grouping the original table into subsets (based upon the attributes that you specify in the group by). Each of these groups will yield one tuple.
The Having is simply equivalent to a WHERE clause after the group by has executed and before the select part of the query is computed.
Lets say your query is:
select a, b, count(*)
from Table
where c > 100
group by a, b
having count(*) > 10;
The evaluation of this query can be seen as the following steps:
You can extend this to any complex query there Table can be any complex query that return a table (a cross product, a join, a UNION, etc).
In fact, having is syntactic sugar and does not extend the power of SQL. Any given query:
SELECT list
FROM table
GROUP BY attrList
HAVING condition;
can be rewritten as:
SELECT list from (
SELECT listatt
FROM table
GROUP BY attrList) as Name
WHERE condition;
The listatt is a list that includes the GROUP BY attributes and the expressions used in list and condition. It might be necessary to name some expressions in this list (with AS). For instance, the example query above can be rewritten as:
select a, b, count
from (select a, b, count(*) as count
from Table
where c > 100
group by a, b) as someName
where count > 10;
The solution you need
Your solution seems to be correct:
SELECT s.sid, s.name
FROM Supplier s, Supplies su, Project pr
WHERE s.sid = su.sid AND su.jid = pr.jid
GROUP BY s.sid, s.name
HAVING COUNT (DISTINCT pr.jid) >= 2
You join the three tables, then using sid as a grouping attribute (sname is functionally dependent on it, so it does not have an impact on the number of groups, but you must include it, otherwise it cannot be part of the select part of the statement). Then you are removing those that do not satisfy your condition: the satisfy pr.jid is >= 2
, which is that you wanted originally.
Best solution to your problem
I personally prefer a simpler cleaner solution:
SELECT sid, sname from
(SELECT sid from supplies
GROUP BY sid, pid
HAVING count(DISTINCT jid) >= 2
) AS T1
NATURAL JOIN
Supliers;
It will also be faster to execute, because the join is only done when needed, not all the times.
--dmg
For me, if I want to interact with the hidden div without seeing it disappear each time I leave the triggering element (a in that case) I must add:
div:hover {
display: block;
}
Use http://www.proxomitron.info and set up the header you want, etc.
Show create table in classic asp (handles constraints, primary keys, copying the table structure and/or data ...)
Sql server Show create table Mysql-style "Show create table" and "show create database" commands from Microsoft sql server. The script is written is Microsoft asp-language and is quite easy to port to another language.*
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss a");
use hh
in place of HH
In my case, my server was configured to work only in https mode, and error occured when I try to access http mode. So changing http://my-service
to https://my-service
helped.
This was the only thing that worked for me on Armbian:
dmesg | grep -oE 'mac=.*\w+' | cut -b '5-'
You can also look at the SampleSyncAdapter sample from the SDK. It may help you.
1) Create a handler in the fragment that you want to update.
public static Handler sUpdateHandler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
sUpdateHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// call you update method here.
}
};
}
2) In the Activity/Fragment/Dialog, wherever you want the update call to be fired, get the reference to that handler and send a message (telling your fragment to update)
// Check if the fragment is visible by checking if the handler is null or not.
Handler handler = TaskTabCompletedFragment.sUpdateHandler;
if (handler != null) {
handler.obtainMessage().sendToTarget();
}
In addition, if you wish to parse your object in case of http error (400-5** codes), You can use the following code: (just replace 'getInputStream' with 'getErrorStream':
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getErrorStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
return sb.toString();
I went for a simpler approach:
HTML
<div class="box">
<h1 class="text">OK THEN LETS GO</h1>
<hr class="line" />
</div>
CSS
.box {
align-items: center;
background: #ff7777;
display: flex;
height: 100vh;
justify-content: center;
}
.line {
border: 5px solid white;
display: block;
width: 100vw;
}
.text {
background: #ff7777;
color: white;
font-family: sans-serif;
font-size: 2.5rem;
padding: 25px 50px;
position: absolute;
}
Result
I ran into problems with just an FittedBox
so I wrapped my Image in an LayoutBuilder
:
LayoutBuilder(
builder: (_, constraints) => Image(
fit: BoxFit.fill,
width: constraints.maxWidth,
image: AssetImage(assets.example),
),
)
This worked like a charm and I suggest you give it a try.
Of course you can use height instead of width, this is just what I used.
@watson
On windows forms it is available, at the top of the class put
static void Main(string[] args)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
//other stuff here
}
since windows is single threaded, its all you need, in the event its a service you need to put it right above the call to the service (since there is no telling what thread you'll be on).
using System.Security.Principal
is also needed.
I think what are important in cryptography are not primes itself, but it is the difficulty of prime factorization problem
Suppose you have very very large integer which is known to be product of two primes m and n, it is not easy to find what are m and n. Algorithm such as RSA depends on this fact.
By the way, there is a published paper on algorithm which can "solve" this prime factorization problem in acceptable time using quantum computer. So newer algorithms in cryptography may not rely on this "difficulty" of prime factorization anymore when quantum computer comes to town :)
There is no direct method to draw a triangle.
You can use drawPolygon() method for this.
It takes three parameters in the following form:
drawPolygon(int x[],int y[], int number_of_points);
To draw a triangle:
(Specify the x coordinates in array x and y coordinates in array y and number of points which will be equal to the elements of both the arrays.Like in triangle you will have 3 x coordinates and 3 y coordinates which means you have 3 points in total.)
Suppose you want to draw the triangle using the following points:(100,50),(70,100),(130,100)
Do the following inside public void paint(Graphics g)
:
int x[]={100,70,130};
int y[]={50,100,100};
g.drawPolygon(x,y,3);
Similarly you can draw any shape using as many points as you want.