I'm not sure it's a standard construct, but I think you should have a look on "negative lookahead" (which writes : "?!", without the quotes). It's far easier than all answers in this thread, including the accepted one.
Example : Regex : "^(?!123)[0-9]*\w" Captures any string beginning by digits followed by letters, UNLESS if "these digits" are 123.
http://msdn.microsoft.com/en-us/library/az24scfc%28v=vs.110%29.aspx#grouping_constructs (microsoft page, but quite comprehensive) for lookahead / lookbehind
PS : it works well for me (.Net). But if I'm wrong on something, please let us know. I find this construct very simple and effective, so I'm surprised of the accepted answer.
The C compiler can glue adjacent string literals into one, like
printf("foo: %s "
"bar: %d", foo, bar);
The preprocessor can use a backslash as a last character of the line, not counting CR (or CR/LF, if you are from Windowsland):
printf("foo %s \
bar: %d", foo, bar);
save() method can be used to insert new record and update existing record and generally used for saving instance of single record(row in mysql) in database.
update() is not used to insert records and can be used to update multiple records(rows in mysql) in database.
You can also consider to reverse your array and take the first element. That way you don't have to know about the length, but it brings no real benefits and the disadvantage that the reverse operation might take longer with big arrays:
array1.split(",").reverse()[0]
It's easy though, but also modifies the original array in question. That might or might not be a problem.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse
Probably you might want to use this though:
array1.split(",").pop()
Try This
$(this).closest('.ui-dialog-content').dialog('close');
It will close the dialog inside it.
I know this is an old post, but I wanted to add something I learned for the next folks who land here while googling.
In Powershell 5.1, you want to use continue
to move onto the next item in your loop. I tested with 6 items in an array, had a foreach
loop through, but put an if statement with:
foreach($i in $array){
write-host -fore green "hello $i"
if($i -like "something"){
write-host -fore red "$i is bad"
continue
write-host -fore red "should not see this"
}
}
Of the 6 items, the 3rd one was something. As expected, it looped through the first 2, then the matching something gave me the red line where $i
matched, I saw something is bad
and then it went on to the next item in the array without saying should not see this
. I tested with return
and it exited the loop altogether.
From the Python documentation:
This object is commonly used by slicing (see Slicings). It supports no special operations. There is exactly one ellipsis object, named Ellipsis (a built-in name).
type(Ellipsis)()
produces the Ellipsis singleton.It is written as
Ellipsis
or...
.
Most preferable answer by @BankZ
sp_help 'TableName'
additionally for different schema
sp_help 'schemaName.TableName'
Your question can be conveniently divided into several parts:
Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.
How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.
You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):
Download and install a trusted VPN.
Install the VPN on your Android device.
Open the application and connect to a server in a different country.
Your Android location will now be successfully changed!
Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.
Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.
How do you send the message?
The classes in the System.Net.Mail
namespace (which is probably what you should use) has full support for authentication, either specified in Web.config, or using the SmtpClient.Credentials
property.
public static Stream ToStream(this Image image)
{
var stream = new MemoryStream();
image.Save(stream, image.RawFormat);
stream.Position = 0;
return stream;
}
If you set the return value of setInterval
to a variable, you can use clearInterval
to stop it.
var myTimer = setInterval(...);
clearInterval(myTimer);
If you want add a day (24 hours) to current datetime you can add milliseconds like this:
new Date(Date.now() + ( 3600 * 1000 * 24))
you could use replaceAll instead of remove and append replaceAll
A class with a field:
Public Class MyStudent
Public StudentId As Integer
The constructor:
Public Sub New(newStudentId As Integer)
StudentId = newStudentId
End Sub
End Class
Most of the answers in this thread are catered to use with JSON.stringify
specifically -- they do not show how to actually remove circular-references in the original object-tree. (well, short of calling JSON.parse
again afterward -- which requires reassignment, and has a higher performance impact)
For removing circular-references from the source object-tree, you can use a function such as this: https://stackoverflow.com/a/63952549/2441655
These general-purpose circular-reference-remover functions can then be used to make subsequent calls to circular-reference-sensitive functions (like JSON.stringify
) safe:
const objTree = {normalProp: true};
objTree.selfReference = objTree;
RemoveCircularLinks(objTree); // without this line, the JSON.stringify call errors
console.log(JSON.stringify(objTree));
Add following codesnippet in your cofig file
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
I review all answer but all have a performance issue.
for example in :
string _Title;
public string Title
{
get
{
if (_Title == null)
{
Deployment.Current.Dispatcher.InvokeAsync(async () => { Title = await getTitle(); });
}
return _Title;
}
set
{
if (value != _Title)
{
_Title = value;
RaisePropertyChanged("Title");
}
}
}
Deployment.Current.Dispatcher.InvokeAsync(async () => { Title = await getTitle(); });
use dispatcher which is not a good answer.
but there is a simple solution, just do it:
string _Title;
public string Title
{
get
{
if (_Title == null)
{
Task.Run(()=>
{
_Title = getTitle();
RaisePropertyChanged("Title");
});
return;
}
return _Title;
}
set
{
if (value != _Title)
{
_Title = value;
RaisePropertyChanged("Title");
}
}
}
I use the following:
git grep ^ | wc -l
This searches all files versioned by git for the regex ^
, which represents the beginning of a line, so this command gives the total number of lines!
Most importantly make sure your file name is Dockerfile
if you use another name it won't work(at least it did not for me.)
Also if you are in the same dir where the Dockerfile is use a .
i.e.
docker build -t Myubuntu1:v1 .
or use the absolute path i.e
docker build -t Myubuntu1:v1 /Users/<username>/Desktop/Docker
awk '{sum+=$3}; END {printf "%f",sum/NR}' ${file}_${f}_v1.xls >> to-plot-p.xls
print
will insert a newline by default. You dont want that to happen, hence use printf
instead.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
final RelativeLayout relativeLayout = new RelativeLayout(this);
final TextView tv1 = new TextView(this);
tv1.setText("tv1 is here");
// Setting an ID is mandatory.
tv1.setId(View.generateViewId());
relativeLayout.addView(tv1);
final TextView tv2 = new TextView(this);
tv2.setText("tv2 is here");
// We are defining layout params for tv2 which will be added to its parent relativelayout.
// The type of the LayoutParams depends on the parent type.
RelativeLayout.LayoutParams tv2LayoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
//Also, we want tv2 to appear below tv1, so we are adding rule to tv2LayoutParams.
tv2LayoutParams.addRule(RelativeLayout.BELOW, tv1.getId());
//Now, adding the child view tv2 to relativelayout, and setting tv2LayoutParams to be set on view tv2.
relativeLayout.addView(tv2);
tv2.setLayoutParams(tv2LayoutParams);
//Or we can combined the above two steps in one line of code
//relativeLayout.addView(tv2, tv2LayoutParams);
this.setContentView(relativeLayout);
}
}
First if the object you're dealing with is a string then you need to parse it then figure out the length of the keys :
obj = JSON.parse(jsonString);
shareInfoLen = Object.keys(obj.shareInfo[0]).length;
d
and i
conversion specifiers behave the same with fprintf
but behave differently for fscanf
.
As some other wrote in their answer, the idiomatic way to print an int
is using d
conversion specifier.
Regarding i
specifier and fprintf
, C99 Rationale says that:
The %i conversion specifier was added in C89 for programmer convenience to provide symmetry with fscanf’s %i conversion specifier, even though it has exactly the same meaning as the %d conversion specifier when used with fprintf.
An alternative that has not been mentioned, but that may be a more efficient option for some (won't work with NULL entries) is to use a sparse index (entries in the index only exist when there is something in the field). Here is a sample data set:
db.foo.find()
{ "_id" : ObjectId("544540b31b5cf91c4893eb94"), "imageUrl" : "http://example.com/foo.jpg" }
{ "_id" : ObjectId("544540ba1b5cf91c4893eb95"), "imageUrl" : "http://example.com/bar.jpg" }
{ "_id" : ObjectId("544540c51b5cf91c4893eb96"), "imageUrl" : "http://example.com/foo.png" }
{ "_id" : ObjectId("544540c91b5cf91c4893eb97"), "imageUrl" : "http://example.com/bar.png" }
{ "_id" : ObjectId("544540ed1b5cf91c4893eb98"), "otherField" : 1 }
{ "_id" : ObjectId("544540f11b5cf91c4893eb99"), "otherField" : 2 }
Now, create the sparse index on imageUrl field:
db.foo.ensureIndex( { "imageUrl": 1 }, { sparse: true } )
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
Now, there is always a chance (and in particular with a small data set like my sample) that rather than using an index, MongoDB will use a table scan, even for a potential covered index query. As it turns out that gives me an easy way to illustrate the difference here:
db.foo.find({}, {_id : 0, imageUrl : 1})
{ "imageUrl" : "http://example.com/foo.jpg" }
{ "imageUrl" : "http://example.com/bar.jpg" }
{ "imageUrl" : "http://example.com/foo.png" }
{ "imageUrl" : "http://example.com/bar.png" }
{ }
{ }
OK, so the extra documents with no imageUrl
are being returned, just empty, not what we wanted. Just to confirm why, do an explain:
db.foo.find({}, {_id : 0, imageUrl : 1}).explain()
{
"cursor" : "BasicCursor",
"isMultiKey" : false,
"n" : 6,
"nscannedObjects" : 6,
"nscanned" : 6,
"nscannedObjectsAllPlans" : 6,
"nscannedAllPlans" : 6,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 0,
"server" : "localhost:31100",
"filterSet" : false
}
So, yes, a BasicCursor
equals a table scan, it did not use the index. Let's force the query to use our sparse index with a hint()
:
db.foo.find({}, {_id : 0, imageUrl : 1}).hint({imageUrl : 1})
{ "imageUrl" : "http://example.com/bar.jpg" }
{ "imageUrl" : "http://example.com/bar.png" }
{ "imageUrl" : "http://example.com/foo.jpg" }
{ "imageUrl" : "http://example.com/foo.png" }
And there is the result we were looking for - only documents with the field populated are returned. This also only uses the index (i.e. it is a covered index query), so only the index needs to be in memory to return the results.
This is a specialized use case and can't be used generally (see other answers for those options). In particular it should be noted that as things stand you cannot use count()
in this way (for my example it will return 6 not 4), so please only use when appropriate.
Can add muted
tag.
<video autoplay muted>
<source src="video.webm" type="video/webm" />
<source src="video.mp4" type="video/mp4" />
</video>
reference https://developers.google.com/web/updates/2016/07/autoplay
Just add a new datafile for the existing tablespace
ALTER TABLESPACE LEGAL_DATA ADD DATAFILE '/u01/oradata/userdata03.dbf' SIZE 200M;
To find out the location and size of your data files:
SELECT FILE_NAME, BYTES FROM DBA_DATA_FILES WHERE TABLESPACE_NAME = 'LEGAL_DATA';
Use this for every external link
$('a[href^="http://"], a[href^="https://"]').attr('target', '_blank');
By Default angular return responseType as Json, but we can configure below types according to your requirement.
responseType: 'arraybuffer'|'blob'|'json'|'text'
Ex:
this.http.post(
'http://localhost:8080/order/addtocart',
{ dealerId: 13, createdBy: "-1", productId, quantity },
{ headers, responseType: 'text'});
Any - boolean function that returns true when any of object in list satisfies condition set in function parameters. For example:
List<string> strings = LoadList();
boolean hasNonEmptyObject = strings.Any(s=>string.IsNullOrEmpty(s));
Where - function that returns list with all objects in list that satisfy condition set in function parameters. For example:
IEnumerable<string> nonEmptyStrings = strings.Where(s=> !string.IsNullOrEmpty(s));
Exists - basically the same as any but it's not generic - it's defined in List class, while Any is defined on IEnumerable interface.
There are many suggestions but I found two of them most common.
I first tried export JAVA_OPTS="-Dhttps.protocols=SSLv3,TLSv1,TLSv1.1,TLSv1.2"
on command line before startup of program but it didn't work for me.
Then I added the following code in the startup class constructor and it worked for me.
try {
SSLContext ctx = SSLContext.getInstance("TLSv1.2");
ctx.init(null, null, null);
SSLContext.setDefault(ctx);
} catch (Exception e) {
System.out.println(e.getMessage());
}
Frankly, I don't know in detail why ctx.init(null, null, null);
but all (SSL/TLS) is working fine for me.
There is one more option: System.setProperty("https.protocols", "SSLv3,TLSv1,TLSv1.1,TLSv1.2");
. It will also go in code but I've not tried it.
package in.co.largestinarraylist;
import java.util.ArrayList;
import java.util.Scanner;
public class LargestInArrayList {
public static void main(String[] args) {
int n;
ArrayList<Integer> L = new ArrayList<Integer>();
int max;
Scanner in = new Scanner(System.in);
System.out.println("Enter Size of Array List");
n = in.nextInt();
System.out.println("Enter elements in Array List");
for (int i = 0; i < n; i++) {
L.add(in.nextInt());
}
max = L.get(0);
for (int i = 0; i < L.size(); i++) {
if (L.get(i) > max) {
max = L.get(i);
}
}
System.out.println("Max Element: " + max);
in.close();
}
}
I agree with @Gonzalo's answer. I have a process that doesn't do I/O, and here is what I've found:
Note that all threads work on one array but different ranges (two threads do not access the same index), so the results may differ if they've worked on different arrays.
The 1.86 machine is a macbook air with an SSD. The other mac is an iMac with a normal HDD (I think it's 7200 rpm). The windows machine also has a 7200 rpm HDD.
In this test, the optimal number was equal to the number of cores in the machine.
This code doesn't do what you expect:
If Dir(SigString) <> "" Then
Signature = GetBoiler(SigString)
Else
Signature = ""
End If
If you pass an empty string (""
) or vbNullString
to Dir
, it will return the name of the first file in the current directory path (the path returned by CurDir$
). So, if SigString
is empty, your If
condition will evaluate to True
because Dir
will return a non-empty string (the name of the first file in the current directory), and GetBoiler
will be called. And if SigString
is empty, the call to fso.GetFile
will fail.
You should either change your condition to check that SigString
isn't empty, or use the FileSystemObject.FileExists
method instead of Dir
for checking if the file exists. Dir
is tricky to use precisely because it does things you might not expect it to do. Personally, I would use Scripting.FileSystemObject
over Dir
because there's no funny business (FileExists
returns True
if the file exists, and, well, False
if it doesn't). What's more, FileExists
expresses the intent of your code much clearly than Dir
.
Method 1: Check that SigString
is non-empty first
If SigString <> "" And Dir(SigString) <> "" Then
Signature = GetBoiler(SigString)
Else
Signature = ""
End If
Method 2: Use the FileSystemObject.FileExists
method
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(SigString) Then
Signature = GetBoiler(SigString)
Else
Signature = ""
End If
Try it like,
<?php
$name='your name';
echo '<table>
<tr><th>Name</th></tr>
<tr><td>'.$name.'</td></tr>
</table>';
?>
Updated
<?php
echo '<table>
<tr><th>Rst</th><th>Marks</th></tr>
<tr><td>'.$rst4.'</td><td>'.$marks4.'</td></tr>
</table>';
?>
Use this:
void double_to_char(double f,char * buffer){
gcvt(f,10,buffer);
}
It's not really a question of what's more efficient.
The commands 'rsync', and 'cp' are not equivalent and achieve different goals.
1- rsync can preserve the time of creation of existing files. (using -a option)
2- rsync will run multiprocess and transfer using either local sockets or network sockets. (i.e. fork itself into multiple processes)
3- The multiprocessing, and threading will increase your throughput when copying large number of small files, and even with multiple larger files.
So bottom line is rsync is for large data, and cp is for smaller local copying. (MB to small GB range). When you start getting into multiple GB or in the TB range, go with rsync. And of course network copies, rsync all the way.
For Swift 2.3
extension UIButton {
func underline() {
let attributedString = NSMutableAttributedString(string: (self.titleLabel?.text!)!)
attributedString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleSingle.rawValue, range: NSRange(location: 0, length: (self.titleLabel?.text!.characters.count)!))
self.setAttributedTitle(attributedString, forState: .Normal)
}
}
and in ViewController
@IBOutlet var yourButton: UIButton!
in ViewDidLoad
Method or in your function just write
yourButton.underline()
it will underline the title of your button
This is fairly easy to answer from the internet. Set system properties http.proxyHost
and http.proxyPort
. You can do this with System.setProperty()
, or from the command line with the -D
syntax.
I too got this error. Incidentally, i typed __int__ instead of __init__.
I think, in many mistype cases the IDE i am using (IntelliJ) would have changed the color to the default set for Function definition. But, in my case __int__ being another dunder/magic method, color remained same as the one which IDE displays for __init__ (default Predefined item definition color), which took me some time in spotting the missing i.
You can't resize an array in Java. You'd need to either:
Create a new array of the desired size, and copy the contents from the original array to the new array, using java.lang.System.arraycopy(...);
Use the java.util.ArrayList<T>
class, which does this for you when you need to make the array bigger. It nicely encapsulates what you describe in your question.
Use java.util.Arrays.copyOf(...)
methods which returns a bigger array, with the contents of the original array.
As you have said if you want to add 24 hours to the timestamp for right now then simply you can do:
<?php echo strtotime('+1 day'); ?>
Above code will add 1 day or 24 hours to your current timestamp.
in place of +1 day
you can take whatever you want, As php manual says strtotime can Parse about any English textual datetime description into a Unix timestamp.
examples from the manual are as below:
<?php
echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";
?>
A very simple and elegant solution to this is provided by W3C. Simply use the margin:0 auto declaration as follows:
.top_image img { margin:0 auto; }
More information and examples from W3C.
If you have tried installing via the official docker-compose page, where you need to download the binary using curl:
curl -L https://github.com/docker/compose/releases/download/1.8.0/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
Then do not forget to add executable flag to the binary:
chmod +x /usr/local/bin/docker-compose
If docker-compose is installed using python-pip
sudo apt-get -y install python-pip
sudo pip install docker-compose
try using pip show --files docker-compose
to see where it is installed.
If docker-compose is installed in user path, then try:
sudo "PATH=$PATH" docker-compose
As I see from your updated post, docker-compose is installed in user path /home/user/.local/bin
and if this path is not in your local path $PATH
, then try:
sudo "PATH=$PATH:/home/user/.local/bin" docker-compose
In case you are willing to use Curl for the calls with JSON 2 and Spring 3.2.0 in hand checkout the FAQ here. As AnnotationMethodHandlerAdapter is deprecated and replaced by RequestMappingHandlerAdapter.
You can animate the position (top, bottom, left, right) and then subtract the element's width or height through a CSS transformation.
Consider:
$('.animate').on('click', function(){
$(this).toggleClass("move");
})
_x000D_
.animate {
height: 100px;
width: 100px;
background-color: #c00;
transition: all 1s ease;
position: absolute;
cursor: pointer;
font: 13px/100px sans-serif;
color: white;
text-align: center;
}
/* ? just to position things */
.animate.left { left: 0; top: 50%; margin-top: -100px;}
.animate.right { right: 0; top: 50%; }
.animate.top { top: 0; left: 50%; }
.animate.bottom { bottom: 0; left: 50%; margin-left: -100px;}
.animate.left.move {
left: 100%;
transform: translate(-100%, 0);
}
.animate.right.move {
right: 100%;
transform: translate(100%, 0);
}
.animate.top.move {
top: 100%;
transform: translate(0, -100%);
}
.animate.bottom.move {
bottom: 100%;
transform: translate(0, 100%);
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Click to animate
<div class="animate left">left</div>
<div class="animate top">top</div>
<div class="animate bottom">bottom</div>
<div class="animate right">right</div>
_x000D_
And then animate depending on the position...
Closeable
extends AutoCloseable
, and is specifically dedicated to IO streams: it throws IOException instead of Exception, and is idempotent, whereas AutoCloseable doesn't provide this guarantee.
This is all explained in the javadoc of both interfaces.
Implementing AutoCloseable (or Closeable) allows a class to be used as a resource of the try-with-resources construct introduced in Java 7, which allows closing such resources automatically at the end of a block, without having to add a finally block which closes the resource explicitely.
Your class doesn't represent a closeable resource, and there's absolutely no point in implementing this interface: an IOTest can't be closed. It shouldn't even be possible to instantiate it, since it doesn't have any instance method. Remember that implementing an interface means that there is a is-a relationship between the class and the interface. You have no such relationship here.
They can make deleting records more cumbersome - you can't delete the "master" record where there are records in other tables where foreign keys would violate that constraint. You can use triggers to have cascading deletes.
If you chose your primary key unwisely, then changing that value becomes even more complex. For example, if I have the PK of my "customers" table as the person's name, and make that key a FK in the "orders" table", if the customer wants to change his name, then it is a royal pain... but that is just shoddy database design.
I believe the advantages in using fireign keys outweighs any supposed disadvantages.
I usually use *
when I want to get all the strings that contain the wanted characters.
*
used in regex, replaces all characters.
Used in SASS or CSS would be something like [id*="s"]
and it will get all DOM elements with id "s......".
/* add red color to all div with id s .... elements */
div[id^="s"] {
color: red;
}
You can also pipe to a while
loop that can do multiple actions on the file which find
locates. So here is one for looking in jar
archives for a given java class file in folder with a large distro of jar
files
find /usr/lib/eclipse/plugins -type f -name \*.jar | while read jar; do echo $jar; jar tf $jar | fgrep IObservableList ; done
the key point being that the while
loop contains multiple commands referencing the passed in file name separated by semicolon and these commands can include pipes. So in that example I echo the name of the matching file then list what is in the archive filtering for a given class name. The output looks like:
/usr/lib/eclipse/plugins/org.eclipse.core.contenttype.source_3.4.1.R35x_v20090826-0451.jar /usr/lib/eclipse/plugins/org.eclipse.core.databinding.observable_1.2.0.M20090902-0800.jar org/eclipse/core/databinding/observable/list/IObservableList.class /usr/lib/eclipse/plugins/org.eclipse.search.source_3.5.1.r351_v20090708-0800.jar /usr/lib/eclipse/plugins/org.eclipse.jdt.apt.core.source_3.3.202.R35x_v20091130-2300.jar /usr/lib/eclipse/plugins/org.eclipse.cvs.source_1.0.400.v201002111343.jar /usr/lib/eclipse/plugins/org.eclipse.help.appserver_3.1.400.v20090429_1800.jar
in my bash shell (xubuntu10.04/xfce) it really does make the matched classname bold as the fgrep
highlights the matched string; this makes it really easy to scan down the list of hundreds of jar
files that were searched and easily see any matches.
on windows you can do the same thing with:
for /R %j in (*.jar) do @echo %j & @jar tf %j | findstr IObservableList
note that in that on windows the command separator is '&' not ';' and that the '@' suppresses the echo of the command to give a tidy output just like the linux find output above; although findstr
is not make the matched string bold so you have to look a bit closer at the output to see the matched class name. It turns out that the windows 'for' command knows quite a few tricks such as looping through text files...
enjoy
To properly answer this qustion you need to consider PHP internals or the target that PHP is built for.
To answer this from a typical Linux perspective on x86...
Sizes of types in C: https://usrmisc.wordpress.com/2012/12/27/integer-sizes-in-c-on-32-bit-and-64-bit-linux/
Types used in PHP for variables: http://php.net/manual/en/internals2.variables.intro.php
Strings are always 2GB as the length is always 32bits and a bit is wasted because it uses int rather than uint. int is impractical for lengths over 2GB as it requires a cast to avoid breaking arithmetic or "than" comparisons. The extra bit is likely being used for overflow checks.
Strangely, hash keys might internally support 4GB as uint is used although I have never put this to the test. PHP hash keys have a +1 to the length for a trailing null byte which to my knowledge gets ignored so it may need to be unsigned for that edge case rather than to allow longer keys.
A 32bit system may impose more external limits.
In your template, you have access to all the variables that are members of the current $scope
. So, tobedone
should be $scope.tobedone
, and then you can display it with {{tobedone}}
, or [[tobedone]]
in your case.
As mentioned above by others,
Scrum is an iterative and incremental agile software development method for managing software projects and product or application development. So Scrum is in fact a type of Agile approach which is used widely in software developments.
So, Scrum is a specific flavor of Agile, specifically it is referred to as an agile project management framework.
Also Scrum has mainly two roles inside it, which are: 1. Main/Core Role 2. Ancillary Role
Main/Core role: It consists of mainly three roles: a). Scrum Master, b). Product Owner, c). Development Team.
Ancillary Role: The ancillary roles in Scrum teams are those with no formal role and infrequent involvement in the Scrum procession but nonetheless, they must be taken into account. viz. Stakeholders, Managers.
Scrum Master:- There are 6 types of meetings in scrum:
Let me know if any one need more inputs on this.
A base 10 number can be expressed as a series of the form
a × 10^p + b × 10^p-1 .. z × 10^0
so the sum of a number's digits is the sum of the coefficients of the terms.
Based on this information, the sum of the digits can be computed like this:
import math
def add_digits(n):
# Assume n >= 0, else we should take abs(n)
if 0 <= n < 10:
return n
r = 0
ndigits = int(math.log10(n))
for p in range(ndigits, -1, -1):
d, n = divmod(n, 10 ** p)
r += d
return r
This is effectively the reverse of the continuous division by 10 in the accepted answer. Given the extra computation in this function compared to the accepted answer, it's not surprising to find that this approach performs poorly in comparison: it's about 3.5 times slower, and about twice as slow as
sum(int(x) for x in str(n))
You can also try another library - https://github.com/wikimedia/jquery.i18n .
In addition to parameter replacement and multiple plural forms, it has support for gender a rather unique feature of custom grammar rules that some languages need.
Many of these solutions here ignore git
version tags which still means you have to track version in multiple places (bad). I approached this with the following goals:
git
repogit tag
/push
and setup.py upload
steps with a single command that takes no inputs.From a make release
command, the last tagged version in the git repo is found and incremented. The tag is pushed back to origin
.
The Makefile
stores the version in src/_version.py
where it will be read by setup.py
and also included in the release. Do not check _version.py
into source control!
setup.py
command reads the new version string from package.__version__
.
# remove optional 'v' and trailing hash "v1.0-N-HASH" -> "v1.0-N"
git_describe_ver = $(shell git describe --tags | sed -E -e 's/^v//' -e 's/(.*)-.*/\1/')
git_tag_ver = $(shell git describe --abbrev=0)
next_patch_ver = $(shell python versionbump.py --patch $(call git_tag_ver))
next_minor_ver = $(shell python versionbump.py --minor $(call git_tag_ver))
next_major_ver = $(shell python versionbump.py --major $(call git_tag_ver))
.PHONY: ${MODULE}/_version.py
${MODULE}/_version.py:
echo '__version__ = "$(call git_describe_ver)"' > $@
.PHONY: release
release: test lint mypy
git tag -a $(call next_patch_ver)
$(MAKE) ${MODULE}/_version.py
python setup.py check sdist upload # (legacy "upload" method)
# twine upload dist/* (preferred method)
git push origin master --tags
The release
target always increments the 3rd version digit, but you can use the next_minor_ver
or next_major_ver
to increment the other digits. The commands rely on the versionbump.py
script that is checked into the root of the repo
"""An auto-increment tool for version strings."""
import sys
import unittest
import click
from click.testing import CliRunner # type: ignore
__version__ = '0.1'
MIN_DIGITS = 2
MAX_DIGITS = 3
@click.command()
@click.argument('version')
@click.option('--major', 'bump_idx', flag_value=0, help='Increment major number.')
@click.option('--minor', 'bump_idx', flag_value=1, help='Increment minor number.')
@click.option('--patch', 'bump_idx', flag_value=2, default=True, help='Increment patch number.')
def cli(version: str, bump_idx: int) -> None:
"""Bumps a MAJOR.MINOR.PATCH version string at the specified index location or 'patch' digit. An
optional 'v' prefix is allowed and will be included in the output if found."""
prefix = version[0] if version[0].isalpha() else ''
digits = version.lower().lstrip('v').split('.')
if len(digits) > MAX_DIGITS:
click.secho('ERROR: Too many digits', fg='red', err=True)
sys.exit(1)
digits = (digits + ['0'] * MAX_DIGITS)[:MAX_DIGITS] # Extend total digits to max.
digits[bump_idx] = str(int(digits[bump_idx]) + 1) # Increment the desired digit.
# Zero rightmost digits after bump position.
for i in range(bump_idx + 1, MAX_DIGITS):
digits[i] = '0'
digits = digits[:max(MIN_DIGITS, bump_idx + 1)] # Trim rightmost digits.
click.echo(prefix + '.'.join(digits), nl=False)
if __name__ == '__main__':
cli() # pylint: disable=no-value-for-parameter
This does the heavy lifting how to process and increment the version number from git
.
The my_module/_version.py
file is imported into my_module/__init__.py
. Put any static install config here that you want distributed with your module.
from ._version import __version__
__author__ = ''
__email__ = ''
The last step is to read the version info from the my_module
module.
from setuptools import setup, find_packages
pkg_vars = {}
with open("{MODULE}/_version.py") as fp:
exec(fp.read(), pkg_vars)
setup(
version=pkg_vars['__version__'],
...
...
)
Of course, for all of this to work you'll have to have at least one version tag in your repo to start.
git tag -a v0.0.1
In python automatic garbage collection deallocates the variable (pandas DataFrame are also just another object in terms of python). There are different garbage collection strategies that can be tweaked (requires significant learning).
You can manually trigger the garbage collection using
import gc
gc.collect()
But frequent calls to garbage collection is discouraged as it is a costly operation and may affect performance.
&& and || are short circuit operators operating on scalars. & and | operate on arrays, and use short-circuiting only in the context of if
or while
loop expressions.
For more complex scraping applications, I would recommend the IRobotSoft web scraper. It is a dedicated free software for screen scraping. It has a strong query language for HTML pages, and it provides a very simple web recording interface that will free you from many programming effort.
In my case, i got wifi problem. make sure you have valid internet connection
Follow below steps:
Open catalina.sh
from tomcat/bin.
Change JAVA_OPTS to
JAVA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8 -server -Xms1536m
-Xmx1536m -XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"
Restart your tomcat
<input name="amount" type="text" value="Only number in here"/>
<script>
$('input[name=amount]').keyup(function(){
$(this).val($(this).val().replace(/[^\d]/,''));
});
</script>
I had the same problem, and I was using the following plugin for tests:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.9</version>
<configuration>
<useFile>true</useFile>
<includes>
<include>**/*Tests.java</include>
<include>**/*Test.java</include>
</includes>
<excludes>
<exclude>**/Abstract*.java</exclude>
</excludes>
<junitArtifactName>junit:junit</junitArtifactName>
<parallel>methods</parallel>
<threadCount>10</threadCount>
</configuration>
</plugin>
The test were running fine in the IDE (eclipse sts), but failed when using command mvn test.
After a lot of trial and error, I figured the solution was to remove parallel testing, the following two lines from the plugin configuration above:
<parallel>methods</parallel>
<threadCount>10</threadCount>
Hope that this helps someone out!
Whenever a record has updated a record is "deleted". Here is my example:
ALTER TRIGGER [dbo].[UpdatePhyDate]
ON [dbo].[M_ContractDT1]
AFTER UPDATE
AS
BEGIN
-- on ContarctDT1 PhyQty is updated
-- I want system date in Phytate automatically saved
SET NOCOUNT ON;
declare @dt1ky as int
if(update(Phyqty))
begin
select @dt1ky = dt1ky from deleted
update M_ContractDT1 set PhyDate=GETDATE() where Dt1Ky= @dt1ky
end
END
It works fine
For more complex classes you could consider the tool jsonpickle:
jsonpickle is a Python library for serialization and deserialization of complex Python objects to and from JSON.
The standard Python libraries for encoding Python into JSON, such as the stdlib’s json, simplejson, and demjson, can only handle Python primitives that have a direct JSON equivalent (e.g. dicts, lists, strings, ints, etc.). jsonpickle builds on top of these libraries and allows more complex data structures to be serialized to JSON. jsonpickle is highly configurable and extendable–allowing the user to choose the JSON backend and add additional backends.
The best solution is definitely to go to File>Invalidate Caches & Restart
Then in the dialog menu... Click Invalidate Caches & Restart. Wait a minute or however long it takes to reset your project, then you should be good.
--
I should note that I also ran into the issue of referencing a resource file or "R" file that was inside a compileOnly library that I had inside my gradle. (i.e. compileOnly library > res > referenced xml file) I stopped referencing this file in my Java code and it helped me. So be weary of where you are referencing files.
I had a key file & a crt file but it wouldn't show in IIS because I couldn't attach the key to the certificate during the import. Ended up creating a pfx file containing the certificate & the key, and after that it worked (When importing to the computer and not local user)
Created the file with OpenSSL (Download first).
openssl pkcs12 -export -out domain.name.pfx -inkey domain.name.key -in domain.name.crt
Set your onClickListener
s on onBindViewHolder()
and you can access the position from there. If you set them in your ViewHolder
you won't know what position was clicked unless you also pass the position into the ViewHolder
EDIT
As pskink
pointed out ViewHolder
has a getPosition()
so the way you were originally doing it was correct.
When the view is clicked you can use getPosition()
in your ViewHolder
and it returns the position
Update
getPosition()
is now deprecated and replaced with getAdapterPosition()
Update 2020
getAdapterPosition()
is now deprecated and replaced with getAbsoluteAdapterPosition()
or getBindingAdapterPosition()
Kotlin code:
override fun onBindViewHolder(holder: MyHolder, position: Int) {
// - get element from your dataset at this position
val item = myDataset.get(holder.absoluteAdapterPosition)
}
You can change the passphrase for your private key by doing:
ssh-keygen -f ~/.ssh/id_rsa -p
Use the following steps to select the database:
mysql -u username -p
it will prompt for password, Please enter password. Now list all the databases
show databases;
select the database which you want to select using the command:
use databaseName;
select data from any table:
select * from tableName limit 10;
You can select your database using the command use photogallery;
Thanks !
Add new folder with name of Images in your project. Put some images into Images folder. Then it will work fine.
<input type="image" src="~/Images/Desert.jpg" alt="Submit" width="48" height="48">
Note: This is not unicode compliant.
"IU".split('')
results in the 4 character array["I", "?", "?", "u"]
which can lead to dangerous bugs. See answers below for safe alternatives.
Just split it by an empty string.
var output = "Hello world!".split('');_x000D_
console.log(output);
_x000D_
See the String.prototype.split()
MDN docs.
As of R 3.3.0, one may use startsWith()
as a faster alternative to grepl()
:
which(startsWith(mydata_2$height_seca1, 1578))
The following is an example of how you might write and read a pickle file. Note that if you keep appending pickle data to the file, you will need to continue reading from the file until you find what you want or an exception is generated by reaching the end of the file. That is what the last function does.
import os
import pickle
PICKLE_FILE = 'pickle.dat'
def main():
# append data to the pickle file
add_to_pickle(PICKLE_FILE, 123)
add_to_pickle(PICKLE_FILE, 'Hello')
add_to_pickle(PICKLE_FILE, None)
add_to_pickle(PICKLE_FILE, b'World')
add_to_pickle(PICKLE_FILE, 456.789)
# load & show all stored objects
for item in read_from_pickle(PICKLE_FILE):
print(repr(item))
os.remove(PICKLE_FILE)
def add_to_pickle(path, item):
with open(path, 'ab') as file:
pickle.dump(item, file, pickle.HIGHEST_PROTOCOL)
def read_from_pickle(path):
with open(path, 'rb') as file:
try:
while True:
yield pickle.load(file)
except EOFError:
pass
if __name__ == '__main__':
main()
Later versions of Safari allow you to Disable Cross-Origin Restrictions. Just enable the developer menu from Preferences >> Advanced, and select "Disable Cross-Origin Restrictions" from the develop menu.
If you want local only, then you only need to enable the developer menu, and select "Disable local file restrictions" from the develop menu.
the above approach didn't work for me on Android Studio 3.0. It still shows the background. I just made an empty background file
<?xml version="1.0" encoding="utf-8"?>
<vector
android:height="108dp"
android:width="108dp"
android:viewportHeight="108"
android:viewportWidth="108"
xmlns:android="http://schemas.android.com/apk/res/android">
</vector>
This worked except the full bleed layers
An extra pair of rabbits' ears should do the trick.
start "" "C:\Program...
START
regards the first quoted parameter as the window-title, unless it's the only parameter - and any switches up until the executable name are regarded as START
switches.
I tried following format, working fine
*/5 * * * * wget --quiet -O /dev/null http://localhost/cron.php
Jaanna, the session parameters in Oracle SQL Developer are dependent on your client computer, while the NLS parameters on PL/SQL is from server.
For example the NLS_NUMERIC_CHARACTERS
on client computer can be ',.' while it's '.,' on server.
So when you run script from PL/SQL and Oracle SQL Developer the decimal separator can be completely different for the same script, unless you alter session with your expected NLS_NUMERIC_CHARACTERS
in the script.
One way to easily test your session parameter is to do:
select to_number(5/2) from dual;
Responsive meta tag
To ensure proper rendering and touch zooming for all devices, add the responsive viewport meta tag to your <head>
.
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
I just stumbled onto this issue accessing some Python libraries: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools". The latest link to that is actually here: https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2019
When you begin the installer, it will have several "options" enabled which will balloon the install size to 5gb. If you have Windows 10, you'll need to leave selected the "Windows 10 SDK" option as mentioned here.
I hope it helps save others time!
You can add Blank Line throw PdfContentByte
class in itextPdf
. As shown below:
package com.pdf.test;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class Ranvijay {
public static final String RESULT = "d:/printReport.pdf";
public void createPdf(String filename) throws Exception {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(filename));
document.open();
Font bold = new Font(Font.FontFamily.HELVETICA, 8f, Font.BOLD);
Font normal = new Font(Font.FontFamily.HELVETICA, 8f, Font.NORMAL);
PdfPTable tabletmp = new PdfPTable(1);
tabletmp.getDefaultCell().setBorder(Rectangle.NO_BORDER);
tabletmp.setWidthPercentage(100);
PdfPTable table = new PdfPTable(2);
float[] colWidths = { 45, 55 };
table.setWidths(colWidths);
String imageUrl = "http://ssl.gstatic.com/s2/oz/images/logo/2x/googleplus_color_33-99ce54a16a32f6edc61a3e709eb61d31.png";
Image image2 = Image.getInstance(new URL(imageUrl));
image2.setWidthPercentage(60);
table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP);
PdfPCell cell = new PdfPCell();
cell.setBorder(Rectangle.NO_BORDER);
cell.addElement(image2);
table.addCell(cell);
String email = "[email protected]";
String collectionDate = "09/09/09";
Chunk chunk1 = new Chunk("Date: ", normal);
Phrase ph1 = new Phrase(chunk1);
Chunk chunk2 = new Chunk(collectionDate, bold);
Phrase ph2 = new Phrase(chunk2);
Chunk chunk3 = new Chunk("\nEmail: ", normal);
Phrase ph3 = new Phrase(chunk3);
Chunk chunk4 = new Chunk(email, bold);
Phrase ph4 = new Phrase(chunk4);
Paragraph ph = new Paragraph();
ph.add(ph1);
ph.add(ph2);
ph.add(ph3);
ph.add(ph4);
table.addCell(ph);
tabletmp.addCell(table);
PdfContentByte canvas = writer.getDirectContent();
canvas.saveState();
canvas.setLineWidth((float) 10 / 10);
canvas.moveTo(40, 806 - (5 * 10));
canvas.lineTo(555, 806 - (5 * 10));
canvas.stroke();
document.add(tabletmp);
canvas.restoreState();
PdfPTable tabletmp1 = new PdfPTable(1);
tabletmp1.getDefaultCell().setBorder(Rectangle.NO_BORDER);
tabletmp1.setWidthPercentage(100);
document.add(tabletmp1);
document.close();
}
/**
* Main method.
*
* @param args
* no arguments needed
* @throws DocumentException
* @throws IOException
*/
public static void main(String[] args) throws Exception {
new Ranvijay().createPdf(RESULT);
System.out.println("Done Please check........");
}
}
@HTML.ActionLink
generates a HTML anchor tag
. While @Url.Action
generates a URL
for you. You can easily understand it by;
// 1. <a href="/ControllerName/ActionMethod">Item Definition</a>
@HTML.ActionLink("Item Definition", "ActionMethod", "ControllerName")
// 2. /ControllerName/ActionMethod
@Url.Action("ActionMethod", "ControllerName")
// 3. <a href="/ControllerName/ActionMethod">Item Definition</a>
<a href="@Url.Action("ActionMethod", "ControllerName")"> Item Definition</a>
Both of these approaches are different and it totally depends upon your need.
set -x
Prints a trace of simple commands, for commands, case commands, select commands, and arithmetic for commands and their arguments or associated word lists after they are expanded and before they are executed. The value of the PS4 variable is expanded and the resultant value is printed before the command and its expanded arguments.
[source]
set -x
echo `expr 10 + 20 `
+ expr 10 + 20
+ echo 30
30
set +x
echo `expr 10 + 20 `
30
Above example illustrates the usage of set -x
. When it is used, above arithmetic expression has been expanded. We could see how a singe line has been evaluated step by step.
expr
has been evaluated.echo
has been evaluated.To know more about set ? visit this link
when it comes to your shell script,
[ "$DEBUG" == 'true' ] && set -x
Your script might have been printing some additional lines of information when the execution mode selected as DEBUG
. Traditionally people used to enable debug mode when a script called with optional argument such as -d
In Visual Studio 2013 & 2015 :
Tools -> Options -> Text Editor -> All Languages -> check Line Numbers
In Xcode 6, you can do this mostly right in Xcode:
The answer is simply that it makes no difference how the segue is triggered.
The prepareForSegue:sender:
method is called in any case and this is where you pass your parameters across.
I know that this maybe a simiple solution, but this is what I do
$("#map_canvas").html("");
markers = [];
Works every time for me.
A few line of java code.
public static void main(String args[]) throws Exception{
String str="test string";
MessageDigest messageDigest=MessageDigest.getInstance("MD5");
messageDigest.update(str.getBytes(),0,str.length());
System.out.println("MD5: "+new BigInteger(1,messageDigest.digest()).toString(16));
}
$ echo 'hello:world:again' |sed 's/:.*//'
hello
Depending on the encoding you wish to use:
var str = System.Text.Encoding.Default.GetString(result);
If you can use Java APIs and additional storage:
public static final boolean isPalindromeWithAdditionalStorage(String string) {
String reversed = new StringBuilder(string).reverse().toString();
return string.equals(reversed);
}
In can need an in-place method for Java:
public static final boolean isPalindromeInPlace(String string) {
char[] array = string.toCharArray();
int length = array.length-1;
int half = Math.round(array.length/2);
char a,b;
for (int i=length; i>=half; i--) {
a = array[length-i];
b = array[i];
if (a != b) return false;
}
return true;
}
Sometimes learning by example helps the most. Run this console application in three different console windows. You'll see that the application you ran first acquires the mutex first, while the other two are waiting their turn. Then press enter in the first application, you'll see that application 2 now continues running by acquiring the mutex, however application 3 is waiting its turn. After you press enter in application 2 you'll see that application 3 continues. This illustrates the concept of a mutex protecting a section of code to be executed only by one thread (in this case a process) like writing to a file as an example.
using System;
using System.Threading;
namespace MutexExample
{
class Program
{
static Mutex m = new Mutex(false, "myMutex");//create a new NAMED mutex, DO NOT OWN IT
static void Main(string[] args)
{
Console.WriteLine("Waiting to acquire Mutex");
m.WaitOne(); //ask to own the mutex, you'll be queued until it is released
Console.WriteLine("Mutex acquired.\nPress enter to release Mutex");
Console.ReadLine();
m.ReleaseMutex();//release the mutex so other processes can use it
}
}
}
So you want to generate date in format YYYYMMDD_hhmmss
.
As %date%
and %time%
formats are locale dependant you might need more robust ways to get a formatted date.
Here's one option:
@if (@X)==(@Y) @end /*
@cscript //E:JScript //nologo "%~f0"
@exit /b %errorlevel%
@end*/
var todayDate = new Date();
todayDate = "" +
todayDate.getFullYear() +
("0" + (todayDate.getMonth() + 1)).slice(-2) +
("0" + todayDate.getDate()).slice(-2) +
"_" +
("0" + todayDate.getHours()).slice(-2) +
("0" + todayDate.getMinutes()).slice(-2) +
("0" + todayDate.getSeconds()).slice(-2) ;
WScript.Echo(todayDate);
and if you save the script as jsdate.bat
you can assign it as a value :
for /f %%a in ('jsdate.bat') do @set "fdate=%%a"
echo %fdate%
or directly from command prompt:
for /f %a in ('jsdate.bat') do @set "fdate=%a"
Or you can use powershell which probably is the way that requires the less code:
for /f %%# in ('powershell Get-Date -Format "yyyyMMdd_HHmmss"') do set "fdate=%%#"
Try this script to get your browser language
<script type="text/javascript">_x000D_
var userLang = navigator.language || navigator.userLanguage; _x000D_
alert ("The language is: " + userLang);_x000D_
</script>
_x000D_
Cheers
The cssrewrite filter is not compatible with the @bundle notation for now. So you have two choices:
Reference the CSS files in the web folder (after: console assets:install --symlink web
)
{% stylesheets '/bundles/myCompany/css/*." filter="cssrewrite" %}
Use the cssembed filter to embed images in the CSS like this.
{% stylesheets '@MyCompanyMyBundle/Resources/assets/css/*.css' filter="cssembed" %}
Install the NUnit and NunitTestAdapter package to your test projects from Manage Nunit packages. to perform the same: 1 Right-click on menu Project ? click "Manage NuGet Packages". 2 Go to the "Browse" tab -> Search for the Nunit (or any other package which you want to install) 3 Click on the Package -> A side screen will open "Select the project and click on the install.
Perform your tasks (Add code) If your project is a Console application then a play/run button is displayed on the top click on that any your application will run and If your application is a class library Go to the Test Explorer and click on "Run All" option.
you can use DateTime.ParseExact
with the format string
DateTime dt = DateTime.ParseExact(inputString, formatString, System.Globalization.CultureInfo.InvariantCulture);
Above will throw an exception if the given string not in given format.
use DateTime.TryParseExact
if you don't need exception in case of format incorrect but you can check the return value of that method to identify whether parsing value success or not.
The following code helped me resolve the issue. The path to the template needs to be provided as part of file.resource.loader path. By default it comes as "." . So setting the property explicitly will be required.
Print getClass().getClassLoader().getResource("resources")
or getClass().getClassLoader().getResource("")
to see where your template comes and based on that set it in the velocity template engine.
URL url = getClass().getClassLoader().getResource("resources");
//URL url = getClass().getClassLoader().getResource("");
File folder= new File(url.getFile());
VelocityEngine ve = new VelocityEngine();
ve.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, folder.getAbsolutePath());
ve.init();
Template template = ve.getTemplate( "MyTemplate.vm" );
You can figure out which proxy server you're using by accessing some websites with a browser and then running the DOS command:
netstat
and you'll see some connections in the Foreign Address column on port 80 or 8080 (common proxy server ports). Ideally you will be able to identify the proxy server by its naming convention.
It seems that OpenQA, guys behind Selenium, have already addressed this problem. They defined some variables to explicitely match whitespaces. In my case, I need to use an XPATH similar to //td[text()="${nbsp}"]
.
I reproduced here the text from OpenQA concerning this issue (found here):
HTML automatically normalizes whitespace within elements, ignoring leading/trailing spaces and converting extra spaces, tabs and newlines into a single space. When Selenium reads text out of the page, it attempts to duplicate this behavior, so you can ignore all the tabs and newlines in your HTML and do assertions based on how the text looks in the browser when rendered. We do this by replacing all non-visible whitespace (including the non-breaking space "
") with a single space. All visible newlines (<br>
,<p>
, and<pre>
formatted new lines) should be preserved.We use the same normalization logic on the text of HTML Selenese test case tables. This has a number of advantages. First, you don't need to look at the HTML source of the page to figure out what your assertions should be; "
" symbols are invisible to the end user, and so you shouldn't have to worry about them when writing Selenese tests. (You don't need to put "
" markers in your test case to assertText on a field that contains "
".) You may also put extra newlines and spaces in your Selenese<td>
tags; since we use the same normalization logic on the test case as we do on the text, we can ensure that assertions and the extracted text will match exactly.This creates a bit of a problem on those rare occasions when you really want/need to insert extra whitespace in your test case. For example, you may need to type text in a field like this: "
foo
". But if you simply write<td>foo </td>
in your Selenese test case, we'll replace your extra spaces with just one space.This problem has a simple workaround. We've defined a variable in Selenese,
${space}
, whose value is a single space. You can use${space}
to insert a space that won't be automatically trimmed, like this:<td>foo${space}${space}${space}</td>
. We've also included a variable${nbsp}
, that you can use to insert a non-breaking space.Note that XPaths do not normalize whitespace the way we do. If you need to write an XPath like
//div[text()="hello world"]
but the HTML of the link is really "hello world
", you'll need to insert a real "
" into your Selenese test case to get it to match, like this://div[text()="hello${nbsp}world"]
.
Use 'Exists' which returns either 0 or 1.
The query will be like:
SELECT EXISTS(SELECT * FROM USER WHERE UserID = 20070022)
Guid.NewGuid()
creates a new random guid.
I've had good results with this one. Much easier to use than Sharpen.
http://tangiblesoftwaresolutions.com/Product_Details/Java_to_CSharp_Converter.html
An alternative solution is using jQuery:
<script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
PrepareCheckbox();
});
function PrepareCheckbox(){
document.getElementById("checkbox").checked = true;
}
</script>
For me following code work
$(function () {
debugger;
document.getElementById("FormId").addEventListener("submit", function (e) {
debugger;
if (ValidDateFrom()) { // Check Validation
var form = e.target;
if (form.getAttribute("enctype") === "multipart/form-data") {
debugger;
if (form.dataset.ajax) {
e.preventDefault();
e.stopImmediatePropagation();
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action);
xhr.onreadystatechange = function (result) {
debugger;
if (xhr.readyState == 4 && xhr.status == 200) {
debugger;
var responseData = JSON.parse(xhr.responseText);
SuccessMethod(responseData); // Redirect to your Success method
}
};
xhr.send(new FormData(form));
}
}
}
}, true);
});
In your Action Post Method, pass parameter as HttpPostedFileBase UploadFile and make sure your file input has same as mentioned in your parameter of the Action Method. It should work with AJAX Begin form as well.
Remember over here that your AJAX BEGIN Form will not work over here since you make your post call defined in the code mentioned above and you can reference your method in the code as per the Requirement
I know I am answering late but this is what worked for me
For any project or Framework project in Xcode that use pods, one easy way to avoid dynamic library (dylb) not to load is to set you pod file to ink in static mode. To do so, just make sure to don't write the following line in your pod file.
use_frameworks!
Once the line deleted from your file which you saved, simply run form the console:
$ pod update
if (listA.Except(listB).Any())
Since Angular 1.4, the limitTo
filter also accepts a second optional argument begin
From the docs:
{{ limitTo_expression | limitTo : limit : begin}}
begin (optional) string|number
Index at which to begin limitation. As a negative index, begin indicates an offset from the end of input. Defaults to 0.
So you don't need to create a new directive, This argument can be used to set the offset of the pagination
ng-repeat="item in vm.items| limitTo: vm.itemsPerPage: (vm.currentPage-1)*vm.itemsPerPage"
The whole code if somebody need it.
void alarm(Context context, Calendar calendar) {
AlarmManager alarmManager = (AlarmManager)context.getSystemService(ALARM_SERVICE);
final String SOME_ACTION = "com.android.mytabs.MytabsActivity.AlarmReceiver";
IntentFilter intentFilter = new IntentFilter(SOME_ACTION);
AlarmReceiver mReceiver = new AlarmReceiver();
context.registerReceiver(mReceiver, intentFilter);
Intent anotherIntent = new Intent(SOME_ACTION);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, anotherIntent, 0);
alramManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(context, "Added", Toast.LENGTH_LONG).show();
}
class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent arg1) {
Toast.makeText(context, "Started", Toast.LENGTH_LONG).show();
}
}
git diff branch_1..branch_2
That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:
git diff branch_1...branch_2
This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.
However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.
In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.
Here is a simple example based on a SAP system I have access to.
Public Sub SimpleSAPExport()
Set SapGuiAuto = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI
Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
Set session = SAPCon.Children(0) 'Get the first session (window) on that connection
'Start the transaction to view a table
session.StartTransaction "SE16"
'Select table T001
session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
session.findById("wnd[0]/tbar[1]/btn[7]").Press
'Set our selection criteria
session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
session.findById("wnd[0]/tbar[1]/btn[8]").press
'Click the export to file button
session.findById("wnd[0]/tbar[1]/btn[45]").press
'Choose the export format
session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
session.findById("wnd[1]/tbar[0]/btn[0]").press
'Choose the export filename
session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\Temp\"
'Export the file
session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub
To help find the names of elements such aswnd[1]/tbar[0]/btn[0]
you can use script recording.
Click the customize local layout button, it probably looks a bit like this:
Then find the Script Recording and Playback menu item.
Within that the More
button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.
The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI")
defines the SapGuiAuto object.
If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx
in the SAP GUI installation folder.
The removeAttr()
function only removes HTML attributes. The display
is not a HTML attribute, it's a CSS property. You'd like to use css()
function instead to manage CSS properties.
But jQuery offers a show()
function which does exactly what you want in a concise call:
$("span").show();
You can use exec
:
exec("import myapp.commands.%s" % command)
As far as the best algorithm goes you probably have it right. I would recommend that you unravel the recursive function and use a stack of your own (remember a stack overflow is the end of the world in a .Net 2.0+ app, the exception can not be caught IIRC).
The most important thing is that if you are using it in any form of a UI put it on a worker thread that signals the UI thread with updates.
$(this).parent().parent().attr('id');
Is how you would get the id of the parent's parent.
EDIT:
$(this).closest('ul').attr('id');
Is a more foolproof solution for your case.
I think this is only partially true. Changing the format seems to switch the date to a string object which then has no methods like AddDays to manipulate it. So to make this work, you have to switch it back to a date. For example:
Get-Date (Get-Date).AddDays(-1) -format D
You can use the Test-Path
cmd-let. So something like...
if(!(Test-Path [oldLocation]) -and !(Test-Path [newLocation]))
{
Write-Host "$file doesn't exist in both locations."
}
You can use git cherry-pick to apply a single commit by itself to your current branch.
Example: git cherry-pick d42c389f
I see you're using inline styles. textDecoration: 'none'
is used in child, where in fact it should be used inside <Link>
as such:
<Link to="first" style={{ textDecoration: 'none' }}>
<MenuItem style={{ paddingLeft: 13 }}>Team 1</MenuItem>
</Link>
<Link>
will essentially return a standard <a>
tag, which is why we apply textDecoration
rule there.
I hope that helps
The JLS 5, Section 15.18.1.1 JLS 8 § 15.18.1 "String Concatenation Operator +", leading to JLS 8, § 5.1.11 "String Conversion", requires this operation to succeed without failure:
...Now only reference values need to be considered. If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l). Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.
Let's look at the bytecode! The compiler takes your code:
String s = null;
s = s + "hello";
System.out.println(s); // prints "nullhello"
and compiles it into bytecode as if you had instead written this:
String s = null;
s = new StringBuilder(String.valueOf(s)).append("hello").toString();
System.out.println(s); // prints "nullhello"
(You can do so yourself by using javap -c
)
The append methods of StringBuilder
all handle null just fine. In this case because null
is the first argument, String.valueOf()
is invoked instead since StringBuilder does not have a constructor that takes any arbitrary reference type.
If you were to have done s = "hello" + s
instead, the equivalent code would be:
s = new StringBuilder("hello").append(s).toString();
where in this case the append method takes the null and then delegates it to String.valueOf()
.
Note: String concatenation is actually one of the rare places where the compiler gets to decide which optimization(s) to perform. As such, the "exact equivalent" code may differ from compiler to compiler. This optimization is allowed by JLS, Section 15.18.1.2:
To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.
The compiler I used to determine the "equivalent code" above was Eclipse's compiler, ecj.
You don't want git revert
. That undoes a previous commit. You want git checkout
to get git's version of the file from master.
git checkout -- filename.txt
In general, when you want to perform a git operation on a single file, use -- filename
.
2020 Update
Git introduced a new command git restore
in version 2.23.0
. Therefore, if you have git version 2.23.0+
, you can simply git restore filename.txt
- which does the same thing as git checkout -- filename.txt
. The docs for this command do note that it is currently experimental.
Set log_statement
to all
:
Here is a simple construct that will do it, by using setdiff
:
rm(list=setdiff(ls(), "x"))
And a full example. Run this at your own risk - it will remove all variables except x
:
x <- 1
y <- 2
z <- 3
ls()
[1] "x" "y" "z"
rm(list=setdiff(ls(), "x"))
ls()
[1] "x"
easier answer - put the stuff in quotes in different cells and then concatenate them!
B1: rcrCheck.asp
C1: =D1&B1&E1
D1: "code in quotes" and "more code in quotes"
E1: "
it comes out perfect (can't show you because I get a stupid dialog box about code)
easy peasy!!
Try adding window
before location
(i.e. window.location
).
As of Android studio 3.4, You need to put this line in your Layout which holds the RecyclerView
.
app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior"
In JavaScript, the type of key/value store you are attempting to use is an object literal, rather than an array. You are mistakenly creating a composite array object, which happens to have other properties based on the key names you provided, but the array portion contains no elements.
Instead, declare valueToPush
as an object and push that onto cookie_value_add
:
// Create valueToPush as an object {} rather than an array []
var valueToPush = {};
// Add the properties to your object
// Note, you could also use the valueToPush["productID"] syntax you had
// above, but this is a more object-like syntax
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;
cookie_value_add.push(valueToPush);
// View the structure of cookie_value_add
console.dir(cookie_value_add);
Jonathan from the ExcelCentral forums suggests:
=WEEKNUM(A1,2)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),2)+1
This formula extracts the week of the year [...] and then subtracts it from the week of the first day in the month to get the week of the month. You can change the day that weeks begin by changing the second argument of both WEEKNUM functions (set to 2 [for Monday] in the above example). For weeks beginning on Sunday, use:
=WEEKNUM(A1,1)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),1)+1
For weeks beginning on Tuesday, use:
=WEEKNUM(A1,12)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),12)+1
etc.
I like it better because it's using the built in week calculation functionality of Excel (WEEKNUM).
This was changing for me beginning with .NET 4.7.2 and it was due to the SameSite property on the session cookie. See here for more info: https://devblogs.microsoft.com/aspnet/upcoming-samesite-cookie-changes-in-asp-net-and-asp-net-core/
The default value changed to "Lax" and started breaking things. I changed it to "None" and things worked as expected.
I have this code snippet run from the ENTRYPOINT
in my docker file:
while true
do
echo "Press [CTRL+C] to stop.."
sleep 1
done
Run the built docker image as:
docker run -td <image name>
Log in to the container shell:
docker exec -it <container id> /bin/bash
From the CSS specification on Calculating widths and margins for Block-level, non-replaced elements in normal flow:
If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element with respect to the edges of the containing block.
Take a look at http://jsfiddle.net/TroyAlford/ZZEk8/ for a working example of the below:
<img id='myImg' src='/my/img/link.gif' />
<script type="text/javascript">
$(document).bind('click', function () {
// Add a click-handler to the image.
$('#myImg').bind('click', function (ev) {
var $img = $(ev.target);
var offset = $img.offset();
var x = ev.clientX - offset.left;
var y = ev.clientY - offset.top;
alert('clicked at x: ' + x + ', y: ' + y);
});
});
</script>
Note that the above will get you the x and the y relative to the image's box - but will not correctly take into account margin, border and padding. These elements aren't actually part of the image, in your case - but they might be part of the element that you would want to take into account.
In this case, you should also use $div.outerWidth(true) - $div.width()
and $div.outerHeight(true) - $div.height()
to calculate the amount of margin / border / etc.
Your new code might look more like:
<img id='myImg' src='/my/img/link.gif' />
<script type="text/javascript">
$(document).bind('click', function () {
// Add a click-handler to the image.
$('#myImg').bind('click', function (ev) {
var $img = $(ev.target);
var offset = $img.offset(); // Offset from the corner of the page.
var xMargin = ($img.outerWidth() - $img.width()) / 2;
var yMargin = ($img.outerHeight() - $img.height()) / 2;
// Note that the above calculations assume your left margin is
// equal to your right margin, top to bottom, etc. and the same
// for borders.
var x = (ev.clientX + xMargin) - offset.left;
var y = (ev.clientY + yMargin) - offset.top;
alert('clicked at x: ' + x + ', y: ' + y);
});
});
</script>
To allow DMARC checks for SPF to pass and also be aligned when using sendmail, make sure you are setting the envelope sender address (-f
or -r
parameter) to something that matches the domain in the From:
header address.
Using PHP's built-in mail()
function without setting the 5th paramater will cause DMARC SPF checks to be unaligned if not done correctly. By default, sendmail will send the email with the webserver's user as the RFC5321.MailFrom / Return Path header.
For example, say you are hosting your website domain.com
on the host.com
web server. If you do not set the additional parameters parameter:
mail($to,$subject,$message,$headers); // Wrong way
The email recipient will receive an email with the following mail headers:
Return-Path: <[email protected]>
From: <[email protected]>
Even though this passes SPF checks, it will be unaligned (since domain.com and host.com do not match), which means that DMARC SPF check will fail as unaligned.
Instead, you must pass the envelope sender address to sendmail by including the 5th parameter in the PHP mail()
function, for example:
mail($to,$subject,$message,$headers, '-r [email protected]'); // Right way
In this case, the email recipient will receive an email with the following mail headers:
Return-Path: <[email protected]>
From: <[email protected]>
Since both of these headers contain addresses from domain.com
, SPF will pass and also be aligned, which means that DMARC will also pass the SPF check.
create table myTable
(
Column1 int not null,
Column2 int not null
)
GO
ALTER TABLE myTable
ADD PRIMARY KEY (Column1,Column2)
GO
I am using Windows and get the same error message. I find another problem which is relevant. I defined OpenCV_DIR in my path at the end of the line. However when I typed "path" in the command line, my OpenCV_DIR was not shown. I found because Windows probably has a limit on how long the path can be, it cut my OpenCV_DIR to be only part of what I defined. So I removed some other part of the path, now it works.
Works for me:
List<Item> list = Task.Run(() => manager.GetList()).Result;
in this way it is not necessary to mark the method with async in the call.
In the default configuration of a SQL Server database, string comparisons are case-insensitive. If your database overrides this setting (through the use of an alternate collation), then you'll need to specify what sort of collation to use in your query.
SELECT * FROM myTable WHERE myField = 'sOmeVal' COLLATE SQL_Latin1_General_CP1_CI_AS
Note that the collation I provided is just an example (though it will more than likely function just fine for you). A more thorough outline of SQL Server collations can be found here.
driver.findElement(By.id("invoice_supplier_id")).setAttribute("value", "your value");
For internal gridlines, use the tag: td For external gridlines, use the tag: table
In this case, you are thinking of the String comparing function "String".equals("some_text")
. Chars do not need to use this function. Instead a standard ==
comparison operator will suffice.
private static int countNumChars(String s) {
for(char c : s.toCharArray()){
if (c == ' ') // your resulting outcome
}
}
Global makes the variable "Global"
def out():
global x
x = 1
print(x)
return
out()
print (x)
This makes 'x' act like a normal variable outside the function. If you took the global out then it would give an error since it cannot print a variable inside a function.
def out():
# Taking out the global will give you an error since the variable x is no longer 'global' or in other words: accessible for other commands
x = 1
print(x)
return
out()
print (x)
Try:
while [ $stats -gt 300 -o $stats -eq 0 ]
[
is a call to test
. It is not just for grouping, like parentheses in other languages. Check man [
or man test
for more information.
The notion of security is meaningless unless you define what it is that you want to be secure against.
If you want to be secure against stored browser history, some types of logging, and people looking at your URLs, then POST is more secure.
If you want to be secure against somebody sniffing your network activity, then there's no difference.
In my case was a ?> at the end of the routes.php. Spent a lot of time there...
The "\z" COMMAND is also a good way to list tables when inside the interactive psql session.
eg.
# psql -d mcdb -U admin -p 5555
mcdb=# /z
Access privileges for database "mcdb"
Schema | Name | Type | Access privileges
--------+--------------------------------+----------+---------------------------------------
public | activities | table |
public | activities_id_seq | sequence |
public | activities_users_mapping | table |
[..]
public | v_schedules_2 | view | {admin=arwdxt/admin,viewuser=r/admin}
public | v_systems | view |
public | vapp_backups | table |
public | vm_client | table |
public | vm_datastore | table |
public | vmentity_hle_map | table |
(148 rows)
Change your directory to where script is located by using cd command
Then type
bash program-name.sh
Yeah, it is quite vague.
You should use it whenever for readers of the documentation of your method it may be useful to also look at some other method. If the documentation of your methodA says "Works like methodB but ...", then you surely should put a link.
An alternative to @see
would be the inline {@link ...}
tag:
/**
* ...
* Works like {@link #methodB}, but ...
*/
When the fact that methodA calls methodB is an implementation detail and there is no real relation from the outside, you don't need a link here.
The min sdk version is the earliest release of the Android SDK that your application can run on. Usually this is because of a problem with the earlier APIs, lacking functionality, or some other behavioural issue.
The target sdk version is the version your application was targeted to run on. Ideally, this is because of some sort of optimal run conditions. If you were to "make your app for version 19", this is where that would be specified. It may run on earlier or later releases, but this is what you were aiming for. This is mostly to indicate how current your application is for use in the marketplace, etc.
The compile sdk version is the version of android your IDE (or other means of compiling I suppose) uses to make your app when you publish a .apk
file. This is useful for testing your application as it is a common need to compile your app as you develop it. As this will be the version to compile to an APK, it will naturally be the version of your release. Likewise, it is advisable to have this match your target sdk version.
Commenting use_frameworks! in PodFile worked for me.
#use_frameworks!
Note: Did this on XCode 10.1, pod version 1.8.4
Differences between
isinstance()
andtype()
in Python?
Type-checking with
isinstance(obj, Base)
allows for instances of subclasses and multiple possible bases:
isinstance(obj, (Base1, Base2))
whereas type-checking with
type(obj) is Base
only supports the type referenced.
As a sidenote, is
is likely more appropriate than
type(obj) == Base
because classes are singletons.
In Python, usually you want to allow any type for your arguments, treat it as expected, and if the object doesn't behave as expected, it will raise an appropriate error. This is known as polymorphism, also known as duck-typing.
def function_of_duck(duck):
duck.quack()
duck.swim()
If the code above works, we can presume our argument is a duck. Thus we can pass in other things are actual sub-types of duck:
function_of_duck(mallard)
or that work like a duck:
function_of_duck(object_that_quacks_and_swims_like_a_duck)
and our code still works.
However, there are some cases where it is desirable to explicitly type-check. Perhaps you have sensible things to do with different object types. For example, the Pandas Dataframe object can be constructed from dicts or records. In such a case, your code needs to know what type of argument it is getting so that it can properly handle it.
So, to answer the question:
isinstance()
and type()
in Python?Allow me to demonstrate the difference:
type
Say you need to ensure a certain behavior if your function gets a certain kind of argument (a common use-case for constructors). If you check for type like this:
def foo(data):
'''accepts a dict to construct something, string support in future'''
if type(data) is not dict:
# we're only going to test for dicts for now
raise ValueError('only dicts are supported for now')
If we try to pass in a dict that is a subclass of dict
(as we should be able to, if we're expecting our code to follow the principle of Liskov Substitution, that subtypes can be substituted for types) our code breaks!:
from collections import OrderedDict
foo(OrderedDict([('foo', 'bar'), ('fizz', 'buzz')]))
raises an error!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in foo
ValueError: argument must be a dict
isinstance
But if we use isinstance
, we can support Liskov Substitution!:
def foo(a_dict):
if not isinstance(a_dict, dict):
raise ValueError('argument must be a dict')
return a_dict
foo(OrderedDict([('foo', 'bar'), ('fizz', 'buzz')]))
returns OrderedDict([('foo', 'bar'), ('fizz', 'buzz')])
In fact, we can do even better. collections
provides Abstract Base Classes that enforce minimal protocols for various types. In our case, if we only expect the Mapping
protocol, we can do the following, and our code becomes even more flexible:
from collections import Mapping
def foo(a_dict):
if not isinstance(a_dict, Mapping):
raise ValueError('argument must be a dict')
return a_dict
It should be noted that type can be used to check against multiple classes using
type(obj) in (A, B, C)
Yes, you can test for equality of types, but instead of the above, use the multiple bases for control flow, unless you are specifically only allowing those types:
isinstance(obj, (A, B, C))
The difference, again, is that isinstance
supports subclasses that can be substituted for the parent without otherwise breaking the program, a property known as Liskov substitution.
Even better, though, invert your dependencies and don't check for specific types at all.
So since we want to support substituting subclasses, in most cases, we want to avoid type-checking with type
and prefer type-checking with isinstance
- unless you really need to know the precise class of an instance.
After one day struggle i found some scenario check may be you are facing same,
If everything is woking same as google code then please check manifest file in my case i added geo key and map key that's why exception occurs,
Note - do not add two keys in manifest file remove map key
meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="@string/google_maps_key"/>
above code and add this code.
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/auto_location"/>
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version"/>
I'm pretty sure you can do explicit casting here.
foo f = (foo)value;
So long as you say the enum inherits(?) from int, which you have.
enum foo : int
EDIT Yes it turns out that by default, an enums underlying type is int. You can however use any integral type except char.
You can also cast from a value that's not in the enum, producing an invalid enum. I suspect this works by just changing the type of the reference and not actually changing the value in memory.
enum (C# Reference)
Enumeration Types (C# Programming Guide)
I was facing the same error, I was trying to install jest into to one of the packages in a monorepo project.
If you are using Yarn + Learna to package a monorepo project, you will have to navigate to the package.json inside the target package and then run npm install
or npm install <package name>
.
In a nutshell, is
checks whether two references point to the same object or not.==
checks whether two objects have the same value or not.
a=[1,2,3]
b=a #a and b point to the same object
c=list(a) #c points to different object
if a==b:
print('#') #output:#
if a is b:
print('##') #output:##
if a==c:
print('###') #output:##
if a is c:
print('####') #no output as c and a point to different object
Trim() works for both sides.
Just my 2 cents regarding the divs option.
Famous/Infamous and SamsaraJS (and possibly others) use absolutely positioned non-nested divs (with non-trivial HTML/CSS content), combined with matrix2d/matrix3d for positioning and 2D/3D transformations, and achieve a stable 60FPS on moderate mobile hardware, so I'd argue against divs being a slow option.
There are plenty of screen recordings on Youtube and elsewhere, of high-performance 2D/3D stuff running in the browser with everything being an DOM element which you can Inspect Element on, at 60FPS (mixed with WebGL for certain effects, but not for the main part of the rendering).
sudo ln -s /usr/lib/jvm/java-7-oracle/jre /usr/lib/jvm/default-java
Create a symbolic link to the default-java directory.
You can find your java directory by
readlink -f $(which java)
# outputs: /usr/lib/jvm/java-7-oracle/jre/bin/java
# Remove the last `/bin/java` and use it in above symbolic link command.
You can check for NaN by using var != var
. NaN
does not equal NaN
.
EDIT: This is probably by far the worst method. It's confusing, terrible for readability, and overall bad practice.
:: For UTF-8 works for Microsoft Office 2016 and higher!
Try this code:
if WScript.Arguments.Count < 2 Then
WScript.Echo "Please specify the source and the destination files. Usage: ExcelToCsv <xls/xlsx source file> <csv destination file>"
Wscript.Quit
End If
csv_format = 62
Set objFSO = CreateObject("Scripting.FileSystemObject")
src_file = objFSO.GetAbsolutePathName(Wscript.Arguments.Item(0))
dest_file = objFSO.GetAbsolutePathName(WScript.Arguments.Item(1))
Dim oExcel
Set oExcel = CreateObject("Excel.Application")
Dim oBook
Set oBook = oExcel.Workbooks.Open(src_file)
oBook.SaveAs dest_file, csv_format
oBook.Close False
oExcel.Quit
I suspect you are running Android 6.0 Marshmallow (API 23) or later. If this is the case, you must implement runtime permissions before you try to read/write external storage.
You can try "ours" option in git merge,
git merge branch -X ours
This option forces conflicting hunks to be auto-resolved cleanly by favoring our version. Changes from the other tree that do not conflict with our side are reflected to the merge result. For a binary file, the entire contents are taken from our side.
xcopy "%userprofile%\Desktop\?????????" "D:\Backup\" /s/h/e/k/f/c
should work, assuming that your language setting allows Cyrillic (or you use Unicode fonts in the console).
For reference about the arguments: http://ss64.com/nt/xcopy.html
formData = new FormData();
formData.append('_token', "{{csrf_token()}}");
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
For the fun of it here's an implementation based on the callback approach:
const char* find(const char* s,
const char* e,
int (*pred)(char))
{
while( s != e && !pred(*s) ) ++s;
return s;
}
void split_on_ws(const char* s,
const char* e,
void (*callback)(const char*, const char*))
{
const char* p = s;
while( s != e ) {
s = find(s, e, isspace);
callback(p, s);
p = s = find(s, e, isnotspace);
}
}
void handle_word(const char* s, const char* e)
{
// handle the word that starts at s and ends at e
}
int main()
{
split_on_ws(some_str, some_str + strlen(some_str), handle_word);
}
Main thing to worry about is how would you notify the elevator that it needs to move up or down. and also if you are going to have a centralized class to control this behavior and how could you distribute the control.
It seems like it can be very simple or very complicated. If we don't take concurrency or the time for an elevator to get to one place, then it seems like it will be simple since we just need to check the states of elevator, like is it moving up or down, or standing still. But if we make Elevator implement Runnable, and constantly check and synchronize a queue (linkedList). A Controller class will assign which floor to go in the queue. When the queue is empty, the run() method will wait (queue.wait() ), when a floor is assigned to this elevator, it will call queue.notify() to wake up the run() method, and run() method will call goToFloor(queue.pop()). This will make the problem too complicated. I tried to write it on paper, but dont think it works. It seems like we don't really need to take concurrency or timing issue into account here, but we do need to somehow use a queue to distribute the control.
Any suggestion?
Solution by @omiday worked for me in Xvnc TigerVNC 1.1.0, so I condensed it into a single bash function vncsize x y. Use it like this: vncsize 1400 1000. It works for any VNC output name, "default" or "VNC-0".
function vncsize {
local x=$1 y=$2
local mode
if mode=$(cvt "$x" "$y" 2>/dev/null)
then
if [[ $mode =~ "Modeline (.*)$" ]]
then
local newMode=${BASH_REMATCH[1]//\"/}
local modeName=${newMode%% *}
local newSize=( ${modeName//[\"x_]/ } )
local screen=$(xrandr -q|grep connected|cut -d' ' -f1)
xrandr --newmode $newMode
xrandr --addmode "$screen" "$modeName"
xrandr --size "${newSize[0]}x${newSize[1]}" &&
return 0
else
echo "Unable to parse modeline for ($x $y) from $mode"
return 2
fi
else
echo "\`$x $y' is not a valid X Y pair"
return 1
fi
}
Create two js files
// File cal.js
module.exports = {
sum: function(a,b) {
return a+b
},
multiply: function(a,b) {
return a*b
}
};
Main js file
// File app.js
var tools = require("./cal.js");
var value = tools.sum(10,20);
console.log("Value: "+value);
Console Output
Value: 30
Using VueJS I tried every method in this question but none worked. So in case somebody is struggling whit the same:
mounted() {
$(document).ready(function() { //<<====== wont work without this
$(window).scroll(function() {
console.log('logging');
});
});
},
int code = 2;
Environment.Exit( code );
Since C++17 you can also use the standardized free function:
std::size(container)
which will return the amount of elements in that container.
example:
std::vector<int> vec = { 1, 2, 3, 4, 8 };
std::cout << std::size(vec) << "\n\n"; // 5
int A[] = {40,10,20};
std::cout << std::size(A) << '\n'; // 3
Another method is to define an exception and then only catch that exception letting all others propagate.
Declare
eTableDoesNotExist Exception;
PRAGMA EXCEPTION_INIT(eTableDoesNotExist, -942);
Begin
EXECUTE IMMEDIATE ('DROP TABLE myschema.mytable');
Exception
When eTableDoesNotExist Then
DBMS_Output.Put_Line('Table already does not exist.');
End;
I encountered the same problem.
What caused it for me were a bunch of whitespaces (
) that I inserted.
After removing them, the problem was solved.
I got the same problem trying to use the python manage.py runserver. In my case I just use sudo su. Use the terminal as a root and try it again an it works partially. So I use python manage.py migrate comand and it fix it.
It is a new signing mechanism introduced in Android 7.0, with additional features designed to make the APK signature more secure.
It is not mandatory. You should check BOTH of those checkboxes if possible, but if the new V2 signing mechanism gives you problems, you can omit it.
So you can just leave V2 unchecked if you encounter problems, but should have it checked if possible.
UPDATED: This is now mandatory when targeting Android 11.
You have two possibilities:
org.springframework.beans.factory.config.MethodInvokingFactoryBean
to invoke a static setter.In the first option you have a bean with a regular setter but instead setting an instance property you set the static property/field.
public void setTheProperty(Object value) {
foo.bar.Class.STATIC_VALUE = value;
}
but in order to do this you need to have an instance of a bean that will expose this setter (its more like an workaround).
In the second case it would be done as follows:
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="staticMethod" value="foo.bar.Class.setTheProperty"/> <property name="arguments"> <list> <ref bean="theProperty"/> </list> </property> </bean>
On you case you will add a new setter on the Utils
class:
public static setDataBaseAttr(Properties p)
and in your context you will configure it with the approach exemplified above, more or less like:
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="staticMethod" value="foo.bar.Utils.setDataBaseAttr"/> <property name="arguments"> <list> <ref bean="dataBaseAttr"/> </list> </property> </bean>
With set of static imports, Guava solution can be very compact one-liner:
toString(getResource("foo.txt"), UTF_8);
The following imports are required:
import static com.google.common.io.Resources.getResource
import static com.google.common.io.Resources.toString
import static java.nio.charset.StandardCharsets.UTF_8
In your selector you seem to be attempting to fetch some nested element of your radio button with a given id. If you want to check a radio button, you should select this radio button in the selector and not something else:
$('input:radio[name="cols"]').attr('checked', 'checked');
This assumes that you have the following radio button in your markup:
<input type="radio" name="cols" value="1" />
If your radio button had an id:
<input type="radio" name="cols" value="1" id="myradio" />
you could directly use an id selector:
$('#myradio').attr('checked', 'checked');
Anywhere between your <body>
and </body>
tags, put in a button using the below code:
<button>
<a href="file.doc" download>Click to Download!</a>
</button>
This is sure to work!
You should never assume register_global_variables
is turned on. Even if it is, it's deprecated and you should never use it that way.
Refer directly to the $_POST
or $_GET
variables. Most likely your form is POSTing, so you'd want your code to look something along the lines of this:
<input type="hidden" name="date" id="hiddenField" value="<?php echo $_POST['date'] ?>" />
If this doesn't work for you right away, print out the $_POST
or $_GET
variable on the page that would have the hidden form field and determine exactly what you want and refer to it.
echo "<pre>";
print_r($_POST);
echo "</pre>";
C++11 has another (imperfect) option:
std::array<int, 100> a;
a.fill(-1);
Try the jEscape plugin (download from google drive)
$(document).escape(function() {
alert('ESC button pressed');
});
or get keycode for cross browser
var code = (e.keyCode ? e.keyCode : e.which);
if (code === 27) alert('ESC');
if (code === 13) alert('ENTER');
maybe you can use switch
var code = (e.keyCode ? e.keyCode : e.which);
switch (code) {
case 27:
alert('ESC');
break;
case 13:
alert('ENTER');
break;
}
function getKeys(obj){
var keys = [];
for (key in obj) {
if (obj.hasOwnProperty(key)) { keys[keys.length] = key; }
}
return keys;
}
You need to
using System.Linq;
to use IEnumerable
options at your List
.
You cannot use PuTTY to download the files, but you can use PSCP from the PuTTY developers to get the files or dump any directory that you want.
Please see the following link on how to download a file/folder: https://the.earth.li/~sgtatham/putty/0.60/htmldoc/Chapter5.html
string shortDate = dateTimePicker1.Value.ToShortDateString();
.shape() gives the actual shape of your array in terms of no of elements in it, No of rows/No of Columns. The answer you get is in the form of tuples.
For Example: 1D ARRAY:
d=np.array([1,2,3,4])
print(d)
(1,)
Output: (4,) ie the number4 denotes the no of elements in the 1D Array.
2D Array:
e=np.array([[1,2,3],[4,5,6]])
print(e)
(2,3)
Output: (2,3) ie the number of rows and the number of columns.
The number of elements in the final output will depend on the number of rows in the Array....it goes on increasing gradually.
As others have mentioned in this and other similar threads, the best way to avoid this problem is to use RGBA/HSLA or else use a transparent PNG.
But, if you want a ridiculous solution, similar to the one linked in another answer in this thread (which is also my website), here's a brand new script I wrote that fixes this problem automatically, called thatsNotYoChild.js:
http://www.impressivewebs.com/fixing-parent-child-opacity/
Basically it uses JavaScript to remove all children from the parent div, then reposition the child elements back to where they should be without actually being children of that element anymore.
To me, this should be a last resort, but I thought it would be fun to write something that did this, if anyone wants to do this.
My Comments:
When I see the output, the output is mixed with One, Two, Three which are the thread names and they run simultaneously. I am not sure when you say thread is not running by main method.
Not sure if I understood your question or not. But I m putting my answer what I could understand, hope it can help you.
1) Then you created the object, it called the constructor, in construct it has start method which started the thread and executed the contents written inside run() method.
So as you created 3 objects (3 threads - one, two, three), all 3 threads started executing simultaneously.
2) Join and Synchronization They are 2 different things, Synchronization is when there are multiple threads sharing a common resource and one thread should use that resource at a time. E.g. Threads such as DepositThread, WithdrawThread etc. do share a common object as BankObject. So while DepositThread is running, the WithdrawThread will wait if they are synchronized. wait(), notify(), notifyAll() are used for inter-thread communication. Plz google to know more.
about Join(), it is when multiple threads are running, but you join. e.g. if there are two thread t1 and t2 and in multi-thread env they run, the output would be: t1-0 t2-0 t1-1 t2-1 t1-2 t2-2
and we use t1.join(), it would be: t1-0 t1-1 t1-2 t2-0 t2-1 t2-2
This is used in realtime when sometimes you don't mix up the thread in certain conditions and one depends another to be completed (not in shared resource), so you can call the join() method.
They are:
With REGEXP_SUBSTR is as simple as:
SELECT REGEXP_SUBSTR(t.column_one, '[^ ]+', 1, 1) col_one,
REGEXP_SUBSTR(t.column_one, '[^ ]+', 1, 2) col_two
FROM YOUR_TABLE t;
I like this tool, called simply DbSchema. It's written in Java so it runs on OS X, Windows, or Linux. It's a little clunky, especially when it comes to printing, but from my experience they're all like that. This one is the best of the several I've tried. It makes nice, clear diagrams. Free trial. Costs about $120 depending on how many licenses you buy.
Put your assets in the public folder
public/css
public/images
public/fonts
public/js
And them called it using Laravel
{{ HTML::script('js/scrollTo.js'); }}
{{ HTML::style('css/css.css'); }}
It is working fine with me.
I have the following HTML:
<div>
<select id="select1">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
<br/>
<button onClick="GetSelectedItem('select1');">Get Selected Item</button>
</div>
And the following JavaScript:
function GetSelectedItem(el)
{
var e = document.getElementById(el);
var strSel = "The Value is: " + e.options[e.selectedIndex].value + " and text is: " + e.options[e.selectedIndex].text;
alert(strSel);
}
See that you are using the right id. In case you are using it with ASP.NET, the id changes when rendered.
I solved this problem by making sure that the value of JAVA_HOME was the folder location in English
C:\Program Files\Java\jdk1.8.0_31
rather than the folder location that one can see/explorer browse in my Windows7 - Portuguese installation
C:\Programas\Java\jdk1.8.0_31
You can filter using where
Job.includes(:attachments).where(file_type: ["logo", "image"])
This is an old post, but I thought I would add another method to do this:
var win = window.open("http://www.google.com");
var winClosed = setInterval(function () {
if (win.closed) {
clearInterval(winClosed);
foo(); //Call your function here
}
}, 250);
You don't have to modify the contents or use any event handlers from the child window.