Thanks All, I found how to do it, which is the same as Dave and Sergey:
I am using QT Creator:
In the main GUI window create using the drag drop GUI and create label (e.g. "myLabel")
In the callback of the button (clicked) do the following using the (*ui) pointer to the user interface window:
void MainWindow::on_pushButton_clicked()
{
QImage imageObject;
imageObject.load(imagePath);
ui->myLabel->setPixmap(QPixmap::fromImage(imageObject));
//OR use the other way by setting the Pixmap directly
QPixmap pixmapObject(imagePath");
ui->myLabel2->setPixmap(pixmapObject);
}
The answer that works on Ubuntu18, python3, opencv 3.2.0 is similar to the one above. But with the change in line cv2.waitKey(0)
. that means the program waits until a button is pressed.
With this code I found the key value for the arrow buttons: arrow up (82), down (84), arrow left(81) and Enter(10) and etc..
import cv2
img = cv2.imread('sof.jpg') # load a dummy image
while(1):
cv2.imshow('img',img)
k = cv2.waitKey(0)
if k==27: # Esc key to stop
break
elif k==-1: # normally -1 returned,so don't print it
continue
else:
print k # else print its value
The code is very long so I can't paste all the code.
There could be any number of reasons why your code doesn't work. Maybe you declared the button variables twice so you aren't actually changing enabling/disabling the button like you think you are. Maybe you are blocking the EDT.
You need to create a SSCCE to post on the forum.
So its up to you to isolate the problem. Start with a simple frame thas two buttons and see if your code works. Once you get that working, then try starting a Thread that simply sleeps for 10 seconds to see if it still works.
Learn how the basice work first before writing a 200 line program.
Learn how to do some basic debugging, we are not mind readers. We can't guess what silly mistake you are doing based on your verbal description of the problem.
Do not use CDATA in HTML4 but you should use CDATA in XHTML and must use CDATA in XML if you have unescaped symbols like < and >.
The PHP manual explains both quite well:
http://php.net/manual/en/reserved.variables.server.php # REQUEST_URI
http://php.net/manual/en/reserved.variables.get.php # for the $_GET["q"] variable
Use the glide library. It worked for me and will work for your code too.It works for both images as well as gifs too.
ImageView imageView = (ImageView) findViewById(R.id.test_image);
GlideDrawableImageViewTarget imagePreview = new GlideDrawableImageViewTarget(imageView);
Glide
.with(this)
.load(url)
.listener(new RequestListener<String, GlideDrawable>() {
@Override
public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
return false;
}
@Override
public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
return false;
}
})
.into(imagePreview);
}
If the goal is to create a grid with equal height rows, where the tallest cell in the grid sets the height for all rows, here's a quick and simple solution:
grid-auto-rows: 1fr
Grid Layout provides a unit for establishing flexible lengths in a grid container. This is the fr
unit. It is designed to distribute free space in the container and is somewhat analogous to the flex-grow
property in flexbox.
If you set all rows in a grid container to 1fr
, let's say like this:
grid-auto-rows: 1fr;
... then all rows will be equal height.
It doesn't really make sense off-the-bat because fr
is supposed to distribute free space. And if several rows have content with different heights, then when the space is distributed, some rows would be proportionally smaller and taller.
Except, buried deep in the grid spec is this little nugget:
7.2.3. Flexible Lengths: the
fr
unit...
When the available space is infinite (which happens when the grid container’s width or height is indefinite), flex-sized (
fr
) grid tracks are sized to their contents while retaining their respective proportions.The used size of each flex-sized grid track is computed by determining the
max-content
size of each flex-sized grid track and dividing that size by the respective flex factor to determine a “hypothetical1fr
size”.The maximum of those is used as the resolved
1fr
length (the flex fraction), which is then multiplied by each grid track’s flex factor to determine its final size.
So, if I'm reading this correctly, when dealing with a dynamically-sized grid (e.g., the height is indefinite), grid tracks (rows, in this case) are sized to their contents.
The height of each row is determined by the tallest (max-content
) grid item.
The maximum height of those rows becomes the length of 1fr
.
That's how 1fr
creates equal height rows in a grid container.
As noted in the question, equal height rows are not possible with flexbox.
Flex items can be equal height on the same row, but not across multiple rows.
This behavior is defined in the flexbox spec:
In a multi-line flex container, the cross size of each line is the minimum size necessary to contain the flex items on the line.
In other words, when there are multiple lines in a row-based flex container, the height of each line (the "cross size") is the minimum height necessary to contain the flex items on the line.
The fetchType attribute controls whether the annotated field is fetched immediately when the primary entity is fetched. It does not necessarily dictate how the fetch statement is constructed, the actual sql implementation depends on the provider you are using toplink/hibernate etc.
If you set fetchType=EAGER
This means that the annotated field is populated with its values at the same time as the other fields in the entity. So if you open an entitymanager retrieve your person objects and then close the entitymanager, subsequently doing a person.address will not result in a lazy load exception being thrown.
If you set fetchType=LAZY
the field is only populated when it is accessed. If you have closed the entitymanager by then a lazy load exception will be thrown if you do a person.address. To load the field you need to put the entity back into an entitymangers context with em.merge(), then do the field access and then close the entitymanager.
You might want lazy loading when constructing a customer class with a collection for customer orders. If you retrieved every order for a customer when you wanted to get a customer list this may be a expensive database operation when you only looking for customer name and contact details. Best to leave the db access till later.
For the second part of the question - how to get hibernate to generate optimised SQL?
Hibernate should allow you to provide hints as to how to construct the most efficient query but I suspect there is something wrong with your table construction. Is the relationship established in the tables? Hibernate may have decided that a simple query will be quicker than a join especially if indexes etc are missing.
If you want to execute your Python script in PHP, it's necessary to do this command in your php script:
exec('your script python.py')
The answer from niaher stating that to use the fluent API you need a custom extension may have been correct at the time of writing. You can now (EF core 2.1) use the fluent API as follows:
modelBuilder.Entity<ClassName>()
.HasIndex(a => new { a.Column1, a.Column2}).IsUnique();
let urlString = "http://heyhttp.org/me.json"
var request = URLRequest(url: URL(string: urlString)!)
let session = URLSession.shared
session.dataTask(with: request) {data, response, error in
if error != nil {
print(error!.localizedDescription)
return
}
do {
let jsonResult: NSDictionary? = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
print("Synchronous\(jsonResult)")
} catch {
print(error.localizedDescription)
}
}.resume()
I just grabbed the junit-4.xsd that others have linked to and used a tool named XMLSpear to convert the schema to a blank XML file with the options shown below. This is the (slightly cleaned up) result:
<?xml version="1.0" encoding="UTF-8"?>
<testsuites disabled="" errors="" failures="" name="" tests="" time="">
<testsuite disabled="" errors="" failures="" hostname="" id=""
name="" package="" skipped="" tests="" time="" timestamp="">
<properties>
<property name="" value=""/>
</properties>
<testcase assertions="" classname="" name="" status="" time="">
<skipped/>
<error message="" type=""/>
<failure message="" type=""/>
<system-out/>
<system-err/>
</testcase>
<system-out/>
<system-err/>
</testsuite>
</testsuites>
Some of these items can occur multiple times:
testsuites
element, since that’s how XML works, but there can be multiple testsuite
elements within the testsuites
element.properties
element can have multiple property
children.testsuite
element can have multiple testcase
children.testcase
element can have multiple error
, failure
, system-out
, or system-err
children.Under linux, the simpler is:
find
to do a recursive search of *.java files wc -l
to count lines:To resume, just do:
find . -name '*.java' | xargs wc -l
Another reference:
If you are using the maven-jaxb2-plugin
, prior to version 0.9.0, you can use the workaround described on this issue, in which this behaviour affected the plugin.
As others have said, you can/should prepend the string with @
(though you could also just escape the backslashes), but what they glossed over (that is, didn't bring it up despite making a change related to it) was the fact that, as I recently discovered, using \
at the beginning of a pathname, without .
to represent the current directory, refers to the root of the current directory tree.
C:\foo\bar>cd \
C:\>
versus
C:\foo\bar>cd .\
C:\foo\bar>
(Using .
by itself has the same effect as using .\
by itself, from my experience. I don't know if there are any specific cases where they somehow would not mean the same thing.)
You could also just leave off the leading .\
, if you want.
C:\foo>cd bar
C:\foo\bar>
In fact, if you really wanted to, you don't even need to use backslashes. Forwardslashes work perfectly well! (Though a single /
doesn't alias to the current drive root as \
does.)
C:\>cd foo/bar
C:\foo\bar>
You could even alternate them.
C:\>cd foo/bar\baz
C:\foo\bar\baz>
...I've really gone off-topic here, though, so feel free to ignore all this if you aren't interested.
The Angular2 team published a tutorial for using Webpack
I created and placed the files from the tutorial in a small GitHub seed project. So you can quickly try the workflow.
Instructions:
npm install
npm start. For development. This will create a virtual "dist" folder that will be livereloaded at your localhost address.
npm run build. For production. "This will create a physical "dist" folder version than can be sent to a webserver. The dist folder is 7.8MB but only 234KB is actually required to load the page in a web browser.
This Webpack Starter Kit offers some more testing features than the above tutorial and seem quite popular.
NULL
isn't a keyword; it's a macro substitution for 0, and comes in stddef.h
or cstddef
, I believe. You haven't #included
an appropriate header file, so g++ sees NULL
as a regular variable name, and you haven't declared it.
It is now possible to achieve that in Flutter 1.5 and Dart 2.3 by using a for element in your collection.
var list = ["one", "two", "three", "four"];
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
for(var item in list ) Text(item)
],
),
This will display four Text widgets containing the items in the list.
NB. No braces around the for loop and no return keyword.
it is working perfectly by only using html
<p><a href="#"onclick="window.open('http://google.com');window.open('http://yahoo.com');">Click to open Google and Yahoo</a></p>
Best of both worlds [@DiddiZ, @Chalkos]: this one mainly builds upon @Chalkos method, but fixes a bug (ifst.next()), and improves initial checks (taken from @DiddiZ) as well as removes the need to copy the first collection (just removes items from a copy of the second collection).
Not requiring a hashing function or sorting, and enabling an early exist on un-equality, this is the most efficient implementation yet. That is unless you have a collection length in the thousands or more, and a very simple hashing function.
public static <T> boolean isCollectionMatch(Collection<T> one, Collection<T> two) {
if (one == two)
return true;
// If either list is null, return whether the other is empty
if (one == null)
return two.isEmpty();
if (two == null)
return one.isEmpty();
// If lengths are not equal, they can't possibly match
if (one.size() != two.size())
return false;
// copy the second list, so it can be modified
final List<T> ctwo = new ArrayList<>(two);
for (T itm : one) {
Iterator<T> it = ctwo.iterator();
boolean gotEq = false;
while (it.hasNext()) {
if (itm.equals(it.next())) {
it.remove();
gotEq = true;
break;
}
}
if (!gotEq) return false;
}
// All elements in one were found in two, and they're the same size.
return true;
}
--
-- STORED PROCEDURE
-- Name of stored procedure.
--
-- DESCRIPTION
-- Business description of the stored procedure's functionality.
--
-- PARAMETERS
-- @InputParameter1
-- * Description of @InputParameter1 and how it is used.
--
-- RETURN VALUE
-- 0 - No Error.
-- -1000 - Description of cause of non-zero return value.
--
-- PROGRAMMING NOTES
-- Gotchas and other notes for your fellow programmer.
--
-- CHANGE HISTORY
-- 05 May 2009 - Who
-- * More comprehensive description of the change than that included with the
-- source code commit message.
--
Sharding does more than just horizontal partitioning. According to the wikipedia article,
Horizontal partitioning splits one or more tables by row, usually within a single instance of a schema and a database server. It may offer an advantage by reducing index size (and thus search effort) provided that there is some obvious, robust, implicit way to identify in which partition a particular row will be found, without first needing to search the index, e.g., the classic example of the 'CustomersEast' and 'CustomersWest' tables, where their zip code already indicates where they will be found.
Sharding goes beyond this: it partitions the problematic table(s) in the same way, but it does this across potentially multiple instances of the schema. The obvious advantage would be that search load for the large partitioned table can now be split across multiple servers (logical or physical), not just multiple indexes on the same logical server.
Also,
Splitting shards across multiple isolated instances requires more than simple horizontal partitioning. The hoped-for gains in efficiency would be lost, if querying the database required both instances to be queried, just to retrieve a simple dimension table. Beyond partitioning, sharding thus splits large partitionable tables across the servers, while smaller tables are replicated as complete units
You can set a default value, e.g. for the form message
, like this:
$defaultData = array('message' => 'Type your message here');
$form = $this->createFormBuilder($defaultData)
->add('name', 'text')
->add('email', 'email')
->add('message', 'textarea')
->add('send', 'submit')
->getForm();
In case your form is mapped to an Entity, you can go like this (e.g. default username):
$user = new User();
$user->setUsername('John Doe');
$form = $this->createFormBuilder($user)
->add('username')
->getForm();
if (condition){ // where condition evaluates to true
return false
}
see similar question asked 3 days ago.
My solution is to set the environment variable as spring.profiles.active=development
. So that all applications running in that machine will refer the variable and start the application. The order in which spring loads a properties as follows
application.properties
system properties
environment variable
When you set null=true
it will set null
in your database if the field is not filled. If
you set blank='true
it will not set any value to the field.
The first problem is, that you are trying to return an incorrect value at the end of the main function. C++ standard dictates that the return type of main() is int, but instead you are trying to return the empty set.
The other problem is - at least with g++ - that the compiler deduces the language used from the file suffix. From g++(1):
For any given input file, the file name suffix determines what kind of compilation is done:
file.cc file.cp file.cxx file.cpp file.CPP file.c++ file.C
C ++ source code which must be preprocessed. Note that in .cxx, the last two letters must both be literally x. Likewise, .C refers to a literal capital C.
Fixing these should leave you with a fully working Hello World application, as can be seen from the demo here.
To specify the coordinates within the SVG image independently of the scaled size of the image, use the viewBox
attribute on the SVG element to define what the bounding box of the image is in the coordinate system of the image, and use the width
and height
attributes to define what the width or height are with respect to the containing page.
For instance, if you have the following:
<svg>
<polygon fill=red stroke-width=0
points="0,10 20,10 10,0" />
</svg>
It will render as a 10px by 20px triangle:
Now, if you set only the width and height, that will change the size of the SVG element, but not scale the triangle:
<svg width=100 height=50>
<polygon fill=red stroke-width=0
points="0,10 20,10 10,0" />
</svg>
If you set the view box, that causes it to transform the image such that the given box (in the coordinate system of the image) is scaled up to fit within the given width and height (in the coordinate system of the page). For instance, to scale up the triangle to be 100px by 50px:
<svg width=100 height=50 viewBox="0 0 20 10">
<polygon fill=red stroke-width=0
points="0,10 20,10 10,0" />
</svg>
If you want to scale it up to the width of the HTML viewport:
<svg width="100%" viewBox="0 0 20 10">
<polygon fill=red stroke-width=0
points="0,10 20,10 10,0" />
</svg>
Note that by default, the aspect ratio is preserved. So if you specify that the element should have a width of 100%, but a height of 50px, it will actually only scale up to the height of 50px (unless you have a very narrow window):
<svg width="100%" height="50px" viewBox="0 0 20 10">
<polygon fill=red stroke-width=0
points="0,10 20,10 10,0" />
</svg>
If you actually want it to stretch horizontally, disable aspect ratio preservation with preserveAspectRatio=none
:
<svg width="100%" height="50px" viewBox="0 0 20 10" preserveAspectRatio="none">
<polygon fill=red stroke-width=0
points="0,10 20,10 10,0" />
</svg>
(note that while in my examples I use syntax that works for HTML embedding, to include the examples as an image in StackOverflow I am instead embedding within another SVG, so I need to use valid XML syntax)
Polymorphism is a multiple implementations of an object or you could say multiple forms of an object. lets say you have class Animals
as the abstract base class and it has a method called movement()
which defines the way that the animal moves. Now in reality we have different kinds of animals and they move differently as well some of them with 2 legs, others with 4 and some with no legs, etc.. To define different movement()
of each animal on earth, we need to apply polymorphism. However, you need to define more classes i.e. class Dogs
Cats
Fish
etc. Then you need to extend those classes from the base class Animals
and override its method movement()
with a new movement functionality based on each animal you have. You can also use Interfaces
to achieve that. The keyword in here is overriding, overloading is different and is not considered as polymorphism. with overloading you can define multiple methods "with same name" but with different parameters on same object or class.
I'd like to suggest an amendment to Zach/RegularMike's answer (but don't have the "reputation" to be able to comment!). I found there solution a very useful basis, but suffered in my application because if there are strings within arrays it would recursively call the function for every character in the string (which caused IE11 & Edge browsers to fail with "out of stack space" errors). My simple optimization was to add the same test used in the "object" clause recursive call to the one in the "array" clause:
if (arrayElem instanceof Object || arrayElem instanceof Array) {
Thus my full code (which is now looking for all instances of a particular key, so slightly different to the original requirement) is:
// Get all instances of specified property deep within supplied object
function getPropsInObject(theObject, targetProp) {
var result = [];
if (theObject instanceof Array) {
for (var i = 0; i < theObject.length; i++) {
var arrayElem = theObject[i];
if (arrayElem instanceof Object || arrayElem instanceof Array) {
result = result.concat(getPropsInObject(arrayElem, targetProp));
}
}
} else {
for (var prop in theObject) {
var objProp = theObject[prop];
if (prop == targetProp) {
return theObject[prop];
}
if (objProp instanceof Object || objProp instanceof Array) {
result = result.concat(getPropsInObject(objProp, targetProp));
}
}
}
return result;
}
The previous answers are all doing more work than they need to. Just use array_diff. This is the simplest way to do it:
$containsAllValues = !array_diff($search_this, $all);
That's all you have to do.
a>b
:def gcd(a, b):
if(a<b):
a,b=b,a
while(b!=0):
r,b=b,a%r
a=r
return a
a>b
or a<b
:def gcd(a, b):
t = min(a, b)
# Keep looping until t divides both a & b evenly
while a % t != 0 or b % t != 0:
t -= 1
return t
Cast the datetime to a date, then GROUP BY using this syntax:
SELECT SUM(foo), DATE(mydate) FROM a_table GROUP BY DATE(a_table.mydate);
Or you can GROUP BY the alias as @orlandu63 suggested:
SELECT SUM(foo), DATE(mydate) DateOnly FROM a_table GROUP BY DateOnly;
Though I don't think it'll make any difference to performance, it is a little clearer.
After testing all workarounds, i suggest you to take a look at Settings -> Project -> project dependencies
and re-arrange them.
The most common idiom to create a two-dimensional array with 5 rows and 10 columns is:
int[][] multD = new int[5][10];
Alternatively, you could use the following, which is more similar to what you have, though you need to explicitly initialize each row:
int[][] multD = new int[5][];
for (int i = 0; i < 5; i++) {
multD[i] = new int[10];
}
There are two possible approaches; either you create a unique value and store somewhere along with the creation time, for example in a database, or you put the creation time inside the token so that you can decode it later and see when it was created.
To create a unique token:
string token = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
Basic example of creating a unique token containing a time stamp:
byte[] time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
byte[] key = Guid.NewGuid().ToByteArray();
string token = Convert.ToBase64String(time.Concat(key).ToArray());
To decode the token to get the creation time:
byte[] data = Convert.FromBase64String(token);
DateTime when = DateTime.FromBinary(BitConverter.ToInt64(data, 0));
if (when < DateTime.UtcNow.AddHours(-24)) {
// too old
}
Note: If you need the token with the time stamp to be secure, you need to encrypt it. Otherwise a user could figure out what it contains and create a false token.
I keep running into this issue when I destroy my Laravel Homestead (Vagrant) box and start fresh.
SSH into the box from the command line homestead ssh
Go to the my.cnf file sudo vi /etc/mysql/my.cnf
Add the below lines to the bottom of the file (below the !includedir)
[mysqld]
innodb_log_file_size=512M
innodb_strict_mode=0
Save the changes to my.cnf, then reload MYSQL sudo service mysql restart
Do something like this:
A <div>
with ID of #imageDIV
, another one with ID #download
and a hidden <div>
with ID #previewImage
.
Include the latest version of jquery, and jspdf.debug.js from the jspdf CDN
Then add this script:
var element = $("#imageDIV"); // global variable
var getCanvas; // global variable
$('document').ready(function(){
html2canvas(element, {
onrendered: function (canvas) {
$("#previewImage").append(canvas);
getCanvas = canvas;
}
});
});
$("#download").on('click', function () {
var imgageData = getCanvas.toDataURL("image/png");
// Now browser starts downloading it instead of just showing it
var newData = imageData.replace(/^data:image\/png/, "data:application/octet-stream");
$("#download").attr("download", "image.png").attr("href", newData);
});
The div will be saved as a PNG on clicking the #download
This is probably what you need:
$text = str_replace(' ', '_', substr($text, 0, 10));
<LinearLayout
android:id="@+id/linear1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="9"
android:orientation="horizontal" >
<ImageView
android:id="@+id/ring_oss"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:src="@drawable/ring_oss" />
<ImageView
android:id="@+id/maila_oss"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:src="@drawable/maila_oss" />
<EditText
android:id="@+id/edittxt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:src="@drawable/maila_oss" />
</LinearLayout>
/lkjasdf
has always been faster than :noh
for me.
MySQL's maximum memory usage very much depends on hardware, your settings and the database itself.
The hardware is the obvious part. The more RAM the merrier, faster disks ftw. Don't believe those monthly or weekly news letters though. MySQL doesn't scale linear - not even on Oracle hardware. It's a little trickier than that.
The bottom line is: there is no general rule of thumb for what is recommend for your MySQL setup. It all depends on the current usage or the projections.
MySQL offers countless variables and switches to optimize its behavior. If you run into issues, you really need to sit down and read the (f'ing) manual.
As for the database -- a few important constraints:
InnoDB
, MyISAM
, ...)Most MySQL tips on stackoverflow will tell you about 5-8 so called important settings. First off, not all of them matter - e.g. allocating a lot of resources to InnoDB and not using InnoDB doesn't make a lot of sense because those resources are wasted.
Or - a lot of people suggest to up the max_connection
variable -- well, little do they know it also implies that MySQL will allocate more resources to cater those max_connections
-- if ever needed. The more obvious solution might be to close the database connection in your DBAL or to lower the wait_timeout
to free those threads.
If you catch my drift -- there's really a lot, lot to read up on and learn.
Table engines are a pretty important decision, many people forget about those early on and then suddenly find themselves fighting with a 30 GB sized MyISAM
table which locks up and blocks their entire application.
I don't mean to say MyISAM sucks, but InnoDB
can be tweaked to respond almost or nearly as fast as MyISAM
and offers such thing as row-locking on UPDATE
whereas MyISAM
locks the entire table when it is written to.
If you're at liberty to run MySQL on your own infrastructure, you might also want to check out the percona server because among including a lot of contributions from companies like Facebook and Google (they know fast), it also includes Percona's own drop-in replacement for InnoDB
, called XtraDB
.
See my gist for percona-server (and -client) setup (on Ubuntu): http://gist.github.com/637669
Database size is very, very important -- believe it or not, most people on the Intarwebs have never handled a large and write intense MySQL setup but those do really exist. Some people will troll and say something like, "Use PostgreSQL!!!111", but let's ignore them for now.
The bottom line is: judging from the size, decision about the hardware are to be made. You can't really make a 80 GB database run fast on 1 GB of RAM.
It's not: the more, the merrier. Only indices needed are to be set and usage has to be checked with EXPLAIN
. Add to that that MySQL's EXPLAIN
is really limited, but it's a start.
About these my-large.cnf
and my-medium.cnf
files -- I don't even know who those were written for. Roll your own.
A great start is the tuning primer. It's a bash script (hint: you'll need linux) which takes the output of SHOW VARIABLES
and SHOW STATUS
and wraps it into hopefully useful recommendation. If your server has ran some time, the recommendation will be better since there will be data to base them on.
The tuning primer is not a magic sauce though. You should still read up on all the variables it suggests to change.
I really like to recommend the mysqlperformanceblog. It's a great resource for all kinds of MySQL-related tips. And it's not just MySQL, they also know a lot about the right hardware or recommend setups for AWS, etc.. These guys have years and years of experience.
Another great resource is planet-mysql, of course.
I don't recommend changing apaches port itself, because it will need you remember changed port. Its also headache to tell your co-developers about port change.
Go to windows features(By searching turn on or off windows features) -> Find Internet information services(IIS) and uncheck if it checked. Please make a note when you disable it FTP server/ client will not work.(incase you are using it, change httpd.conf as giovannipds 's answer) -> If still port is not free, then change skype port through skype settings.
There is no such thing as :touch
in the W3C specifications, http://www.w3.org/TR/CSS2/selector.html#pseudo-class-selectors
:active
should work, I would think.
Order on the :active
/:hover
pseudo class is important for it to function correctly.
Here is a quote from that above link
Interactive user agents sometimes change the rendering in response to user actions. CSS provides three pseudo-classes for common cases:
- The :hover pseudo-class applies while the user designates an element (with some pointing device), but does not activate it. For example, a visual user agent could apply this pseudo-class when the cursor (mouse pointer) hovers over a box generated by the element. User agents not supporting interactive media do not have to support this pseudo-class. Some conforming user agents supporting interactive media may not be able to support this pseudo-class (e.g., a pen device).
- The :active pseudo-class applies while an element is being activated by the user. For example, between the times the user presses the mouse button and releases it.
- The :focus pseudo-class applies while an element has the focus (accepts keyboard events or other forms of text input).
You forgot to add a position property to the .dummy-wrap
class, and the top/left/bottom/right values don't apply to statically positioned elements (the default)
I've experimented with typing "exit for" a few times and noticed it worked and VB didn't yell at me. It's an option I guess but it just looked bad.
I think the best option is similar to that shared by Tobias. Just put your code in a function and have it return when you want to break out of your loops. Looks cleaner too.
For Each item In itemlist
For Each item1 In itemlist1
If item1 = item Then
Return item1
End If
Next
Next
As the documentation clearly states, Character.getNumericValue()
returns the character's value as a digit.
It returns -1
if the character is not a digit.
If you want to get the numeric Unicode code point of a boxed Character
object, you'll need to unbox it first:
int value = (int)c.charValue();
The parameter tomcat.util.http.parser.HttpParser.requestTargetAllow
is deprecated since Tomcat 8.5: tomcat official doc.
You can use relaxedQueryChars / relaxedPathChars
in the connectors definition to allow these chars: tomcat official doc.
I'd use months_between
, possibly combined with floor
:
select floor(months_between(date '2012-10-10', date '2011-10-10') /12) from dual;
select floor(months_between(date '2012-10-9' , date '2011-10-10') /12) from dual;
floor
makes sure you get down-rounded years. If you want the fractional parts, you obviously want to not use floor
.
If you still want to show the item but make it not clickable and look disabled with CSS:
CSS:
.disabled {
pointer-events:none; //This makes it not clickable
opacity:0.6; //This grays it out to look disabled
}
HTML:
<li class="disabled">Disabled List Item</li>
Also, if you are using BootStrap, they already have a class called disabled for this purpose. See this example.
As @LV98 pointed out, users could change this on the client side and submit a selection you weren't expecting. You will want to validate at the server as well.
control-shift-L should open the log(s) for you. this will by default be the messages log, but if you create the item that is creating the error the Compiler Log will show up (for me the box shows up in the bottom middle left).
if the messages log is the only log that shows up, simply re-execute the item that was causing the failure and the compiler log will show up
for instance, hit Control-shift-L then execute this
CREATE OR REPLACE FUNCTION TEST123() IS
BEGIN
VAR := 2;
end TEST123;
and you will see the message "Error(1,18): PLS-00103: Encountered the symbol ")" when expecting one of the following: current delete exists prior "
(You can also see this in "View--Log")
One more thing, if you are having a problem with a (function || package || procedure) if you do the coding via the SQL Developer interface (by finding the object in question on the connections tab and editing it the error will be immediately displayed (and even underlined at times)
This exception could point to the LINQ parameter that is named source:
System.Linq.Enumerable.Select[TSource,TResult](IEnumerable`1 source, Func`2 selector)
As the source
parameter in your LINQ
query (var nCounts = from sale in sal
) is 'sal
', I suppose the list named 'sal' might be null.
CopyOnWriteArrayList
Use CopyOnWriteArrayList
class. This is the thread safe version of ArrayList
.
You could try running a script as follows
var WindowStyle_Hidden = 0
var objShell = WScript.CreateObject("WScript.Shell")
var result = objShell.Run("cmd.exe /c setrbvars.bat", WindowStyle_Hidden)
save the file as filename.js
Package organization or package structuring is usually a heated discussion. Below are some simple guidelines for package naming and structuring:
com.company.product.modulea
com.company.product.module.web
or com.company.product.module.util
etc.com.company.product.model
and com.company.product.util
, etc.After a few experiments and trials you should be able to come up with a structuring that you are comfortable with. Don't be fixated on one convention, be open to changes.
Very simple: no color, no opacity:
rgba(0, 0, 0, 0);
OnRequestPermissionResult-free and shouldShowRequestPermissionRationale-free method:
public static void requestDangerousPermission(AppCompatActivity activity, String permission) {
if (hasPermission(activity, permission)) return;
requestPermission();
new Handler().postDelayed(() -> {
if (activity.getLifecycle().getCurrentState() == Lifecycle.State.RESUMED) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + context.getPackageName()));
context.startActivity(intent);
}
}, 250);
}
Opens device settings after 250ms if no permission popup happened (which is the case if 'Never ask again' was selected.
My SetUp:
Spring Boot v1.5.10
Hikari v.3.2.x (for evaluation)
To really understand the configuration of Hikari Data Source, I recommend to disable Spring Boot's Auto-Configuration for Data Source.
Add following to application.properties:-
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
This will disable Spring Boot's capability to configure the DataSource on its own.
Now is the chance for you to define your own Custom Configuration to create HikariDataSource bean and populate it with the desired properties.
NOTE :::
public class HikariDataSource extends HikariConfig
You need to
I believe in defining my own Custom Configuration class ( @Configuration ) to create the data source on my own and populate it with the data source properties defined in a separate file (than traditional: application.properties)
In this manner I can define my own sessionFactory Bean using Hibernate recommended: "LocalSessionFactoryBean" class and populate it with your Hikari Data Source > and other Hiberante-JPA based properties.
Summary of Spring Boot based Hikari DataSource Properties:-
spring.datasource.hikari.allow-pool-suspension=true
spring.datasource.hikari.auto-commit=false
spring.datasource.hikari.catalog=
spring.datasource.hikari.connection-init-sql=
spring.datasource.hikari.connection-test-query=
spring.datasource.hikari.connection-timeout=100
spring.datasource.hikari.data-source-class-name=
spring.datasource.hikari.data-source-j-n-d-i=
spring.datasource.hikari.driver-class-name=
spring.datasource.hikari.idle-timeout=50
spring.datasource.hikari.initialization-fail-fast=true
spring.datasource.hikari.isolate-internal-queries=true
spring.datasource.hikari.jdbc-url=
spring.datasource.hikari.leak-detection-threshold=
spring.datasource.hikari.login-timeout=60
spring.datasource.hikari.max-lifetime=
spring.datasource.hikari.maximum-pool-size=500
spring.datasource.hikari.minimum-idle=30
spring.datasource.hikari.password=
spring.datasource.hikari.pool-name=
spring.datasource.hikari.read-only=true
spring.datasource.hikari.register-mbeans=true
spring.datasource.hikari.transaction-isolation=
spring.datasource.hikari.username=
spring.datasource.hikari.validation-timeout=
This should do it for you ^wp.*php$
Matches
wp-comments-post.php
wp.something.php
wp.php
Doesn't match
something-wp.php
wp.php.txt
Well, given your constraints, I think setting overflow: scroll;
on the .page
div is probably your only option. 280 px is pretty narrow, and given your font size, word wrapping alone isn't going to do it. Some words are just long and can't be wrapped. You can either reduce your font size drastically or go with overflow: scroll.
Normally the views belong with a specific matching controller that supports its data requirements, or the view belongs in the Views/Shared
folder if shared between controllers (hence the name).
You can refer to views/partial views from another controller, by specifying the full path (including extension) like:
return PartialView("~/views/ABC/XXX.cshtml", zyxmodel);
or a relative path (no extension), based on the answer by @Max Toro
return PartialView("../ABC/XXX", zyxmodel);
BUT THIS IS NOT A GOOD IDEA ANYWAY
*Note: These are the only two syntax that work. not ABC\\XXX
or ABC/XXX
or any other variation as those are all relative paths and do not find a match.
You can use Html.Renderpartial
in your view instead, but it requires the extension as well:
Html.RenderPartial("~/Views/ControllerName/ViewName.cshtml", modeldata);
Use @Html.Partial
for inline Razor syntax:
@Html.Partial("~/Views/ControllerName/ViewName.cshtml", modeldata)
You can use the ../controller/view
syntax with no extension (again credit to @Max Toro):
@Html.Partial("../ControllerName/ViewName", modeldata)
Note: Apparently RenderPartial
is slightly faster than Partial, but that is not important.
If you want to actually call the other controller, use:
@Html.Action("action", "controller", parameters)
My personal preference is to use @Html.Action
as it allows each controller to manage its own views, rather than cross-referencing views from other controllers (which leads to a large spaghetti-like mess).
You would normally pass just the required key values (like any other view) e.g. for your example:
@Html.Action("XXX", "ABC", new {id = model.xyzId })
This will execute the ABC.XXX
action and render the result in-place. This allows the views and controllers to remain separately self-contained (i.e. reusable).
I have just hit a situation where I could not use @Html.Action, but needed to create a view path based on a action
and controller
names. To that end I added this simple View
extension method to UrlHelper
so you can say return PartialView(Url.View("actionName", "controllerName"), modelData)
:
public static class UrlHelperExtension
{
/// <summary>
/// Return a view path based on an action name and controller name
/// </summary>
/// <param name="url">Context for extension method</param>
/// <param name="action">Action name</param>
/// <param name="controller">Controller name</param>
/// <returns>A string in the form "~/views/{controller}/{action}.cshtml</returns>
public static string View(this UrlHelper url, string action, string controller)
{
return string.Format("~/Views/{1}/{0}.cshtml", action, controller);
}
}
Use java.net.URL#openStream()
with a proper URL (including the protocol!). E.g.
InputStream input = new URL("http://www.somewebsite.com/a.txt").openStream();
// ...
Quick solution: Update package.json
"devDependencies": {
...
"typescript": "~3.7.4",
}
In tsconfig.json
{
...,
"angularCompilerOptions": {
...,
"disableTypeScriptVersionCheck": true
}
}
then remove node_modules folder and reinstall with
npm install
For more visit here
You can do by xlwings as well
import xlwings as xw
for book in xlwings.books:
print(book)
You can use a Multiset (from guava). It will give you the count for each object. For example:
Multiset<Character> chars = HashMultiset.create();
for (int i = 0; i < string.length(); i++) {
chars.add(string.charAt(i));
}
Then for each character you can call chars.count('a')
and it returns the number of occurrences
A hackish perl solution can be like this. It's nice because it doesn't load all the file in memory, prints intermediate temp files, and then uses the all-wonderful paste
#!/usr/bin/perl
use warnings;
use strict;
my $counter;
open INPUT, "<$ARGV[0]" or die ("Unable to open input file!");
while (my $line = <INPUT>) {
chomp $line;
my @array = split ("\t",$line);
open OUTPUT, ">temp$." or die ("unable to open output file!");
print OUTPUT join ("\n",@array);
close OUTPUT;
$counter=$.;
}
close INPUT;
# paste files together
my $execute = "paste ";
foreach (1..$counter) {
$execute.="temp$counter ";
}
$execute.="> $ARGV[1]";
system $execute;
SHOW ENGINE INNODB STATUS \G
Look for the Section -
TRANSACTIONS
We can use INFORMATION_SCHEMA Tables.
Useful Queries
To check about all the locks transactions are waiting for:
USE INFORMATION_SCHEMA;
SELECT * FROM INNODB_LOCK_WAITS;
A list of blocking transactions:
SELECT *
FROM INNODB_LOCKS
WHERE LOCK_TRX_ID IN (SELECT BLOCKING_TRX_ID FROM INNODB_LOCK_WAITS);
OR
SELECT INNODB_LOCKS.*
FROM INNODB_LOCKS
JOIN INNODB_LOCK_WAITS
ON (INNODB_LOCKS.LOCK_TRX_ID = INNODB_LOCK_WAITS.BLOCKING_TRX_ID);
A List of locks on particular table:
SELECT * FROM INNODB_LOCKS
WHERE LOCK_TABLE = db_name.table_name;
A list of transactions waiting for locks:
SELECT TRX_ID, TRX_REQUESTED_LOCK_ID, TRX_MYSQL_THREAD_ID, TRX_QUERY
FROM INNODB_TRX
WHERE TRX_STATE = 'LOCK WAIT';
Reference - MySQL Troubleshooting: What To Do When Queries Don't Work, Chapter 6 - Page 96.
#!/usr/bin/env sh
this is how git bash knows a file is executable. chmod a+x
does nothing in gitbash. (Note: any "she-bang" will work, e.g. #!/bin/bash
, etc.)
using System.Net;
string host = Dns.GetHostName();
IPHostEntry ip = Dns.GetHostEntry(host);
Console.WriteLine(ip.AddressList[0].ToString());
Just tested this on my machine and it works.
You have multiple options. Two options are the following.
numpy.sum(boolarr)
numpy.count_nonzero(boolarr)
Here's an example:
>>> import numpy as np
>>> boolarr = np.array([[0, 0, 1], [1, 0, 1], [1, 0, 1]], dtype=np.bool)
>>> boolarr
array([[False, False, True],
[ True, False, True],
[ True, False, True]], dtype=bool)
>>> np.sum(boolarr)
5
Of course, that is a bool
-specific answer. More generally, you can use numpy.count_nonzero
.
>>> np.count_nonzero(boolarr)
5
As Christian's answer with assign()
shows, there is a way to assign in the global environment. A simpler, shorter (but not better ... stick with assign) way is to use the <<-
operator, ie
a <<- "new"
inside the function.
My solution using standard <ul>
and <i>
inside <li>
<ul>
<li><i class="fab fa-cc-paypal"></i> <div>Paypal</div></li>
<li><i class="fab fa-cc-apple-pay"></i> <div>Apple Pay</div></li>
<li><i class="fab fa-cc-stripe"></i> <div>Stripe</div></li>
<li><i class="fab fa-cc-visa"></i> <div>VISA</div></li>
</ul>
One can issue the SQL*Plus command SET TIMING ON
to get wall-clock times, but one can't take, for example, fetch time out of that trivially.
The AUTOTRACE setting, when used as SET AUTOTRACE TRACEONLY
will suppress output, but still perform all of the work to satisfy the query and send the results back to SQL*Plus, which will suppress it.
Lastly, one can trace the SQL*Plus session, and manually calculate the time spent waiting on events which are client waits, such as "SQL*Net message to client", "SQL*Net message from client".
I stopped the IIS Worker Process (in task manager), and then started the IIS again. It worked.
Inside your for-loop, just add the following line:
if(books[i] != null) {
total += books[i].getPrice();
}
This works best for me: Add this at the top of the script:
#!c:/Python27/python.exe
(C:\Python27\python.exe is the path to the python.exe on my machine) Then run the script via:
chmod +x script-name.py && script-name.py
Building on @Panagiotis Kanavos' answer, here's a working method as example which will also return the response as an object instead of a string:
using System.Text;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json; // Nuget Package
public static async Task<object> PostCallAPI(string url, object jsonObject)
{
try
{
using (HttpClient client = new HttpClient())
{
var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, content);
if (response != null)
{
var jsonString = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<object>(jsonString);
}
}
}
catch (Exception ex)
{
myCustomLogger.LogException(ex);
}
return null;
}
Keep in mind that this is only an example and that you'd probably would like to use HttpClient
as a shared instance instead of using it in a using-clause.
Old question but I recently ran into this problem.
If you're trying to get the task_id you can do it like this:
import celery
from celery_app import add
from celery import uuid
task_id = uuid()
result = add.apply_async((2, 2), task_id=task_id)
Now you know exactly what the task_id is and can now use it to get the AsyncResult:
# grab the AsyncResult
result = celery.result.AsyncResult(task_id)
# print the task id
print result.task_id
09dad9cf-c9fa-4aee-933f-ff54dae39bdf
# print the AsyncResult's status
print result.status
SUCCESS
# print the result returned
print result.result
4
You need to add JQuery before adding bootstrap-
<!-- JQuery Core JavaScript -->
<script src="lib/js/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="lib/js/bootstrap.min.js"></script>
I wrote an updated version of Kees C. Bakker's answer:
const hasVerticalScroll = (node) => {
if (!node) {
if (window.innerHeight) {
return document.body.offsetHeight > window.innerHeight
}
return (document.documentElement.scrollHeight > document.documentElement.offsetHeight)
|| (document.body.scrollHeight > document.body.offsetHeight)
}
return node.scrollHeight > node.offsetHeight
}
if (hasVerticalScroll(document.querySelector('body'))) {
this.props.handleDisableDownScrollerButton()
}
The function returns true or false depending whether the page has a vertical scrollbar or not.
For example:
const hasVScroll = hasVerticalScroll(document.querySelector('body'))
if (hasVScroll) {
console.log('HAS SCROLL', hasVScroll)
}
Dim tblReady1 As DataTable = tblReady.Clone()
'' convert all the columns type to String
For Each col As DataColumn In tblReady1.Columns
col.DataType = GetType(String)
Next
tblReady1.Load(tblReady.CreateDataReader)
Your problem are the cr (carriage return)
http://jsfiddle.net/NT9KB/210/
you can use:
document.getElementById("img").src = "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
Based on Emissary's ES6+ answer, you could use Array.prototype.reduce
to do your comparison (as opposed to sorting, popping and potentially mutating your array), which I think looks quite slick.
const mode = (myArray) =>
myArray.reduce(
(a,b,i,arr)=>
(arr.filter(v=>v===a).length>=arr.filter(v=>v===b).length?a:b),
null)
I'm defaulting to null, which won't always give you a truthful response if null is a possible option you're filtering for, maybe that could be an optional second argument
The downside, as with various other solutions, is that it doesn't handle 'draw states', but this could still be achieved with a slightly more involved reduce function.
You need to create WifiConfiguration
instance like this:
String networkSSID = "test";
String networkPass = "pass";
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\""; // Please note the quotes. String should contain ssid in quotes
Then, for WEP network you need to do this:
conf.wepKeys[0] = "\"" + networkPass + "\"";
conf.wepTxKeyIndex = 0;
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
For WPA network you need to add passphrase like this:
conf.preSharedKey = "\""+ networkPass +"\"";
For Open network you need to do this:
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
Then, you need to add it to Android wifi manager settings:
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(conf);
And finally, you might need to enable it, so Android connects to it:
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
break;
}
}
UPD: In case of WEP, if your password is in hex, you do not need to surround it with quotes.
Not an answer, but just some food for thought.
If class is having overloaded index/subscript operator, the expression 0[x]
will not work:
class Sub
{
public:
int operator [](size_t nIndex)
{
return 0;
}
};
int main()
{
Sub s;
s[0];
0[s]; // ERROR
}
Since we dont have access to int class, this cannot be done:
class int
{
int operator[](const Sub&);
};
I like to use this command:
List<Store> myStoreList = Service.GetStoreListbyProvince(provinceId)
.GroupBy(s => s.City)
.Select(grp => grp.FirstOrDefault())
.OrderBy(s => s.City)
.ToList();
I have these fields in my list: Id, StoreName, City, PostalCode I wanted to show list of cities in a dropdown which has duplicate values. solution: Group by city then pick the first one for the list.
I hope it helps :)
Well, there's always the low tech solution of adding logging of the size of your maps when you modify them, then search the logs for which maps are growing beyond a reasonable size.
The .git
at the end of the repository name is just a convention. Typically, on git servers repositories are kept in directories named project.git
. The git client and protocol honours this convention by testing for project.git
when only project
is specified.
git://[email protected]/peter/first_app.git
is not a valid git url. git repositories can be identified and accessed via various url schemes specified here. [email protected]:peter/first_app.git
is the ssh
url mentioned on that page.
git
is flexible. It allows you to track your local branch against almost any branch of any repository. While master
(your local default branch) tracking origin/master
(the remote default branch) is a popular situation, it is not universal. Many a times you may not want to do that. This is why the first git push
is so verbose. It tells git what to do with the local master
branch when you do a git pull
or a git push
.
The default for git push
and git pull
is to work with the current branch's remote. This is a better default than origin master. The way git push determines this is explained here.
git
is fairly elegant and comprehensible but there is a learning curve to walk through.
You need to concatenate the selector and pseudo selector. You'll also need a style element to contain your styles. Most people use an external stylesheet, for lots of benefits (caching for one).
<a class="hover">click</a>
<style type="text/css">
a.hover:hover {
text-decoration: underline;
}
</style>
Just a note: the hover class is not necessary, unless you are defining only certain links to have this behavior (which may be the case)
I recently work on it. Try this function:
/**
* @return array an array of your files uploaded.
*/
private function _upload_files($field='userfile'){
$files = array();
foreach( $_FILES[$field] as $key => $all )
foreach( $all as $i => $val )
$files[$i][$key] = $val;
$files_uploaded = array();
for ($i=0; $i < count($files); $i++) {
$_FILES[$field] = $files[$i];
if ($this->upload->do_upload($field))
$files_uploaded[$i] = $this->upload->data($files);
else
$files_uploaded[$i] = null;
}
return $files_uploaded;
}
in your case:
<input type="file" multiple name="images[]" size="20" />
or
<input type="file" name="images[]">
<input type="file" name="images[]">
<input type="file" name="images[]">
in the controller:
public function do_upload(){
$config['upload_path'] = './Images/';
$config['allowed_types'] = 'gif|jpg|png';
//...
$this->load->library('upload',$config);
if ($_FILES['images']) {
$images= $this->_upload_files('images');
print_r($images);
}
}
Some basic reference from PHP manual: PHP file upload
This should works for empty dir (You may need to check if the second string starts with /
which should be treat as an absolute path?):
#!/bin/bash
join_path() {
echo "${1:+$1/}$2" | sed 's#//#/#g'
}
join_path "" a.bin
join_path "/data" a.bin
join_path "/data/" a.bin
Output:
a.bin
/data/a.bin
/data/a.bin
Reference: Shell Parameter Expansion
According to the Python doc, we can also use class.__mro__
attribute or class.mro()
method:
class Suit:
pass
class Heart(Suit):
pass
class Spade(Suit):
pass
class Diamond(Suit):
pass
class Club(Suit):
pass
>>> Heart.mro()
[<class '__main__.Heart'>, <class '__main__.Suit'>, <class 'object'>]
>>> Heart.__mro__
(<class '__main__.Heart'>, <class '__main__.Suit'>, <class 'object'>)
Suit in Heart.mro() # True
object in Heart.__mro__ # True
Spade in Heart.mro() # False
This can happen when trying to install a debug/unsigned APK on top of a signed release APK from the Play store.
H:\>adb install -r "Signed.apk"
2909 KB/s (220439 bytes in 0.074s)
pkg: /data/local/tmp/Signed.apk
Success
H:\>adb install -r "AppName.apk"
2753 KB/s (219954 bytes in 0.078s)
pkg: /data/local/tmp/AppName.apk
Failure [INSTALL_FAILED_VERSION_DOWNGRADE]
The solution to this is to uninstall and then reinstall or re run it from the IDE.
As of jackson 2.7.4 (or earlier maybe), the class is in jacskon-jaxrs-base.jar, which is contained in jackson-jaxrs-json-provider
If you want to have an affix on your header you can use this tricks, add position: relative on your th and change the position in eventListener('scroll')
I have created an example: https://codesandbox.io/s/rl1jjx0o
I use vue.js but you can use this, without vue.js
Go to avd manager and click on Wipe Data of the device you want to run. Worked for me. The size of device on disk will reduce after wiping the data. I hope it helps someone.
When the game starts:
long tStart = System.currentTimeMillis();
When the game ends:
long tEnd = System.currentTimeMillis();
long tDelta = tEnd - tStart;
double elapsedSeconds = tDelta / 1000.0;
If you want to insert a large code block with optional line numbers, etc use the Code Macro (available under Macros -> Other).
tl;dr — There's a summary at the end and headings in the answer to make it easier to find the relevant parts. Reading everything is recommended though as it provides useful background for understanding the why that makes seeing how the how applies in different circumstances easier.
This is the Same Origin Policy. It is a security feature implemented by browsers.
Your particular case is showing how it is implemented for XMLHttpRequest (and you'll get identical results if you were to use fetch), but it also applies to other things (such as images loaded onto a <canvas>
or documents loaded into an <iframe>
), just with slightly different implementations.
(Weirdly, it also applies to CSS fonts, but that is because found foundries insisted on DRM and not for the security issues that the Same Origin Policy usually covers).
The standard scenario that demonstrates the need for the SOP can be demonstrated with three characters:
https://www.[website].com/
in your example)http://localhost:4300
in your example)Alice is logged into Bob's site and has some confidential data there. Perhaps it is a company intranet (accessible only to browsers on the LAN), or her online banking (accessible only with a cookie you get after entering a username and password).
Alice visits Mallory's website which has some JavaScript that causes Alice's browser to make an HTTP request to Bob's website (from her IP address with her cookies, etc). This could be as simple as using XMLHttpRequest
and reading the responseText
.
The browser's Same Origin Policy prevents that JavaScript from reading the data returned by Bob's website (which Bob and Alice don't want Mallory to access). (Note that you can, for example, display an image using an <img>
element across origins because the content of the image is not exposed to JavaScript (or Mallory) … unless you throw canvas into the mix in which case you will generate a same-origin violation error).
For any given URL it is possible that the SOP is not needed. A couple of common scenarios where this is the case are:
… but the browser has no way of knowing if either of the above are true, so trust is not automatic and the SOP is applied. Permission has to be granted explicitly before the browser will give the data it was given to a different website.
Browser extensions*
, the Network tab in browser developer tools and applications like Postman are installed software. They aren't passing data from one website to the JavaScript belonging to a different website just because you visited that different website. Installing software usually takes a more conscious choice.
There isn't a third party (Mallory) who is considered a risk.
*
Browser extensions do need to be written carefully to avoid cross-origin issues. See the Chrome documentation for example.
There are a number of circumstances where Mallory's site can cause a browser to fetch data from a third party and display it (e.g. by adding an <img>
element to display an image). It isn't possible for Mallory's JavaScript to read the data in that resource though, only Alice's browser and Bob's server can do that, so it is still secure.
The Access-Control-Allow-Origin
HTTP response header referred to in the error message is part of the CORS standard which allows Bob to explicitly grant permission to Mallory's site to access the data via Alice's browser.
A basic implementation would just include:
Access-Control-Allow-Origin: *
… in the response headers to permit any website to read the data.
Access-Control-Allow-Origin: http://example.com/
… would allow only a specific site to access it, and Bob can dynamically generate that based on the Origin
request header to permit multiple, but not all, sites to access it.
The specifics of how Bob sets that response header depend on Bob's HTTP server and/or server-side programming language. There is a collection of guides for various common configurations that might help.
NB: Some requests are complex and send a preflight OPTIONS request that the server will have to respond to before the browser will send the GET/POST/PUT/Whatever request that the JS wants to make. Implementations of CORS that only add Access-Control-Allow-Origin
to specific URLs often get tripped up by this.
Obviously granting permission via CORS is something Bob would only do only if either:
There is no standard mechanism for Mallory to add this header because it has to come from Bob's website, which she does not control.
If Bob is running a public API then there might be a mechanism to turn on CORS (perhaps by formatting the request in a certain way, or a config option after logging into a Developer Portal site for Bob's site). This will have to be a mechanism implemented by Bob though. Mallory could read the documentation on Bob's site to see if something is available, or she could talk to Bob and ask him to implement CORS.
Some cross origin requests are preflighted.
This happens when (roughly speaking) you try to make a cross-origin request that:
enctype
).In these cases then the rest of this answer still applies but you also need to make sure that the server can listen for the preflight request (which will be OPTIONS
(and not GET
, POST
or whatever you were trying to send) and respond to it with the right Access-Control-Allow-Origin
header but also Access-Control-Allow-Methods
and Access-Control-Allow-Headers
to allow your specific HTTP methods or headers.
Sometimes people make mistakes when trying to construct Ajax requests, and sometimes these trigger the need for a preflight. If the API is designed to allow cross-origin requests, but doesn't require anything that would need a preflight, then this can break access.
Common mistakes that trigger this include:
Access-Control-Allow-Origin
and other CORS response headers on the request. These don't belong on the request, don't do anything helpful (what would be the point of a permissions system where you could grant yourself permission?), and must appear only on the response.Content-Type: application/json
header on a GET request that has no request body to describe the content of (typically when the author confuses Content-Type
and Accept
).In either of these cases, removing the extra request header will often be enough to avoid the need for a preflight (which will solve the problem when communicating with APIs that support simple requests but not preflighted requests).
Sometimes you need to make an HTTP request, but you don't need to read the response. e.g. if you are posting a log message to the server for recording.
If you are using the fetch
API (rather than XMLHttpRequest
), then you can configure it to not try to use CORS.
Note that this won't let you do anything that you require CORS to do. You will not be able to read the response. You will not be able to make a request that requires a preflight.
It will let you make a simple request, not see the response, and not fill the Developer Console with error messages.
How to do it is explained by the Chrome error message given when you make a request using fetch
and don't get permission to view the response with CORS:
Access to fetch at '
https://example.com/
' from origin 'https://example.net
' has been blocked by CORS policy: No 'Access-Control-Allow-Origin
' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Thus:
fetch("http://example.com", { mode: "no-cors" });
Bob could also provide the data using a hack like JSONP which is how people did cross-origin Ajax before CORS came along.
It works by presenting the data in the form of a JavaScript program which injects the data into Mallory's page.
It requires that Mallory trust Bob not to provide malicious code.
Note the common theme: The site providing the data has to tell the browser that it is OK for a third party site to access the data it is sending to the browser.
Since JSONP works by appending a <script>
element to load the data in the form of a JavaScript program which calls a function already in the page, attempting to use the JSONP technique on a URL which returns JSON will fail — typically with a CORB error — because JSON is not JavaScript.
If the HTML document the JS runs in and the URL being requested are on the same origin (sharing the same scheme, hostname, and port) then they Same Origin Policy grants permission by default. CORS is not needed.
Mallory could use server-side code to fetch the data (which she could then pass from her server to Alice's browser through HTTP as usual).
It will either:
That server-side code could be written & hosted by a third party (such as CORS Anywhere). Note the privacy implications of this: The third party can monitor who proxies what across their servers.
Bob wouldn't need to grant any permissions for that to happen.
There are no security implications here since that is just between Mallory and Bob. There is no way for Bob to think that Mallory is Alice and to provide Mallory with data that should be kept confidential between Alice and Bob.
Consequently, Mallory can only use this technique to read public data.
Do note, however, that taking content from someone else's website and displaying it on your own might be a violation of copyright and open you up to legal action.
As noted in the section "Why the Same Origin Policy only applies to JavaScript in a web page", you can avoid the SOP by not writing JavaScript in a webpage.
That doesn't mean you can't continue to use JavaScript and HTML, but you could distribute it using some other mechanism, such as Node-WebKit or PhoneGap.
It is possible for a browser extension to inject the CORS headers in the response before the Same Origin Policy is applied.
These can be useful for development, but are not practical for a production site (asking every user of your site to install a browser extension that disables a security feature of their browser is unreasonable).
They also tend to work only with simple requests (failing when handling preflight OPTIONS requests).
Having a proper development environment with a local development server is usually a better approach.
Note that SOP / CORS do not mitigate XSS, CSRF, or SQL Injection attacks which need to be handled independently.
Moreover, Please refer to load(Reader reader) method from Property
class on javadoc
In load(Reader reader)
method documentation it says
The key contains all of the characters in the line starting with the first non-white space character and up to, but not including, the first unescaped
'='
,':'
, or white space character other than a line terminator. All of these key termination characters may be included in the key by escaping them with a preceding backslash character; for example,\:\=
would be the two-character key
":=".
Line terminator characters can be included using\r
and\n
escape sequences. Any white space after the key is skipped; if the first non-white space character after the key is'='
or':'
, then it is ignored and any white space characters after it are also skipped. All remaining characters on the line become part of the associated element string; if there are no remaining characters, the element is the empty string""
. Once the raw character sequences constituting the key and element are identified, escape processing is performed as described above.
Hope that helps.
Alternative simple way is to use parsename
:
select full_name,
parsename(replace(full_name, ' ', '.'), 3) as FirstName,
parsename(replace(full_name, ' ', '.'), 2) as MiddleName,
parsename(replace(full_name, ' ', '.'), 1) as LastName
from YourTableName
My solution was to insert <packaging>pom</packaging>
between artifactId
and version
<groupId>com.onlinechat</groupId>
<artifactId>chat-online</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>server</module>
<module>client</module>
<module>network</module>
</modules>
I use both windows and linux, but the solution core.autocrlf true
didn't help me. I even got nothing changed after git checkout <filename>
.
So I use workaround to substitute git status
- gitstatus.sh
#!/bin/bash
git status | grep modified | cut -d' ' -f 4 | while read x; do
x1="$(git show HEAD:$x | md5sum | cut -d' ' -f 1 )"
x2="$(cat $x | md5sum | cut -d' ' -f 1 )"
if [ "$x1" != "$x2" ]; then
echo "$x NOT IDENTICAL"
fi
done
I just compare md5sum
of a file and its brother at repository.
Example output:
$ ./gitstatus.sh
application/script.php NOT IDENTICAL
application/storage/logs/laravel.log NOT IDENTICAL
in swift you should delegate UITextfieldDelegate, its important don't forget it, in the viewController, like:
class MyViewController: UITextfieldDelegate{
mytextfield.delegate = self
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
}
}
I also thought this would work but it's misleading:
myStruct _m1 = {0};
When I tried this:
myStruct _m1 = {0xff};
Only the 1st byte was set to 0xff
, the remaining ones were set to 0
. So I wouldn't get into the habit of using this.
Frankly, sometimes we need to obfuscate the code (for example, register license classes and so on). In this case, your project is not free. IMO, you should pay for a good obfucator.
Dotfuscator hides your code and .NET Reflector shows an error when you attempt to decompile it.
Also consider using an .editorconfig file: https://marketplace.eclipse.org/content/editorconfig-eclipse. Someone not using Eclipse may also benefit from this, in the worst case it can serve as a guideline. NOTE: I will not enter the tabs vs space wars but use spaces FTW :-)
function getCurrentTime(){
var date = new Date();
var hh = date.getHours();
var mm = date.getMinutes();
hh = hh < 10 ? '0'+hh : hh;
mm = mm < 10 ? '0'+mm : mm;
curr_time = hh+':'+mm;
return curr_time;
}
The way to stretch it to the same size as the parent container is to use the attribute:
<Textbox HorizontalAlignment="Stretch" ...
That will make the Textbox element stretch horizontally and fill all the parent space horizontally (actually it depends on the parent panel you're using but should work for most cases).
Percentages can only be used with grid cell values so another option is to create a grid and put your textbox in one of the cells with the appropriate percentage.
What about /disable
, and /enable
switch for a /change
command?
schtasks.exe /change /s <machine name> /tn <task name> /disable
schtasks.exe /change /s <machine name> /tn <task name> /enable
A much easier way is to go to Data and select Group or Subtotal. Instant collapsible rows without messing with pivot tables or VBA.
.overlay
didn't have a height or width and no content, and you can't hover over display:none
.
I instead gave the div the same size and position as .image
and changes RGBA
value on hover.
http://jsfiddle.net/Zf5am/566/
.image { position: absolute; border: 1px solid black; width: 200px; height: 200px; z-index:1;}
.image img { max-width: 100%; max-height: 100%; }
.overlay { position: absolute; top: 0; left: 0; background:rgba(255,0,0,0); z-index: 200; width:200px; height:200px; }
.overlay:hover { background:rgba(255,0,0,.7); }
A 2D array is basically a 1D array of pointers, where every pointer is pointing to a 1D array, which will hold the actual data.
Here N is row and M is column.
dynamic allocation
int** ary = new int*[N];
for(int i = 0; i < N; i++)
ary[i] = new int[M];
fill
for(int i = 0; i < N; i++)
for(int j = 0; j < M; j++)
ary[i][j] = i;
for(int i = 0; i < N; i++)
for(int j = 0; j < M; j++)
std::cout << ary[i][j] << "\n";
free
for(int i = 0; i < N; i++)
delete [] ary[i];
delete [] ary;
This is old, just update new tidyverse workflow not mentioned above.
library(tidyverse)
jobsAFAM1 <- tibble(
date = seq.Date(from = as.Date('2017-01-01'),by = 'day', length.out = 5),
Percent.Change = runif(5, 0,1)
) %>%
mutate(serial='jobsAFAM1')
jobsAFAM2 <- tibble(
date = seq.Date(from = as.Date('2017-01-01'),by = 'day', length.out = 5),
Percent.Change = runif(5, 0,1)
) %>%
mutate(serial='jobsAFAM2')
jobsAFAM <- bind_rows(jobsAFAM1, jobsAFAM2)
ggplot(jobsAFAM, aes(x=date, y=Percent.Change, col=serial)) + geom_line()
@Chris Njuguna
tidyr::gather() is the one in tidyverse workflow to turn wide dataframe to long tidy layout, then ggplot could plot multiple serials.
You are importing from package "sub". start.py
is not itself in a package even if there is a __init__.py
present.
You would need to start your program from one directory over parent.py
:
./start.py
./pkg/__init__.py
./pkg/parent.py
./pkg/sub/__init__.py
./pkg/sub/relative.py
With start.py
:
import pkg.sub.relative
Now pkg is the top level package and your relative import should work.
If you want to stick with your current layout you can just use import parent
. Because you use start.py
to launch your interpreter, the directory where start.py
is located is in your python path. parent.py
lives there as a separate module.
You can also safely delete the top level __init__.py
, if you don't import anything into a script further up the directory tree.
Since you've already mentioned the Ordered Test functionality that the Visual Studio testing framework supplies, I'll ignore that. You also seem to be aware that what you're trying to accomplish in order to test this Static Class is a "bad idea", so I'll ignore that to.
Instead, lets focus on how you might actually be able to guarantee that your tests are executed in the order you want. One option (as supplied by @gaog) is "one test method, many test functions", calling your test functions in the order that you want from within a single function marked with the TestMethod
attribute. This is the simplest way, and the only disadvantage is that the first test function to fail will prevent any of the remaining test functions from executing.
With your description of the situation, this is the solution I would suggest you use.
If the bolded part is a problem for you, you can accomplish an ordered execution of isolated tests by leveraging the in built data driven test functionality. Its more complicated and feels a bit dirty, but it gets the job done.
In short, you define a data source (like a CSV file, or a database table) that controls the order in which you need to run your tests, and names of the functions that actually contain the test functionality. You then hook that data source into a data driven test, use the sequential read option, and execute your functions, in the order you want, as individual tests.
[TestClass]
public class OrderedTests
{
public TestContext TestContext { get; set; }
private const string _OrderedTestFilename = "TestList.csv";
[TestMethod]
[DeploymentItem(_OrderedTestFilename)]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", _OrderedTestFilename, _OrderedTestFilename, DataAccessMethod.Sequential)]
public void OrderedTests()
{
var methodName = (string)TestContext.DataRow[0];
var method = GetType().GetMethod(methodName);
method.Invoke(this, new object[] { });
}
public void Method_01()
{
Assert.IsTrue(true);
}
public void Method_02()
{
Assert.IsTrue(false);
}
public void Method_03()
{
Assert.IsTrue(true);
}
}
In my example, I have a supporting file called TestList.csv, which gets copied to output. It looks like this:
TestName
Method_01
Method_02
Method_03
Your tests will be executed in the order that you specified, and in normal test isolation (i.e. if one fails, the rest still get executed, but sharing static classes).
The above is really only the basic idea, if I were to use it in production I would generate the test function names and their order dynamically before the test is run. Perhaps by leveraging PriorityAttribute you found and some simple reflection code to extract the test methods in the class and order them appropriately, then write that order to the data source.
In my case what removed this message was (After updating everything) deleting the emulator and creating a new one. Manually updating the adb didn't solved this for. Nor updating via the Android studio Gui. In my case it seems that since the emulator was created with "old" components it keep showing the message. I had three emulators, just deleted them all and created a new one. For my surprise when it started the message was no more.
Cannot tell if performance is better or not. The message just didn't came up. Also I have everything updated to the latest (emulators and sdk).
To do it from a Base64 encoding you can use the following function:
function base64ToArrayBuffer(data) {
const bString = window.atob(data);
const bLength = bString.length;
const bytes = new Uint8Array(bLength);
for (let i = 0; i < bLength; i++) {
bytes[i] = bString.charCodeAt(i);
}
return bytes;
}
function base64toPDF(base64EncodedData, fileName = 'file') {
const bufferArray = base64ToArrayBuffer(base64EncodedData);
const blobStore = new Blob([bufferArray], { type: 'application/pdf' });
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blobStore);
return;
}
const data = window.URL.createObjectURL(blobStore);
const link = document.createElement('a');
document.body.appendChild(link);
link.href = data;
link.download = `${fileName}.pdf`;
link.click();
window.URL.revokeObjectURL(data);
link.remove();
}
Differences between an XML Schema Definition (XSD) and Document Type Definition (DTD) include:
Not all these bullet points are 100% accurate, but you get the gist.
On the other hand:
tempData.push( data[index] );
I agree with the correct answer above, but.... your still not giving the index value for the data that you want to add to tempData. Without the [index] value the whole array will be added.
You can transform logical implication A => B
to NOT A or B
. This is one of the most basic laws of logic. In your case it is something like this:
SELECT *
FROM logs
WHERE pw='correct' AND (id>=800 OR success=1)
AND YEAR(timestamp)=2011
I also transformed NOT id<800
to id>=800
, which is also pretty basic.
From The Swift Programming Language
:
The Sort Function Swift’s standard library provides a function called sort, which sorts an array of values of a known type, based on the output of a sorting closure that you provide. Once it completes the sorting process, the sort function returns a new array of the same type and size as the old one, with its elements in the correct sorted order.
The sort
function has two declarations.
The default declaration which allows you to specify a comparison closure:
func sort<T>(array: T[], pred: (T, T) -> Bool) -> T[]
And a second declaration that only take a single parameter (the array) and is "hardcoded to use the less-than comparator."
func sort<T : Comparable>(array: T[]) -> T[]
Example:
sort( _arrayToSort_ ) { $0 > $1 }
I tested a modified version of your code in a playground with the closure added on so I could monitor the function a little more closely, and I found that with n set to 1000, the closure was being called about 11,000 times.
let n = 1000
let x = Int[](count: n, repeatedValue: 0)
for i in 0..n {
x[i] = random()
}
let y = sort(x) { $0 > $1 }
It is not an efficient function, an I would recommend using a better sorting function implementation.
EDIT:
I took a look at the Quicksort wikipedia page and wrote a Swift implementation for it. Here is the full program I used (in a playground)
import Foundation
func quickSort(inout array: Int[], begin: Int, end: Int) {
if (begin < end) {
let p = partition(&array, begin, end)
quickSort(&array, begin, p - 1)
quickSort(&array, p + 1, end)
}
}
func partition(inout array: Int[], left: Int, right: Int) -> Int {
let numElements = right - left + 1
let pivotIndex = left + numElements / 2
let pivotValue = array[pivotIndex]
swap(&array[pivotIndex], &array[right])
var storeIndex = left
for i in left..right {
let a = 1 // <- Used to see how many comparisons are made
if array[i] <= pivotValue {
swap(&array[i], &array[storeIndex])
storeIndex++
}
}
swap(&array[storeIndex], &array[right]) // Move pivot to its final place
return storeIndex
}
let n = 1000
var x = Int[](count: n, repeatedValue: 0)
for i in 0..n {
x[i] = Int(arc4random())
}
quickSort(&x, 0, x.count - 1) // <- Does the sorting
for i in 0..n {
x[i] // <- Used by the playground to display the results
}
Using this with n=1000, I found that
It seems that the built-in sort method is (or is close to) quick sort, and is really slow...
On Linux (and probably most Unix), there is no OS-level DNS caching unless nscd is installed and running. Even then, the DNS caching feature of nscd is disabled by default at least in Debian because it's broken. The practical upshot is that your linux system very very probably does not do any OS-level DNS caching.
You could implement your own cache in your application (like they did for Squid, according to diegows's comment), but I would recommend against it. It's a lot of work, it's easy to get it wrong (nscd got it wrong!!!), it likely won't be as easily tunable as a dedicated DNS cache, and it duplicates functionality that already exists outside your application.
If an end user using your software needs to have DNS caching because the DNS query load is large enough to be a problem or the RTT to the external DNS server is long enough to be a problem, they can install a caching DNS server such as Unbound on the same machine as your application, configured to cache responses and forward misses to the regular DNS resolvers.
This can happen with symlinks sometimes. If you experience this issue and you know you are in an existing directory, but your symlink may have changed, you can use this command:
cd $(pwd)
If you want all the bars to get the same color (fill
), you can easily add it inside geom_bar
.
ggplot(data=df, aes(x=c1+c2/2, y=c3)) +
geom_bar(stat="identity", width=c2, fill = "#FF6666")
Add fill = the_name_of_your_var
inside aes
to change the colors depending of the variable :
c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2)
Use scale_fill_manual()
if you want to manually the change of colors.
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2) +
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))
Kathir's answer is great as he solves that problem with just jQuery. I just wanted to make some additions to his answer to work his code with a beautiful HTML progress bar:
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
$('.progress-bar').width(percentComplete+'%');
$('.progress-bar').html(percentComplete+'%');
}
}, false);
return xhr;
},
url: posturlfile,
type: "POST",
data: JSON.stringify(fileuploaddata),
contentType: "application/json",
dataType: "json",
success: function(result) {
console.log(result);
}
});
Here is the HTML code of progress bar, I used Bootstrap 3 for the progress bar element:
<div class="progress" style="display:none;">
<div class="progress-bar progress-bar-success progress-bar-striped
active" role="progressbar"
aria-valuemin="0" aria-valuemax="100" style="width:0%">
0%
</div>
</div>
This page has the HOWTO:
http://www.golesny.de/p/code/javagetpid
On Windows:
Runtime.exec(..)
Returns an instance of "java.lang.Win32Process") OR "java.lang.ProcessImpl"
Both have a private field "handle".
This is an OS handle for the process. You will have to use this + Win32 API to query PID. That page has details on how to do that.
if you're doing a lot of this kind of thing you should consider using numpy
.
In [56]: import random, numpy
In [57]: lst = numpy.array([random.uniform(0, 5) for _ in range(1000)]) # example list
In [58]: a, b = 1, 3
In [59]: numpy.flatnonzero((lst > a) & (lst < b))[:10]
Out[59]: array([ 0, 12, 13, 15, 18, 19, 23, 24, 26, 29])
In response to Seanny123's question, I used this timing code:
import numpy, timeit, random
a, b = 1, 3
lst = numpy.array([random.uniform(0, 5) for _ in range(1000)])
def numpy_way():
numpy.flatnonzero((lst > 1) & (lst < 3))[:10]
def list_comprehension():
[e for e in lst if 1 < e < 3][:10]
print timeit.timeit(numpy_way)
print timeit.timeit(list_comprehension)
The numpy version is over 60 times faster.
The easyest way is to change .attr() function to a javascript function .setAttribute()
$('#stop').click(function() {
$('next')[0].setAttribute('onclick','stopMoving()');
}
Mongoose uses the mongodb-native driver, which uses the custom ObjectID type. You can compare ObjectIDs with the .equals()
method. With your example, results.userId.equals(AnotherMongoDocument._id)
. The ObjectID type also has a toString()
method, if you wish to store a stringified version of the ObjectID in JSON format, or a cookie.
If you use ObjectID = require("mongodb").ObjectID
(requires the mongodb-native library) you can check if results.userId
is a valid identifier with results.userId instanceof ObjectID
.
Etc.
If you want to return from an outer function with an error without exit
ing you can use this trick:
do-something-complex() {
# Using `return` here would only return from `fail`, not from `do-something-complex`.
# Using `exit` would close the entire shell.
# So we (ab)use a different feature. :)
fail() { : "${__fail_fast:?$1}"; }
nested-func() {
try-this || fail "This didn't work"
try-that || fail "That didn't work"
}
nested-func
}
Trying it out:
$ do-something-complex
try-this: command not found
bash: __fail_fast: This didn't work
This has the added benefit/drawback that you can optionally turn off this feature: __fail_fast=x do-something-complex
.
Note that this causes the outermost function to return 1.
Can be done in 2 steps
Clone the repository
git clone <http url>
Checkout the branch you want
git checkout $BranchName
You can simply subclass UIButton and write your own drawing code to suit your needs. I implemented a radio button like that of android using the following code. It can be used in storyboard as well.See example in Github repo
import UIKit
@IBDesignable
class SPRadioButton: UIButton {
@IBInspectable
var gap:CGFloat = 8 {
didSet {
self.setNeedsDisplay()
}
}
@IBInspectable
var btnColor: UIColor = UIColor.green{
didSet{
self.setNeedsDisplay()
}
}
@IBInspectable
var isOn: Bool = true{
didSet{
self.setNeedsDisplay()
}
}
override func draw(_ rect: CGRect) {
self.contentMode = .scaleAspectFill
drawCircles(rect: rect)
}
//MARK:- Draw inner and outer circles
func drawCircles(rect: CGRect){
var path = UIBezierPath()
path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: rect.width, height: rect.height))
let circleLayer = CAShapeLayer()
circleLayer.path = path.cgPath
circleLayer.lineWidth = 3
circleLayer.strokeColor = btnColor.cgColor
circleLayer.fillColor = UIColor.white.cgColor
layer.addSublayer(circleLayer)
if isOn {
let innerCircleLayer = CAShapeLayer()
let rectForInnerCircle = CGRect(x: gap, y: gap, width: rect.width - 2 * gap, height: rect.height - 2 * gap)
innerCircleLayer.path = UIBezierPath(ovalIn: rectForInnerCircle).cgPath
innerCircleLayer.fillColor = btnColor.cgColor
layer.addSublayer(innerCircleLayer)
}
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.main.nativeScale
}
/*
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
isOn = !isOn
self.setNeedsDisplay()
}
*/
override func awakeFromNib() {
super.awakeFromNib()
addTarget(self, action: #selector(buttonClicked(sender:)), for: UIControl.Event.touchUpInside)
isOn = false
}
@objc func buttonClicked(sender: UIButton) {
if sender == self {
isOn = !isOn
setNeedsDisplay()
}
}
}
Different implementations of the Python DB-API are allowed to use different placeholders, so you'll need to find out which one you're using -- it could be (e.g. with MySQLdb):
cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))
or (e.g. with sqlite3 from the Python standard library):
cursor.execute("INSERT INTO table VALUES (?, ?, ?)", (var1, var2, var3))
or others yet (after VALUES
you could have (:1, :2, :3)
, or "named styles" (:fee, :fie, :fo)
or (%(fee)s, %(fie)s, %(fo)s)
where you pass a dict instead of a map as the second argument to execute
). Check the paramstyle
string constant in the DB API module you're using, and look for paramstyle at http://www.python.org/dev/peps/pep-0249/ to see what all the parameter-passing styles are!
the solution is easy: execute via sh
... -exec sh -c "zcat {} | agrep -dEOE 'grep' " \;
You can use re.escape():
re.escape(string) Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.
>>> import re
>>> re.escape('^a.*$')
'\\^a\\.\\*\\$'
If you are using a Python version < 3.7, this will escape non-alphanumerics that are not part of regular expression syntax as well.
If you are using a Python version < 3.7 but >= 3.3, this will escape non-alphanumerics that are not part of regular expression syntax, except for specifically underscore (_
).
With the Hub command-line wrapper you can link it to git and then you can do
git pull-request
From the man page of hub:
git pull-request [-f] [TITLE|-i ISSUE|ISSUE-URL] [-b BASE] [-h HEAD]
Opens a pull request on GitHub for the project that the "origin" remote points to. The default head of the pull request is the current branch. Both base and head of the pull request can be explicitly given in one of the following formats: "branch", "owner:branch",
"owner/repo:branch". This command will abort operation if it detects that the current topic branch has local commits that are not yet pushed to its upstream branch on the remote. To skip this check, use -f.
If TITLE is omitted, a text editor will open in which title and body of the pull request can be entered in the same manner as git commit message.
If instead of normal TITLE an issue number is given with -i, the pull request will be attached to an existing GitHub issue. Alternatively, instead of title you can paste a full URL to an issue on GitHub.
python has named optional arguments
def func(a, b=2, c=3):
print a, b, c
>>> func(1)
1 2 3
>>> func(1, c=4)
1 2 4
AFAIK Ruby has only positioned arguments because b=2 in the function declaration is an affectation that always append.
Use this in Activity:
private Context context = this;
........
if(Utils.isInternetAvailable(context){
Utils.showToast(context, "toast");
}
..........
in Utils:
public class Utils {
public static boolean isInternetAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}
}
Variables names are only locally meaningful.
Once you hit
return s1,s2,s3,s4
at the end of the method, Python constructs a tuple with the values of s1, s2, s3 and s4 as its four members at index 0, 1, 2 and 3 - NOT a dictionary of variable names to values, NOT an object with variable names and their values, etc.
If you want the variable names to be meaningful after you hit return
in the method, you must create an object or dictionary.
From the command run:
sudo docker build -t myrepo/redis
there are no "arguments" passed to the docker build
command, only a single flag -t
and a value for that flag. After docker parses all of the flags for the command, there should be one argument left when you're running a build.
That argument is the build context. The standard command includes a trailing dot for the context:
sudo docker build -t myrepo/redis .
Every docker build sends a directory to the build server. Docker is a client/server application, and the build runs on the server which isn't necessarily where the docker command is run. Docker uses the build context as the source for files used in COPY
and ADD
steps. When you are in the current directory to run the build, you would pass a .
for the context, aka the current directory. You could pass a completely different directory, even a git repo, and docker will perform the build using that as the context, e.g.:
docker build -t sudobmitch/base:alpine --target alpine-base \
'https://github.com/sudo-bmitch/docker-base.git#main'
For more details on these options to the build command, see the docker build documentation.
If you are including the value for the build context (typically the .
) and still see this error message, you have likely passed more than one argument. Typically this is from failing to parse a flag, or passing a string with spaces without quotes. Possible causes for docker to see more than one argument include:
Missing quotes around a path or argument with spaces (take note using variables that may have spaces in them)
Incorrect dashes in the command: make sure to type these manually rather than copy and pasting
Incorrect quotes: smart quotes don't work on the command line, type them manually rather than copy and pasting.
Whitespace that isn't white space, or that doesn't appear to be a space.
Most all of these come from either a typo or copy and pasting from a source that modified the text to look pretty, breaking it for using as a command.
The easiest way I have to debug this, run the command without any other flags:
docker build .
Once that works, add flags back in until you get the error, and then you'll know what flag is broken and needs the quotes to be fixed/added or dashes corrected, etc.
Important! Vertical center is relative to the height of the parent
If the parent of the element you're trying to center has no defined height, none of the vertical centering solutions will work!
Now, onto vertical centering...
Bootstrap 5 (Updated 2020)
Bootstrap 5 is still flexbox based so vertical centering works the same way as Bootstrap 4. For example align-items-center and justify-content-center can used on the flexbox parent (row
or d-flex
). https://codeply.com/p/0VM5MJ7Had
Bootstrap 4
You can use the new flexbox & size utilities to make the container
full-height and display: flex
. These options don't require extra CSS (except that the height of the container (ie:html,body) must be 100%).
Option 1 align-self-center
on flexbox child
<div class="container d-flex h-100">
<div class="row justify-content-center align-self-center">
I'm vertically centered
</div>
</div>
https://codeply.com/go/fFqaDe5Oey
Option 2 align-items-center
on flexbox parent (.row
is display:flex; flex-direction:row
)
<div class="container h-100">
<div class="row align-items-center h-100">
<div class="col-6 mx-auto">
<div class="jumbotron">
I'm vertically centered
</div>
</div>
</div>
</div>
https://codeply.com/go/BumdFnmLuk
Option 3 justify-content-center
on flexbox parent (.card
is display:flex;flex-direction:column
)
<div class="container h-100">
<div class="row align-items-center h-100">
<div class="col-6 mx-auto">
<div class="card h-100 border-primary justify-content-center">
<div>
...card content...
</div>
</div>
</div>
</div>
</div>
https://codeply.com/go/3gySSEe7nd
More on Bootstrap 4 Vertical Centering
Now that Bootstrap 4 offers flexbox and other utilities, there are many approaches to vertical alignment. http://www.codeply.com/go/WG15ZWC4lf
1 - Vertical Center Using Auto Margins:
Another way to vertically center is to use my-auto
. This will center the element within it's container. For example, h-100
makes the row full height, and my-auto
will vertically center the col-sm-12
column.
<div class="row h-100">
<div class="col-sm-12 my-auto">
<div class="card card-block w-25">Card</div>
</div>
</div>
Vertical Center Using Auto Margins Demo
my-auto
represents margins on the vertical y-axis and is equivalent to:
margin-top: auto;
margin-bottom: auto;
2 - Vertical Center with Flexbox:
Since Bootstrap 4 .row
is now display:flex
you can simply use align-self-center
on any column to vertically center it...
<div class="row">
<div class="col-6 align-self-center">
<div class="card card-block">
Center
</div>
</div>
<div class="col-6">
<div class="card card-inverse card-danger">
Taller
</div>
</div>
</div>
or, use align-items-center
on the entire .row
to vertically center align all col-*
in the row...
<div class="row align-items-center">
<div class="col-6">
<div class="card card-block">
Center
</div>
</div>
<div class="col-6">
<div class="card card-inverse card-danger">
Taller
</div>
</div>
</div>
Vertical Center Different Height Columns Demo
See this Q/A to center, but maintain equal height
3 - Vertical Center Using Display Utils:
Bootstrap 4 has display utils that can be used for display:table
, display:table-cell
, display:inline
, etc.. These can be used with the vertical alignment utils to align inline, inline-block or table cell elements.
<div class="row h-50">
<div class="col-sm-12 h-100 d-table">
<div class="card card-block d-table-cell align-middle">
I am centered vertically
</div>
</div>
</div>
Vertical Center Using Display Utils Demo
More examples
Vertical center image in <div>
Vertical center .row in .container
Vertical center and bottom in <div>
Vertical center child inside parent
Vertical center full screen jumbotron
Important! Did I mention height?
Remember vertical centering is relative to the height of the parent element. If you want to center on the entire page, in most cases, this should be your CSS...
body,html {
height: 100%;
}
Or use min-height: 100vh
(min-vh-100
in Bootstrap 4.1+) on the parent/container. If you want to center a child element inside the parent. The parent must have a defined height.
Also see:
Vertical alignment in bootstrap 4
Bootstrap 4 Center Vertical and Horizontal Alignment
i use jquery code for this. (Alternative solution)
$(document).ready(function() {
var margin = $(".topmenu-design").width()-$("#topmenu").width();
$("#topmenu").css('margin-left',margin/2);
});
In your XML set the Background
attribute to any colour, White(#FFFFFF)
shade or Black(#000000)
shade. If you want transparency, just put 80 before the actual hash code:
#80000000
This will change any colour you want to a transparent one.. :)
%s
is used as a placeholder for string values you want to inject into a formatted string.
%d
is used as a placeholder for numeric or decimal values.
For example (for python 3)
print ('%s is %d years old' % ('Joe', 42))
Would output
Joe is 42 years old
For conversion of milliseconds to seconds, since 1 second = 10³ milliseconds:
//here m will be in seconds
long m = System.currentTimeMillis()/1000;
//here m will be in minutes
long m = System.currentTimeMillis()/1000/60; //this will give in mins
Am I missing something? Somebody correct me if I'm wrong.
list.RemoveAll(s => s.Name == "Fred");
It looks like you have everything correct according to Laravel docs, but you have a typo
$item->push($product);
Should be
$items->push($product);
I also want to think the actual method you're looking for is put
$items->put('products', $product);
Every execution context in javascript has a this parameter that is set by:
eval
You can set the value of this using func.call
, func.apply
or func.bind
.
By default, and what confuses most beginners, when a listener is called after an event is raised on a DOM element, the this value of the function is the DOM element.
jQuery makes this trivial to change with jQuery.proxy.
I just did this tutorial and followed @gion_13 answer. Still did not work. Solved it by making my ng-app name in the index identical to the one in my js file. Exactly identical, even the quotes. So:
<div ng-app="myapp">
<div ng-controller="FirstCtrl">
and the js:
angular.module("myapp", [])
.controller('FirstCtrl',function($scope) {
$scope.data= {message:"hello"};
});
Weird how the ng-app has to be identical but the ng-controller doesn't.
Try this:
declare @var char(3)
set @var='[%]'
select Address from Accomodation where Address like '%'+@var+'%'
You must use [] cancels the effect of wildcard, so you read % as a normal character, idem about character _
Although not any better, just for the reference, you can also do this:
>>> x = '{}Hello{} {}'
>>> print x.format('{','}',42)
{Hello} 42
It can be useful for example when someone wants to print {argument}
. It is maybe more readable than '{{{}}}'.format('argument')
Note that you omit argument positions (e.g. {}
instead of {0}
) after Python 2.7
If using the latest iteration of Android Studio 3.0 and generating your Activity classes, in your styles files change this:
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
To this:
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.ActionBar" />
You can also do this without any code at all. If you right-click on the little sheet tab at the bottom of the sheet, and select "Move or Copy", you will get a dialog box that lets you choose which open workbook to transfer the sheet to.
See this link for more detailed instructions and screenshots.
You should use hasOwnProperty
. For example:
myObj.hasOwnProperty('myKey');
Note: If you are using ESLint, the above may give you an error for violating the no-prototype-builtins rule, in that case the workaround is as below:
Object.prototype.hasOwnProperty.call(myObj, 'myKey');
I use scoop as command-liner installer for Windows... scoop rocks!
The quick answer (use PowerShell):
PS C:\Users\myuser> scoop install ruby
Longer answer:
Just searching for ruby:
PS C:\Users\myuser> scoop search ruby
'main' bucket:
jruby (9.2.7.0)
ruby (2.6.3-1)
'versions' bucket:
ruby19 (1.9.3-p551)
ruby24 (2.4.6-1)
ruby25 (2.5.5-1)
Check the installation info :
PS C:\Users\myuser> scoop info ruby
Name: ruby
Version: 2.6.3-1
Website: https://rubyinstaller.org
Manifest:
C:\Users\myuser\scoop\buckets\main\bucket\ruby.json
Installed: No
Environment: (simulated)
GEM_HOME=C:\Users\myuser\scoop\apps\ruby\current\gems
GEM_PATH=C:\Users\myuser\scoop\apps\ruby\current\gems
PATH=%PATH%;C:\Users\myuser\scoop\apps\ruby\current\bin
PATH=%PATH%;C:\Users\myuser\scoop\apps\ruby\current\gems\bin
Output from installation:
PS C:\Users\myuser> scoop install ruby
Updating Scoop...
Updating 'extras' bucket...
Installing 'ruby' (2.6.3-1) [64bit]
rubyinstaller-2.6.3-1-x64.7z (10.3 MB) [============================= ... ===========] 100%
Checking hash of rubyinstaller-2.6.3-1-x64.7z ... ok.
Extracting rubyinstaller-2.6.3-1-x64.7z ... done.
Linking ~\scoop\apps\ruby\current => ~\scoop\apps\ruby\2.6.3-1
Persisting gems
Running post-install script...
Fetching rake-12.3.3.gem
Successfully installed rake-12.3.3
Parsing documentation for rake-12.3.3
Installing ri documentation for rake-12.3.3
Done installing documentation for rake after 1 seconds
1 gem installed
'ruby' (2.6.3-1) was installed successfully!
Notes
-----
Install MSYS2 via 'scoop install msys2' and then run 'ridk install' to install the toolchain!
'ruby' suggests installing 'msys2'.
PS C:\Users\myuser>
Just use GETDATE()
or GETUTCDATE()
(if you want to get the "universal" UTC time, instead of your local server's time-zone related time).
INSERT INTO [Business]
([IsDeleted]
,[FirstName]
,[LastName]
,[LastUpdated]
,[LastUpdatedBy])
VALUES
(0, 'Joe', 'Thomas',
GETDATE(), <LastUpdatedBy, nvarchar(50),>)
This is the modern way to change URL parameters:
function setGetParam(key,value) {
if (history.pushState) {
var params = new URLSearchParams(window.location.search);
params.set(key, value);
var newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + params.toString();
window.history.pushState({path:newUrl},'',newUrl);
}
}
Forward declare class B
and swap order of A
and B
definitions: 1st B
and 2nd A
. You can not call methods of forward declared B
class.
This works in Cygwin but it should be effective in Linux as well.
ps -W | awk '/ruby/,NF=1' | xargs kill -f
or
ps -W | awk '$0~z,NF=1' z=ruby | xargs kill -f
I usually define an nvl
function, and put it in globals
and filters
.
def nvl(*args):
for item in args:
if item is not None:
return item
return None
app.jinja_env.globals['nvl'] = nvl
app.jinja_env.filters['nvl'] = nvl
Usage in a template:
<span>Welcome {{ nvl(person.nick, person.name, 'Anonymous') }}<span>
// or
<span>Welcome {{ person.nick | nvl(person.name, 'Anonymous') }}<span>
is
operator : New in Django 1.10
{% if somevar is None %}
This appears if somevar is None, or if somevar is not found in the context.
{% endif %}
Here's what I suggest and what has worked for me. In your application class, implement an Application.ActivityLifeCycleCallbacks
listener and set a variable in your application class. Then query the variable as needed.
class YourApplication: Application.ActivityLifeCycleCallbacks {
var currentActivity: Activity? = null
fun onCreate() {
registerActivityLifecycleCallbacks(this)
}
...
override fun onActivityResumed(activity: Activity) {
currentActivity = activity
}
}
I think your asking to select only <span class = "my_class">hello</span>
this element, You have do like this, If I am understand your question correctly this is the answer,
$("#my_id [class='my_class']").addClass('test');
It's not valid html (I don't think) but it seems to work if you create a custom attribute for the script tag in your webpage:
<script id="myScript" myCustomAttribute="some value" ....>
Then access the custom attribute in the javascript:
var myVar = document.getElementById( "myScript" ).getAttribute( "myCustomAttribute" );
Not sure if this is better or worse than parsing the script source string.
If you want to parse the format yourself you could do it easily with a regex such as
private static Pattern pattern = Pattern.compile("(\\d{2}):(\\d{2}):(\\d{2}).(\\d{3})");
public static long dateParseRegExp(String period) {
Matcher matcher = pattern.matcher(period);
if (matcher.matches()) {
return Long.parseLong(matcher.group(1)) * 3600000L
+ Long.parseLong(matcher.group(2)) * 60000
+ Long.parseLong(matcher.group(3)) * 1000
+ Long.parseLong(matcher.group(4));
} else {
throw new IllegalArgumentException("Invalid format " + period);
}
}
However, this parsing is quite lenient and would accept 99:99:99.999 and just let the values overflow. This could be a drawback or a feature.
If none of the above answers worked for you, just close your IntelliJ IDE and remove the IntelliJ IDE file and folder from the root of your project:
rm -rf .idea *.iml
Then open the project with IntelliJ. It must work now.
The example you copied from is using data in the form of an array holding arrays, you are using data in the form of an array holding objects. Objects and arrays are not the same, and because of this they use different syntaxes for accessing data.
If you don't know the variable names, just do a var_dump($blog);
within the loop to see them.
The simplest method - access $blog as an object directly:
Try (assuming those variables are correct):
<?php
foreach ($blogs as $blog) {
$id = $blog->id;
$title = $blog->title;
$content = $blog->content;
?>
<h1> <?php echo $title; ?></h1>
<h1> <?php echo $content; ?> </h1>
<?php } ?>
The alternative method - access $blog as an array:
Alternatively, you may be able to turn $blog
into an array with get_object_vars
(documentation):
<?php
foreach($blogs as &$blog) {
$blog = get_object_vars($blog);
$id = $blog['id'];
$title = $blog['title'];
$content = $blog['content'];
?>
<h1> <?php echo $title; ?></h1>
<h1> <?php echo $content; ?> </h1>
<?php } ?>
It's worth mentioning that this isn't necessarily going to work with nested objects so its viability entirely depends on the structure of your $blog
object.
Better than either of the above - Inline PHP Syntax
Having said all that, if you want to use PHP in the most readable way, neither of the above are right. When using PHP intermixed with HTML, it's considered best practice by many to use PHP's alternative syntax, this would reduce your whole code from nine to four lines:
<?php foreach($blogs as $blog): ?>
<h1><?php echo $blog->title; ?></h1>
<p><?php echo $blog->content; ?></p>
<?php endforeach; ?>
Hope this helped.
Here's my solution. It seems to be dumb but works well...and I was trying to find all proper divisors so the loop started from i = 2.
import math as m
def findfac(n):
faclist = [1]
for i in range(2, int(m.sqrt(n) + 2)):
if n%i == 0:
if i not in faclist:
faclist.append(i)
if n/i not in faclist:
faclist.append(n/i)
return facts
you can try this way:
Fragment currentFragment = getFragmentManager().findFragmentById(R.id.fragment_container);
or
Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
In this if, you check if currentFragment is instance of YourFragment
if (currentFragment instanceof YourFragment) {
Log.v(TAG, "your Fragment is Visible");
}
I think we can do this with one line simple command
for i in `grep -rl eth0 . 2> /dev/null`; do sed -i ‘s/eth0/eth1/’ $i; done
Refer to this page.
Your date time string doesn't contains any seconds. You need to reflect that in your format (remove the :ss
).
Also, you need to specify H
instead of h
if you are using 24 hour times:
DateTime.ParseExact("04/30/2013 23:00", "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture)
See here for more information:
If you are needing this to get user's home dir, below could be considered as portable (win32 and linux at least), part of a standard library.
>>> os.path.expanduser('~')
'C:\\Documents and Settings\\johnsmith'
Also you could parse such string to get only last path component (ie. user name).
See: os.path.expanduser
Since Join-Path can be piped a path value, you can pipe multiple Join-Path statements together:
Join-Path "C:" -ChildPath "Windows" | Join-Path -ChildPath "system32" | Join-Path -ChildPath "drivers"
It's not as terse as you would probably like it to be, but it's fully PowerShell and is relatively easy to read.
Jquery Code
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
HTML CODE
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
In the package explorer, right-click on the package and select New -> File, then enter the filename including the ".properties" suffix.
This works to me:
PackageManager pm = context.getPackageManager();
try {
pm.getPackageInfo("com.whatsapp", PackageManager.GET_ACTIVITIES);
Intent intent = new Intent();
intent.setComponent(new ComponentName(packageName,
ri.activityInfo.name));
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, element);
} catch (NameNotFoundException e) {
ToastHelper.MakeShortText("Whatsapp have not been installed.");
}
How can I make a time delay in Python?
In a single thread I suggest the sleep function:
>>> from time import sleep
>>> sleep(4)
This function actually suspends the processing of the thread in which it is called by the operating system, allowing other threads and processes to execute while it sleeps.
Use it for that purpose, or simply to delay a function from executing. For example:
>>> def party_time():
... print('hooray!')
...
>>> sleep(3); party_time()
hooray!
"hooray!" is printed 3 seconds after I hit Enter.
sleep
with multiple threads and processesAgain, sleep
suspends your thread - it uses next to zero processing power.
To demonstrate, create a script like this (I first attempted this in an interactive Python 3.5 shell, but sub-processes can't find the party_later
function for some reason):
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed
from time import sleep, time
def party_later(kind='', n=''):
sleep(3)
return kind + n + ' party time!: ' + __name__
def main():
with ProcessPoolExecutor() as proc_executor:
with ThreadPoolExecutor() as thread_executor:
start_time = time()
proc_future1 = proc_executor.submit(party_later, kind='proc', n='1')
proc_future2 = proc_executor.submit(party_later, kind='proc', n='2')
thread_future1 = thread_executor.submit(party_later, kind='thread', n='1')
thread_future2 = thread_executor.submit(party_later, kind='thread', n='2')
for f in as_completed([
proc_future1, proc_future2, thread_future1, thread_future2,]):
print(f.result())
end_time = time()
print('total time to execute four 3-sec functions:', end_time - start_time)
if __name__ == '__main__':
main()
Example output from this script:
thread1 party time!: __main__
thread2 party time!: __main__
proc1 party time!: __mp_main__
proc2 party time!: __mp_main__
total time to execute four 3-sec functions: 3.4519670009613037
You can trigger a function to be called at a later time in a separate thread with the Timer
threading object:
>>> from threading import Timer
>>> t = Timer(3, party_time, args=None, kwargs=None)
>>> t.start()
>>>
>>> hooray!
>>>
The blank line illustrates that the function printed to my standard output, and I had to hit Enter to ensure I was on a prompt.
The upside of this method is that while the Timer
thread was waiting, I was able to do other things, in this case, hitting Enter one time - before the function executed (see the first empty prompt).
There isn't a respective object in the multiprocessing library. You can create one, but it probably doesn't exist for a reason. A sub-thread makes a lot more sense for a simple timer than a whole new subprocess.
What is the best approach to do this JAVA?
I would personally NOT use Axis 2, even for client side development only. Here is why I stay away from it:
The only reason Axis is still around is IMO because it's used in Eclipse since ages. Thanks god, this has been fixed in Eclipse Helios and I hope Axis2 will finally die. There are just much better stacks.
I read about SAAJ, looks like that will be more granular level of approach?
To do what?
Is there any other way than using the WSDL2Java tool, to generate the code. Maybe wsimport in another option. What are the pros and cons?
Yes! Prefer a JAX-WS stack like CXF or JAX-WS RI (you might also read about Metro, Metro = JAX-WS RI + WSIT), they are just more elegant, simpler, easier to use. In your case, I would just use JAX-WS RI which is included in Java 6 and thus wsimport
.
Can someone send the links for some good tutorials on these topics?
That's another pro, there are plenty of (good quality) tutorials for JAX-WS, see for example:
What are the options we need to use while generating the code using the WSDL2Java?
No options, use wsimport
:)
Try it: sudo mysql_secure_installation
Work's in Ubuntu 18.04
Check whether your code contains a namespace which the right most part matches your static class name.
Given the a static Bar class, defined on namespace Foo, implementing a method Jump or a property, chances are you are receiving compiler error because there is also another namespace ending on Bar. Yep, fishi stuff ;-)
If that's so, it means your using a Using Bar; and a Bar.Jump() call, therefore one of the following solutions should fit your needs:
In my case, the foollowing compiler error occurred on a EF (Entity Framework) repository project on an Database.SetInitializer() call:
Member 'Database.SetInitializer<MyDatabaseContext>(IDatabaseInitializer<MyDatabaseContext>)' cannot be accessed with an instance reference; qualify it with a type name instead MyProject.ORM
This error arouse when I added a MyProject.ORM.Database namespace, which sufix (Database), as you might noticed, matches Database.SetInitializer class name.
In this, since I have no control on EF's Database static class and I would also like to preserve my custom namespace, I decided fully qualify EF's Database static class with its namepace System.Data.Entity, which resulted on using the following command, which compilation succeed:
System.Data.Entity.Database.SetInitializer<MyDatabaseContext>(MyMigrationStrategy)
Hope it helps
One starting point could be to use this directive (ng-csv) just download the file as csv and that's something excel can understand
http://ngmodules.org/modules/ng-csv
Maybe you can adapt this code (updated link):
http://jsfiddle.net/Sourabh_/5ups6z84/2/
Altough it seems XMLSS (it warns you before opening the file, if you choose to open the file it will open correctly)
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
I tried this: Create a file header.html like
<!-- Meta -->
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<!-- JS -->
<script type="text/javascript" src="js/lib/jquery-1.11.1.min.js" ></script>
<script type="text/javascript" src="js/lib/angular.min.js"></script>
<script type="text/javascript" src="js/lib/angular-resource.min.js"></script>
<script type="text/javascript" src="js/lib/angular-route.min.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css">
<title>Your application</title>
Now include header.html in your HTML pages like:
<head>
<script type="text/javascript" src="js/lib/jquery-1.11.1.min.js" ></script>
<script>
$(function(){ $("head").load("header.html") });
</script>
</head>
Works perfectly fine.
what error do you get is it a SmtpFailedrecipientException? if so you can check the innerexceptions list and view the StatusCode to get more information. the link below has some good information
Edit for the new information
Thisis a problem with finding your SMTP server from what I can see, though you say that it only happens on some emails. Are you using more than one smtp server and if so maybe you can tract the issue down to one in particular, if not it may be that the speed/amount of emails you are sending is causing your smtp server some issue.
Agile and Scrum are terms used in project management. The Agile methodology employs incremental and iterative work beats that are also called sprints. Scrum, on the other hand is the type of agile approach that is used in software development.
Agile is the practice and Scrum is the process to following this practice same as eXtreme Programming (XP) and Kanban are the alternative process to following Agile development practice.
This error message gets triggered when anything is sent before you send HTTP headers (with setcookie
or header
). Common reasons for outputting something before the HTTP headers are:
Accidental whitespace, often at the beginning or end of files, like this:
<?php
// Note the space before "<?php"
?>
To avoid this, simply leave out the closing ?>
- it's not required anyways.
3F 3C
. You can safely remove the BOM EF BB BF
from the start of files.echo
, printf
, readfile
, passthru
, code before <?
etc.display_errors
php.ini property is set. Instead of crashing on a programmer mistake, php silently fixes the error and emits a warning. While you can modify the display_errors
or error_reporting configurations, you should rather fix the problem.$_POST['input']
without using empty
or isset
to test whether the input is set), or using an undefined constant instead of a string literal (as in $_POST[input]
, note the missing quotes).Turning on output buffering should make the problem go away; all output after the call to ob_start
is buffered in memory until you release the buffer, e.g. with ob_end_flush
.
However, while output buffering avoids the issues, you should really determine why your application outputs an HTTP body before the HTTP header. That'd be like taking a phone call and discussing your day and the weather before telling the caller that he's got the wrong number.
document.location.reload()
stores the position, see in the docs.
Add additional true
parameter to force reload, but without restoring the position.
document.location.reload(true)
MDN docs:
The forcedReload flag changes how some browsers handle the user's scroll position. Usually reload() restores the scroll position afterward, but forced mode can scroll back to the top of the page, as if window.scrollY === 0.
.htaccess php_value is working only if you use PHP Server API as module of Web server Apache. Use IfModule syntax:
# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
php_value error_reporting 30711
</IfModule>
If you use PHP Server API CGI/FastCGI use
ini_set('error_reporting', 30711);
or
error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE);
in your PHP code, or PHP configuration files .user.ini | php.ini modification:
error_reporting = E_ALL & ~E_STRICT & ~E_NOTICE
on your virtual host, server level.
Working answers are already given but I want to add a check that acts as a fail-safe in case the flask variable is not available. When you use:
var myVariable = {{ flaskvar | tojson }};
if there is an error that causes the variable to be non existent, resulting errors may produce unexpected results. To avoid this:
{% if flaskvar is defined and flaskvar %}
var myVariable = {{ flaskvar | tojson }};
{% endif %}
Some people try to fix it using one way, some the second. Basically, there are 2 issues, which if you check them out & solve both - in 99% it should fix this issue:
Old device simulators located at YOUR_MAC_NAME
(e.g. Macintosh
) -> Users
-> YOUR_USERNAME
(daniel
) -> Library
-> Developer
-> Xcode
-> iOS Device Support
. Leave there, the newest one, as of today this is 13.2.3 (17B111)
, but in future it'll change. The highest number (here 13.2.3
) of the iOS version indicates that it's newer.
After this list your devices in Terminal
by running xcrun simctl list devices
. Many of them might be unavailable
, therefore delete them by running xcrun simctl delete unavailable
. It'll free some space as well. To be sure that everything is fine check it again by running xcrun simctl list devices
. You should see devices only from the newest version (here 13.2.3
) like the screenshot below shows.
As a bonus which is slightly less relevant to this question, but still free's some space. Go to YOUR_MAC_NAME
(e.g. Macintosh
) -> Users
-> YOUR_USERNAME
(e.g. daniel
) -> Library
-> Developer
-> Xcode
-> Archives
. You'll see many archived deployed application, most probably you don't need all of them. Try to delete these ones, which are not being used anymore.
Using these 2 methods and the bonus method I was able to get extra 15 GB of space on my Mac.
PS. Simply deleting simulators from Xcode by going to Xcode
-> Window
-> Devices and Simulators
-> Simulators
(or simply CMD
+ SHIFT
+ 2
when using keyboard shortcut) and deleting it there won't help. You really need to go for the described steps.
Just go through the below code.
SmtpClient smtpClient = new SmtpClient("mail.MyWebsiteDomainName.com", 25);
smtpClient.Credentials = new System.Net.NetworkCredential("[email protected]", "myIDPassword");
// smtpClient.UseDefaultCredentials = true; // uncomment if you don't want to use the network credentials
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();
//Setting From , To and CC
mail.From = new MailAddress("info@MyWebsiteDomainName", "MyWeb Site");
mail.To.Add(new MailAddress("info@MyWebsiteDomainName"));
mail.CC.Add(new MailAddress("[email protected]"));
smtpClient.Send(mail);
Starting with C# 8.0
, you can create and consume streams asynchronously.
private async void button1_Click(object sender, EventArgs e)
{
IAsyncEnumerable<int> enumerable = GenerateSequence();
await foreach (var i in enumerable)
{
Debug.WriteLine(i);
}
}
public static async IAsyncEnumerable<int> GenerateSequence()
{
for (int i = 0; i < 20; i++)
{
await Task.Delay(100);
yield return i;
}
}
In your R script, called test.R
:
args <- commandArgs(trailingOnly = F)
myargument <- args[length(args)]
myargument <- sub("-","",myargument)
print(myargument)
q(save="no")
From the command line run:
R CMD BATCH -4 test.R
Your output file, test.Rout, will show that the argument 4
has been successfully passed to R:
cat test.Rout
> args <- commandArgs(trailingOnly = F)
> myargument <- args[length(args)]
> myargument <- sub("-","",myargument)
> print(myargument)
[1] "4"
> q(save="no")
> proc.time()
user system elapsed
0.222 0.022 0.236
If you are having trouble changing it to a percentage, then see this answer.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="81dp">
<android.support.constraint.Guideline
android:id="@+id/guideline8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5"/>
<TextView
android:id="@+id/textView6"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="TextView"
app:layout_constraintBottom_toTopOf="@+id/guideline8"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</android.support.constraint.ConstraintLayout>
Please note instead of
public TomcatEmbeddedServletContainerFactory tomcatFactory()
I had to use the following method signature
public EmbeddedServletContainerFactory embeddedServletContainerFactory()
it works for me. if you want to enable future time for choose, you have to delete maximum date. You need to to do like followings.
btnDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
});
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
dialog.getDatePicker().setMaxDate(c.getTimeInMillis());
return dialog;
}
public void onDateSet(DatePicker view, int year, int month, int day) {
btnDate.setText(ConverterDate.ConvertDate(year, month + 1, day));
}
}
Various forms depending on type of List, for Array List:
val myList = mutableListOf<Kolory>()
// or more specifically use the helper for a specific list type
val myList = arrayListOf<Kolory>()
For LinkedList:
val myList = linkedListOf<Kolory>()
// same as
val myList: MutableList<Kolory> = linkedListOf()
For other list types, will be assumed Mutable if you construct them directly:
val myList = ArrayList<Kolory>()
// or
val myList = LinkedList<Kolory>()
This holds true for anything implementing the List
interface (i.e. other collections libraries).
No need to repeat the type on the left side if the list is already Mutable. Or only if you want to treat them as read-only, for example:
val myList: List<Kolory> = ArrayList()
As per Java Doc Collection is:
The root interface in the collection hierarchy. A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. The JDK does not provide any direct implementations of this interface: it provides implementations of more specific subinterfaces like Set and List. This interface is typically used to pass collections around and manipulate them where maximum generality is desired.
Where as Collections is:
This class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by a specified collection, and a few other odds and ends.
I've recently found even more interesting way to create any ValueNode
or ContainerNode
(Jackson v2.3).
ObjectNode node = JsonNodeFactory.instance.objectNode();