Internally, Chrome maintains a stack, where $0 is the selected element, $1 is the element that was last selected, $2 would be the one that was selected before $1 and so on.
Here are some of its applications:
After you've run the Inspect by Name, select all the locations, and make use of the Apply quick fixes to all the problems drop-down, and use either (or both) of Delete unused parameter(s) and Safe Delete.
Don't forget to hit Do Refactor afterwards.
Then you'll need to run another analysis, as the refactored code will no doubt reveal more unused declarations.
You should use the equals
method since this is implemented to perform the comparison you want. toString()
itself uses an iterator just like equals
but it is a more inefficient approach. Additionally, as @Teepeemm pointed out, toString
is affected by order of elements (basically iterator return order) hence is not guaranteed to provide the same output for 2 different maps (especially if we compare two different maps).
Note/Warning: Your question and my answer assume that classes implementing the map interface respect expected toString
and equals
behavior. The default java classes do so, but a custom map class needs to be examined to verify expected behavior.
See: http://docs.oracle.com/javase/7/docs/api/java/util/Map.html
boolean equals(Object o)
Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings. More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.
Additionally, java itself takes care of iterating through all elements and making the comparison so you don't have to. Have a look at the implementation of AbstractMap
which is used by classes such as HashMap
:
// Comparison and hashing
/**
* Compares the specified object with this map for equality. Returns
* <tt>true</tt> if the given object is also a map and the two maps
* represent the same mappings. More formally, two maps <tt>m1</tt> and
* <tt>m2</tt> represent the same mappings if
* <tt>m1.entrySet().equals(m2.entrySet())</tt>. This ensures that the
* <tt>equals</tt> method works properly across different implementations
* of the <tt>Map</tt> interface.
*
* <p>This implementation first checks if the specified object is this map;
* if so it returns <tt>true</tt>. Then, it checks if the specified
* object is a map whose size is identical to the size of this map; if
* not, it returns <tt>false</tt>. If so, it iterates over this map's
* <tt>entrySet</tt> collection, and checks that the specified map
* contains each mapping that this map contains. If the specified map
* fails to contain such a mapping, <tt>false</tt> is returned. If the
* iteration completes, <tt>true</tt> is returned.
*
* @param o object to be compared for equality with this map
* @return <tt>true</tt> if the specified object is equal to this map
*/
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Map))
return false;
Map<K,V> m = (Map<K,V>) o;
if (m.size() != size())
return false;
try {
Iterator<Entry<K,V>> i = entrySet().iterator();
while (i.hasNext()) {
Entry<K,V> e = i.next();
K key = e.getKey();
V value = e.getValue();
if (value == null) {
if (!(m.get(key)==null && m.containsKey(key)))
return false;
} else {
if (!value.equals(m.get(key)))
return false;
}
}
} catch (ClassCastException unused) {
return false;
} catch (NullPointerException unused) {
return false;
}
return true;
}
toString
fails miserably when comparing a TreeMap
and HashMap
though equals
does compare contents correctly.
Code:
public static void main(String args[]) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("2", "whatever2");
map.put("1", "whatever1");
TreeMap<String, Object> map2 = new TreeMap<String, Object>();
map2.put("2", "whatever2");
map2.put("1", "whatever1");
System.out.println("Are maps equal (using equals):" + map.equals(map2));
System.out.println("Are maps equal (using toString().equals()):"
+ map.toString().equals(map2.toString()));
System.out.println("Map1:"+map.toString());
System.out.println("Map2:"+map2.toString());
}
Output:
Are maps equal (using equals):true
Are maps equal (using toString().equals()):false
Map1:{2=whatever2, 1=whatever1}
Map2:{1=whatever1, 2=whatever2}
You have to catch the error just as you're already doing for your save()
call and since you're handling multiple errors here, you can try
multiple calls sequentially in a single do-catch block, like so:
func deleteAccountDetail() {
let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
let request = NSFetchRequest()
request.entity = entityDescription
do {
let fetchedEntities = try self.Context!.executeFetchRequest(request) as! [AccountDetail]
for entity in fetchedEntities {
self.Context!.deleteObject(entity)
}
try self.Context!.save()
} catch {
print(error)
}
}
Or as @bames53 pointed out in the comments below, it is often better practice not to catch the error where it was thrown. You can mark the method as throws
then try
to call the method. For example:
func deleteAccountDetail() throws {
let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
let request = NSFetchRequest()
request.entity = entityDescription
let fetchedEntities = try Context.executeFetchRequest(request) as! [AccountDetail]
for entity in fetchedEntities {
self.Context!.deleteObject(entity)
}
try self.Context!.save()
}
The third-party breakable
package is one possible alternative
https://github.com/erikerlandson/breakable
Example code:
scala> import com.manyangled.breakable._
import com.manyangled.breakable._
scala> val bkb2 = for {
| (x, xLab) <- Stream.from(0).breakable // create breakable sequence with a method
| (y, yLab) <- breakable(Stream.from(0)) // create with a function
| if (x % 2 == 1) continue(xLab) // continue to next in outer "x" loop
| if (y % 2 == 0) continue(yLab) // continue to next in inner "y" loop
| if (x > 10) break(xLab) // break the outer "x" loop
| if (y > x) break(yLab) // break the inner "y" loop
| } yield (x, y)
bkb2: com.manyangled.breakable.Breakable[(Int, Int)] = com.manyangled.breakable.Breakable@34dc53d2
scala> bkb2.toVector
res0: Vector[(Int, Int)] = Vector((2,1), (4,1), (4,3), (6,1), (6,3), (6,5), (8,1), (8,3), (8,5), (8,7), (10,1), (10,3), (10,5), (10,7), (10,9))
A couple of answers that should work above but this is how i would write it.
Also, i wouldn't declare controllers inside templates. It's better to declare them on your routes imo.
add-text.tpl.html
<div ng-controller="myController">
<form ng-submit="addText(myText)">
<input type="text" placeholder="Let's Go" ng-model="myText">
<button type="submit">Add</button>
</form>
<ul>
<li ng-repeat="text in arrayText">{{ text }}</li>
</ul>
</div>
app.js
(function() {
function myController($scope) {
$scope.arrayText = ['hello', 'world'];
$scope.addText = function(myText) {
$scope.arrayText.push(myText);
};
}
angular.module('app', [])
.controller('myController', myController);
})();
Since it wasn't yet mentioned here, it may be worth to add one more option, package spverbatim
(no syntax highlighting):
\documentclass{article}
\usepackage{spverbatim}
\begin{document}
\begin{spverbatim}
Your code here
\end{spverbatim}
\end{document}
Also, if syntax highlighting is not required, package alltt
:
\documentclass{article}
\usepackage{alltt}
\begin{document}
\begin{alltt}
Your code here
\end{alltt}
\end{document}
If you want your anchor to still appear to be clickable:
$("a").removeAttr("href").css("cursor","pointer");
And if you wanted to remove the href from only anchors with certain attributes (eg ones that just have a hash mark as the href - this can be useful in asp.net)
$("a[href='#']").removeAttr("href").css("cursor","pointer");
Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.
Take this
<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
and place it in phpsqlajax_genxml.php
so your javascript can download the XML file. You are trying to do too many things in the same file.
I think you don't need to update only some specific field. Just update whole data.
@Update query
It is a given query basically. No need to make some new query.
@Dao
interface MemoDao {
@Insert
suspend fun insert(memo: Memo)
@Delete
suspend fun delete(memo: Memo)
@Update
suspend fun update(memo: Memo)
}
Memo.class
@Entity
data class Memo (
@PrimaryKey(autoGenerate = true) val id: Int,
@ColumnInfo(name = "title") val title: String?,
@ColumnInfo(name = "content") val content: String?,
@ColumnInfo(name = "photo") val photo: List<ByteArray>?
)
Only thing you need to know is 'id'. For instance, if you want to update only 'title', you can reuse 'content' and 'photo' from already inserted data. In real code, use like this
val memo = Memo(id, title, content, byteArrayList)
memoViewModel.update(memo)
One can also do this with a compact version of @TomAugspurger's answer, like so:
df = df1.merge(df2, how='left', on=['Year', 'Week', 'Colour']).merge(df3[['Week', 'Colour', 'Val3']], how='left', on=['Week', 'Colour'])
EDIT:
Forgot to say that this solution is in pure js, the only thing you need is a browser that supports promises https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Promise
For those who still needs to accomplish such, I've written my own solution that combines promises with timeouts.
Code:
/*
class: Geolocalizer
- Handles location triangulation and calculations.
-- Returns various prototypes to fetch position from strings or coords or dragons or whatever.
*/
var Geolocalizer = function () {
this.queue = []; // queue handler..
this.resolved = [];
this.geolocalizer = new google.maps.Geocoder();
};
Geolocalizer.prototype = {
/*
@fn: Localize
@scope: resolve single or multiple queued requests.
@params: <array> needles
@returns: <deferred> object
*/
Localize: function ( needles ) {
var that = this;
// Enqueue the needles.
for ( var i = 0; i < needles.length; i++ ) {
this.queue.push(needles[i]);
}
// return a promise and resolve it after every element have been fetched (either with success or failure), then reset the queue.
return new Promise (
function (resolve, reject) {
that.resolveQueueElements().then(function(resolved){
resolve(resolved);
that.queue = [];
that.resolved = [];
});
}
);
},
/*
@fn: resolveQueueElements
@scope: resolve queue elements.
@returns: <deferred> object (promise)
*/
resolveQueueElements: function (callback) {
var that = this;
return new Promise(
function(resolve, reject) {
// Loop the queue and resolve each element.
// Prevent QUERY_LIMIT by delaying actions by one second.
(function loopWithDelay(such, queue, i){
console.log("Attempting the resolution of " +queue[i-1]);
setTimeout(function(){
such.find(queue[i-1], function(res){
such.resolved.push(res);
});
if (--i) {
loopWithDelay(such,queue,i);
}
}, 1000);
})(that, that.queue, that.queue.length);
// Check every second if the queue has been cleared.
var it = setInterval(function(){
if (that.queue.length == that.resolved.length) {
resolve(that.resolved);
clearInterval(it);
}
}, 1000);
}
);
},
/*
@fn: find
@scope: resolve an address from string
@params: <string> s, <fn> Callback
*/
find: function (s, callback) {
this.geolocalizer.geocode({
"address": s
}, function(res, status){
if (status == google.maps.GeocoderStatus.OK) {
var r = {
originalString: s,
lat: res[0].geometry.location.lat(),
lng: res[0].geometry.location.lng()
};
callback(r);
}
else {
callback(undefined);
console.log(status);
console.log("could not locate " + s);
}
});
}
};
Please note that it's just a part of a bigger library I wrote to handle google maps stuff, hence comments may be confusing.
Usage is quite simple, the approach, however, is slightly different: instead of looping and resolving one address at a time, you will need to pass an array of addresses to the class and it will handle the search by itself, returning a promise which, when resolved, returns an array containing all the resolved (and unresolved) address.
Example:
var myAmazingGeo = new Geolocalizer();
var locations = ["Italy","California","Dragons are thugs...","China","Georgia"];
myAmazingGeo.Localize(locations).then(function(res){
console.log(res);
});
Console output:
Attempting the resolution of Georgia
Attempting the resolution of China
Attempting the resolution of Dragons are thugs...
Attempting the resolution of California
ZERO_RESULTS
could not locate Dragons are thugs...
Attempting the resolution of Italy
Object returned:
The whole magic happens here:
(function loopWithDelay(such, queue, i){
console.log("Attempting the resolution of " +queue[i-1]);
setTimeout(function(){
such.find(queue[i-1], function(res){
such.resolved.push(res);
});
if (--i) {
loopWithDelay(such,queue,i);
}
}, 750);
})(that, that.queue, that.queue.length);
Basically, it loops every item with a delay of 750 milliseconds between each of them, hence every 750 milliseconds an address is controlled.
I've made some further testings and I've found out that even at 700 milliseconds I was sometimes getting the QUERY_LIMIT error, while with 750 I haven't had any issue at all.
In any case, feel free to edit the 750 above if you feel you are safe by handling a lower delay.
Hope this helps someone in the near future ;)
A dialog is always created and displayed as a part of an Activity. You need to pass in an Activity context instead of the Application context.
http://developer.android.com/guide/topics/ui/dialogs.html#ShowingADialog
just note, The different between the methods are, if the header is not exist
request.headers.get('your-header-name')
will return None
or no exception, so you can use it like
if request.headers.get('your-header-name'):
....
but the following will throw an error
if request.headers['your-header-name'] # KeyError: 'your-header-name'
....
You can handle it by
if 'your-header-name' in request.headers:
customHeader = request.headers['your-header-name']
....
If you have hashes '#' in your URL, all the solutions here do not work. This is the only solution that worked for me.
var hrefa = window.location.href.split("#")[1];
var hrefb = window.location.href.split("#")[2];
window.location.href = window.location.pathname + window.location.search + '&x=x#' + hrefa + '#' + hrefb;
The URL has to be different for it to reload if you have a hash. The &x=x does that here. Just substitute this for something you can ignore. THis is abit of a hack, unable to find a better solution..
Tested in Firefox.
what about using the official API?
According to the API doc:
DESTROY: Removes the datepicker functionality completely. This will return the element back to its pre-init state.
Use:
$("#txtSearch").datepicker("destroy");
to restore the input to its normal behaviour and
$("#txtSearch").datepicker(/*options*/);
again to show the datapicker again.
If you are using the version 1.21.1:
Now, just close the active tab pane and you are done.
This can occur on android too not just computers. Was browsing using Kiwi when the site I was on began to endlessly redirect so I cut net access to close it out and noticed my phone had DL'd something f.txt
in my downloaded files.
Deleted it and didn't open.
Native JSON support has been included in PHP since 5.2 in the form of methods json_encode()
and json_decode()
. You would use the first to output a PHP variable in JSON.
USE AdventureWorks2012;
GO
IF OBJECT_ID(N't6', N'U') IS NOT NULL
DROP TABLE t6;
GO
IF OBJECT_ID(N't7', N'U') IS NOT NULL
DROP TABLE t7;
GO
CREATE TABLE t6(id int IDENTITY);
CREATE TABLE t7(id int IDENTITY(100,1));
GO
CREATE TRIGGER t6ins ON t6 FOR INSERT
AS
BEGIN
INSERT t7 DEFAULT VALUES
END;
GO
--End of trigger definition
SELECT id FROM t6;
--IDs empty.
SELECT id FROM t7;
--ID is empty.
--Do the following in Session 1
INSERT t6 DEFAULT VALUES;
SELECT @@IDENTITY;
/*Returns the value 100. This was inserted by the trigger.*/
SELECT SCOPE_IDENTITY();
/* Returns the value 1. This was inserted by the
INSERT statement two statements before this query.*/
SELECT IDENT_CURRENT('t7');
/* Returns value inserted into t7, that is in the trigger.*/
SELECT IDENT_CURRENT('t6');
/* Returns value inserted into t6. This was the INSERT statement four statements before this query.*/
-- Do the following in Session 2.
SELECT @@IDENTITY;
/* Returns NULL because there has been no INSERT action
up to this point in this session.*/
SELECT SCOPE_IDENTITY();
/* Returns NULL because there has been no INSERT action
up to this point in this scope in this session.*/
SELECT IDENT_CURRENT('t7');
/* Returns the last value inserted into t7.*/
Instead of os.path.isfile
, suggested by others, I suggest using os.path.exists
, which checks for anything with that name, not just whether it is a regular file.
Thus:
if not os.path.exists(filename):
file(filename, 'w').close()
Alternatively:
file(filename, 'w+').close()
The latter will create the file if it exists, but not otherwise. It will, however, fail if the file exists, but you don't have permission to write to it. That's why I prefer the first solution.
In general, questions regarding "magic" variables in Perl can be answered by looking in the Perl predefined variables documentation a la:
perldoc perlvar
However, when you search this documentation for $1, etc., you'll find references in a number of places except the section on these "digit" variables. You have to search for
$<digits>
I would have added this to Brian's answer either by commenting or editing, but I don't have enough rep. If someone adds this I'll remove this answer.
First of all, as others mentioned, you will be using the "array_search()" & the "unset()" methodsas shown below:-
<?php
$arrayDummy = array( 'aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg' );
unset( $arrayDummy[array_search( 'dddd', $arrayDummy )] ); // Index 3 is getting unset here.
print_r( $arrayDummy ); // This will show the indexes as 0, 1, 2, 4, 5, 6.
?>
Now to re-index the same array, without sorting any of the array values, you will need to use the "array_values()" method as shown below:-
<?php
$arrayDummy = array_values( $arrayDummy );
print_r( $arrayDummy ); // Now, you will see the indexes as 0, 1, 2, 3, 4, 5.
?>
Hope it helps.
I found some issue about that kind of error
# ===============================
# = DATA SOURCE
# ===============================
# Set here configurations for the database connection
# Connection url for the database please let me know "[email protected]"
spring.datasource.url = jdbc:mysql://localhost:3306/bookstoreapiabc
# Username and secret
spring.datasource.username = root
spring.datasource.password =
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# ===============================
# = JPA / HIBERNATE
# ===============================
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager).
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update): with "update" the database
# schema will be automatically updated accordingly to java entities found in
# the project
spring.jpa.hibernate.ddl-auto = update
# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
Issue no 2.
Your local server has two database server and those database server conflict. this conflict like this mysql server & xampp or lampp or wamp server. Please one of the database like mysql server because xampp or lampp server automatically install mysql server on this machine
You can use npm shrinkwrap functionality, in order to override any dependency or sub-dependency.
I've just done this in a grunt
project of ours. We needed a newer version of connect, since 2.7.3
. was causing trouble for us. So I created a file named npm-shrinkwrap.json
:
{
"dependencies": {
"grunt-contrib-connect": {
"version": "0.3.0",
"from": "[email protected]",
"dependencies": {
"connect": {
"version": "2.8.1",
"from": "connect@~2.7.3"
}
}
}
}
}
npm
should automatically pick it up while doing the install for the project.
(See: https://nodejs.org/en/blog/npm/managing-node-js-dependencies-with-shrinkwrap/)
It's good that you wrote out your original code. I have another way to code this concept of reversing an integer. I'm only going to allow up to 10 digits. However, I am going to make the assumption that the user will not enter a zero.
if((inputNum <= 999999999)&&(inputNum > 0 ))
{
System.out.print("Your number reversed is: ");
do
{
endInt = inputNum % 10; //to get the last digit of the number
inputNum /= 10;
system.out.print(endInt);
}
While(inputNum != 0);
System.out.println("");
}
else
System.out.println("You used an incorrect number of integers.\n");
System.out.println("Program end");
Update for 2020 - BinaryPrimitives
should now be preferred over BitConverter
. It provides endian-specific APIs, and is less allocatey.
byte[] bytes = BitConverter.GetBytes(i);
although note also that you might want to check BitConverter.IsLittleEndian
to see which way around that is going to appear!
Note that if you are doing this repeatedly you might want to avoid all those short-lived array allocations by writing it yourself via either shift operations (>>
/ <<
), or by using unsafe
code. Shift operations also have the advantage that they aren't affected by your platform's endianness; you always get the bytes in the order you expect them.
The answer anhic gave can be very inefficient if you have a large database and the attribute name is present only in some of the documents.
To improve efficiency you can add a $match to the aggregation.
db.collection.aggregate(
{"$match": {"name" :{ "$ne" : null } } },
{"$group" : {"_id": "$name", "count": { "$sum": 1 } } },
{"$match": {"count" : {"$gt": 1} } },
{"$project": {"name" : "$_id", "_id" : 0} }
)
Most of answers works beside a fact, that when u scroll to the bottom, listener is triggered several times, which in my case is undesirable. To avoid this behavior I've added flag scrollPositionChanged that checks if scroll position even changed before calling method once again.
public class EndDetectingScrollView extends ScrollView {
private boolean scrollPositionChanged = true;
private ScrollEndingListener scrollEndingListener;
public interface ScrollEndingListener {
void onScrolledToEnd();
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
View view = this.getChildAt(this.getChildCount() - 1);
int diff = (view.getBottom() - (this.getHeight() + this.getScrollY()));
if (diff <= 0) {
if (scrollPositionChanged) {
scrollPositionChanged = false;
if (scrollEndingListener != null) {
scrollEndingListener.onScrolledToEnd();
}
}
} else {
scrollPositionChanged = true;
}
}
public void setScrollEndingListener(ScrollEndingListener scrollEndingListener) {
this.scrollEndingListener = scrollEndingListener;
}
}
Then just set listener
scrollView.setScrollEndingListener(new EndDetectingScrollView.ScrollEndingListener() {
@Override
public void onScrolledToEnd() {
//do your stuff here
}
});
You may do the same thing if u do in like
scrollView.getViewTreeObserver().addOnScrollChangedListener(...)
but you have to provide flag from class your adding this listener.
Here is what I find useful:
def one_hot(a, num_classes):
return np.squeeze(np.eye(num_classes)[a.reshape(-1)])
Here num_classes
stands for number of classes you have. So if you have a
vector with shape of (10000,) this function transforms it to (10000,C). Note that a
is zero-indexed, i.e. one_hot(np.array([0, 1]), 2)
will give [[1, 0], [0, 1]]
.
Exactly what you wanted to have I believe.
PS: the source is Sequence models - deeplearning.ai
$.browser
was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.
In case you don't want to get mad with spaces in arguments and want to use variables try this:
objshell.run "cscript ""99 Writelog.vbs"" /r:" & r & " /f:""" & wscript.scriptname & """ /c:""" & c & ""
where
r=123
c="Whatever comment you like"
From a DateTime
, you can use .TimeOfDay
- but that gives you a TimeSpan
representing the time into the day (10 hours).
I will go with ParentNode.children:
As it provides namedItem
method that allows me directly to get one of the children elements without looping through all children or avoiding to use getElementById
etc.
e.g.
ParentNode.children.namedItem('ChildElement-ID'); // JS
ref.current.children.namedItem('ChildElement-ID'); // React
this.$refs.ref.children.namedItem('ChildElement-ID'); // Vue
I will go with Node.childNodes:
As it provides forEach
method when I work with window.IntersectionObserver
e.g.
nodeList.forEach((node) => { observer.observe(node) })
// IE11 does not support forEach on nodeList, but easy to be polyfilled.
On Chrome 83
Node.childNodes provides
entries
,forEach
,item
,keys
,length
andvalues
ParentNode.children provides
item
,length
andnamedItem
Use ClassLoader#getResource()
instead if its URI represents a valid local disk file system path.
URL resource = classLoader.getResource("resource.ext");
File file = new File(resource.toURI());
FileInputStream input = new FileInputStream(file);
// ...
If it doesn't (e.g. JAR), then your best bet is to copy it into a temporary file.
Path temp = Files.createTempFile("resource-", ".ext");
Files.copy(classLoader.getResourceAsStream("resource.ext"), temp, StandardCopyOption.REPLACE_EXISTING);
FileInputStream input = new FileInputStream(temp.toFile());
// ...
That said, I really don't see any benefit of doing so, or it must be required by a poor helper class/method which requires FileInputStream
instead of InputStream
. If you can, just fix the API to ask for an InputStream
instead. If it's a 3rd party one, by all means report it as a bug. I'd in this specific case also put question marks around the remainder of that API.
By default Spring OAuth requires basic HTTP authentication. If you want to switch it off with Java based configuration, you have to allow form authentication for clients like this:
@Configuration
@EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.allowFormAuthenticationForClients();
}
}
The answer from Alexander refers to complete docs...
Your simple example from the question simply prints out these values with 2 digits - appending leading 0 if necessary.
Regarding the internal structure of a Python long, check sys.int_info (or sys.long_info for Python 2.7).
>>> import sys
>>> sys.int_info
sys.int_info(bits_per_digit=30, sizeof_digit=4)
Python either stores 30 bits into 4 bytes (most 64-bit systems) or 15 bits into 2 bytes (most 32-bit systems). Comparing the actual memory usage with calculated values, I get
>>> import math, sys
>>> a=0
>>> sys.getsizeof(a)
24
>>> a=2**100
>>> sys.getsizeof(a)
40
>>> a=2**1000
>>> sys.getsizeof(a)
160
>>> 24+4*math.ceil(100/30)
40
>>> 24+4*math.ceil(1000/30)
160
There are 24 bytes of overhead for 0 since no bits are stored. The memory requirements for larger values matches the calculated values.
If your numbers are so large that you are concerned about the 6.25% unused bits, you should probably look at the gmpy2 library. The internal representation uses all available bits and computations are significantly faster for large values (say, greater than 100 digits).
If your application is making heavy use of Date and Calendar objects, you really should use Joda Time, because java.util.Date
is mutable. java.util.Calendar
has performance problems when its fields get updated, and is clunky for datetime arithmetic.
--> Use this to find time gap between two dates in Swift(With two Strings).
func timeGapBetweenDates(previousDate : String,currentDate : String)
{
let dateString1 = previousDate
let dateString2 = currentDate
let Dateformatter = DateFormatter()
Dateformatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date1 = Dateformatter.date(from: dateString1)
let date2 = Dateformatter.date(from: dateString2)
let distanceBetweenDates: TimeInterval? = date2?.timeIntervalSince(date1!)
let secondsInAnHour: Double = 3600
let minsInAnHour: Double = 60
let secondsInDays: Double = 86400
let secondsInWeek: Double = 604800
let secondsInMonths : Double = 2592000
let secondsInYears : Double = 31104000
let minBetweenDates = Int((distanceBetweenDates! / minsInAnHour))
let hoursBetweenDates = Int((distanceBetweenDates! / secondsInAnHour))
let daysBetweenDates = Int((distanceBetweenDates! / secondsInDays))
let weekBetweenDates = Int((distanceBetweenDates! / secondsInWeek))
let monthsbetweenDates = Int((distanceBetweenDates! / secondsInMonths))
let yearbetweenDates = Int((distanceBetweenDates! / secondsInYears))
let secbetweenDates = Int(distanceBetweenDates!)
if yearbetweenDates > 0
{
print(yearbetweenDates,"years")//0 years
}
else if monthsbetweenDates > 0
{
print(monthsbetweenDates,"months")//0 months
}
else if weekBetweenDates > 0
{
print(weekBetweenDates,"weeks")//0 weeks
}
else if daysBetweenDates > 0
{
print(daysBetweenDates,"days")//5 days
}
else if hoursBetweenDates > 0
{
print(hoursBetweenDates,"hours")//120 hours
}
else if minBetweenDates > 0
{
print(minBetweenDates,"minutes")//7200 minutes
}
else if secbetweenDates > 0
{
print(secbetweenDates,"seconds")//seconds
}
}
Generating locales
Missing locales are generated with locale-gen:
locale-gen en_US.UTF-8
Alternatively a locale file can be created manually with localedef:[1]
localedef -i en_US -f UTF-8 en_US.UTF-8
Setting Locale Settings
The locale settings can be set (to en_US.UTF-8
in the example) as follows:
export LANGUAGE=en_US.UTF-8
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
locale-gen en_US.UTF-8
dpkg-reconfigure locales
The dpkg-reconfigure locales
command will open a dialog under Debian for selecting the desired locale. This dialog will not appear under Ubuntu. The Configure Locales in Ubuntu article shows how to find the information regarding Ubuntu.
Always remember one thing we can not apply margin vertically to inline elements ,if you want to apply then change its display type to block or inline block.for example span{display:inline-block;}
Follow the below steps:
Add to sending request header Content-Type
field:
axios.post(`/Order/`, orderId,
{
headers: {'Content-Type': 'application/json'}
})
Every data (simple or complex type) sent with axios should be placed without any extra brackets (axios.post('/Order/', orderId, ...)
).
WARNING! There is one exception for string
type - stringify it before send (axios.post('/Order/', JSON.stringify(address), ...)
).
Add method to controller:
[HttpPost]
public async Task<IActionResult> Post([FromBody]int orderId)
{
return Ok();
}
If you are using Xcode 6 and designing for iOS 8, none of these solutions are correct. To get your iPhone-only views to be sized correctly, don't turn off size classes, don't turn off inferred metrics, and don't set constraints (yet). Instead, use the size class control, which is an easy to miss text button at the bottom of Interface Builder that initially reads "wAny hAny".
Click the button, and choose Compact Width, Regular Height. This resize your views and cover all iPhone portrait orientations. Apple's docs here: https://developer.apple.com/library/ios/recipes/xcode_help-IB_adaptive_sizes/chapters/SelectingASizeClass.html or search on "Selecting a Size Class in Interface Builder"
To Answer your first question, Jenkins variables are case sensitive. However, if you are writing a windows batch script, they are case insensitive, because Windows doesn't care about the case.
Since you are not very clear about your setup, let's make the assumption that you are using an ant build step to fire up your ant task. Have a look at the Jenkins documentation (same page that Adarsh gave you, but different chapter) for an example on how to make Jenkins variables available to your ant task.
EDIT:
Hence, I will need to access the environmental variable ${BUILD_NUMBER} to construct the URL.
Why don't you use $BUILD_URL
then? Isn't it available in the extended email plugin?
No need to add permission and do tricks. Just use below text in your main layout.
android:keepScreenOn="true"
this is a basic step for learn:
import os, stat, sys
import time
dirpath = sys.argv[1] if len(sys.argv) == 2 else r'.'
listdir = os.listdir(dirpath)
for i in listdir:
os.chdir(dirpath)
data_001 = os.path.realpath(i)
listdir_stat1 = os.stat(data_001)
listdir_stat2 = ((os.stat(data_001), data_001))
print time.ctime(listdir_stat1.st_ctime), data_001
If you are using Spring Framework with application.yml
and having trouble to make the test find the SQL file on the INIT
property, you can use the classpath:
notation.
For example, if you have a init.sql
SQL file on the src/test/resources
, just use:
url=jdbc:h2:~/test;INIT=RUNSCRIPT FROM 'classpath:init.sql';DB_CLOSE_DELAY=-1;
It took me months of googling to find a solution for this issue. You don't need to install a virtual environment running a 32-bit version of Windows to run a program with a 16-bit installer on 64-bit Windows. If the program itself is 32-bit, and just the installer is 16-bit, here's your answer.
There are ways to modify a 16-bit installation program to make it 32-bit so it will install on 64-bit Windows 7. I found the solution on this site:
http://www.reactos.org/forum/viewtopic.php?f=22&t=10988
In my case, the installation program was InstallShield 5.X. The issue was that the setup.exe program used by InstallShield 5.X is 16-bit. First I extracted the installation program contents (changed the extension from .exe to .zip, opened it and extracted). I then replaced the original 16-bit setup.exe, located in the disk1 folder, with InstallShield's 32-bit version of setup.exe (download this file from the site referenced in the above link). Then I just ran the new 32-bit setup.exe in disk1 to start the installation and my program installed and runs perfectly on 64-bit Windows.
You can also repackage this modified installation, so it can be distributed as an installation program, using a free program like Inno Setup 5.
All the classes including the abstract classes can have constructors.Abstract class constructors will be called when its concrete subclass will be instantiated
Thought I would mention this because it took a while for me to fix this issue and I couldn't find the answer anywhere on SO. The code I was working on worked for a co-worker but not for me (I was getting this same error). It worked for me in Chrome, but not in Edge.
I was able to get it working by clearing the cache in Edge.
This may not be the answer to this specific question, but I thought I would mention it in case it saves someone else a little time.
The difference between Func
and Action
is simply whether you want the delegate to return a value (use Func
) or not (use Action
).
Func
is probably most commonly used in LINQ - for example in projections:
list.Select(x => x.SomeProperty)
or filtering:
list.Where(x => x.SomeValue == someOtherValue)
or key selection:
list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)
Action
is more commonly used for things like List<T>.ForEach
: execute the given action for each item in the list. I use this less often than Func
, although I do sometimes use the parameterless version for things like Control.BeginInvoke
and Dispatcher.BeginInvoke
.
Predicate
is just a special cased Func<T, bool>
really, introduced before all of the Func
and most of the Action
delegates came along. I suspect that if we'd already had Func
and Action
in their various guises, Predicate
wouldn't have been introduced... although it does impart a certain meaning to the use of the delegate, whereas Func
and Action
are used for widely disparate purposes.
Predicate
is mostly used in List<T>
for methods like FindAll
and RemoveAll
.
This is one of the common issues with IE and fix for this is simple. Add .focus() twice to the input.
Fix :-
function FocusOnInput() {
var element = document.getElementById('txtContactMobileNo');
element.focus();
setTimeout(function () { element.focus(); }, 1);
}
And call FocusOnInput() on $(document).ready(function () {.....};
If you want to move the position of the legend please use the following code:
library(reshape2) # for melt
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
theme(legend.position="bottom")
This should give you the desired result.
If nothing of this helps (my case), you can set it in your pom.xml, like this:
<properties>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
As this cool guy mentioned here: https://stackoverflow.com/a/25888116/1643465
You can get all details by order object.
// Get $order object from order ID
$order = wc_get_order( $order_id );
// Now you have access to (see above)...
if ( $order ) {
// Get Order ID and Key
$order->get_id();
$order->get_order_key();
// Get Order Totals $0.00
$order->get_formatted_order_total();
$order->get_cart_tax();
$order->get_currency();
$order->get_discount_tax();
$order->get_discount_to_display();
$order->get_discount_total();
$order->get_fees();
$order->get_formatted_line_subtotal();
$order->get_shipping_tax();
$order->get_shipping_total();
$order->get_subtotal();
$order->get_subtotal_to_display();
$order->get_tax_location();
$order->get_tax_totals();
$order->get_taxes();
$order->get_total();
$order->get_total_discount();
$order->get_total_tax();
$order->get_total_refunded();
$order->get_total_tax_refunded();
$order->get_total_shipping_refunded();
$order->get_item_count_refunded();
$order->get_total_qty_refunded();
$order->get_qty_refunded_for_item();
$order->get_total_refunded_for_item();
$order->get_tax_refunded_for_item();
$order->get_total_tax_refunded_by_rate_id();
$order->get_remaining_refund_amount();
}
On GNU versions of find you can use -executable
:
find . -type f -executable -print
For BSD versions of find, you can use -perm
with +
and an octal mask:
find . -type f -perm +111 -print
In this context "+" means "any of these bits are set" and 111 is the execute bits.
Note that this is not identical to the -executable
predicate in GNU find. In particular, -executable
tests that the file can be executed by the current user, while -perm +111
just tests if any execute permissions are set.
Older versions of GNU find also support the -perm +111
syntax, but as of 4.5.12 this syntax is no longer supported. Instead, you can use -perm /111
to get this behavior.
if the zipcode field is not a required field then add null=True and blank=True, then run makemigrations and migrate command to successfully reflect the changes in the database.
Webrtc is a part of peer to peer connection. We all know that before creating peer to peer connection, it requires handshaking process to establish peer to peer connection. And websockets play the role of handshaking process.
The top answer is not suitable when values may have length less than 4.
You will get "Invalid length parameter passed to the right function" because it doesn't accept negatives. Use a CASE statement:
SELECT case when len(foo) >= 4 then RIGHT(foo, LEN(foo) - 4) else '' end AS myfoo from mytable;
Values less than 4 give the surprising behavior below instead of an error, because passing negative values to RIGHT trims the first characters instead of the entire string. It makes more sense to use RIGHT(MyColumn, -5)
instead.
An example comparing what you get when you use the top answer's "length - 5" instead of "-5":
create temp table foo (foo) as values ('123456789'),('12345678'),('1234567'),('123456'),('12345'),('1234'),('123'),('12'),('1'), ('');
select foo, right(foo, length(foo) - 5), right(foo, -5) from foo;
foo len(foo) - 5 just -5
--------- ------------ -------
123456789 6789 6789
12345678 678 678
1234567 67 67
123456 6 6
12345
1234 234
123 3
12
1
for me one solution for this problem was to add in sql.Open ... sslmode=disable
You can't use a subselect inside a CREATE SEQUENCE
statement. You'll have to select the value beforehand.
Keep template column inside DataGrid.Columns. This helped me resolve this issue.
Ref: DataGridTemplateColumn : Items collection must be empty before using ItemsSource.
use pandas vectorized string methods; as in the documentation:
these methods exclude missing/NA values automatically
.str.lower()
is the very first example there;
>>> df['x'].str.lower()
0 one
1 two
2 NaN
Name: x, dtype: object
For me what worked in ubuntu image:
FROM ubuntu:xenial
USER root
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update && apt-get install --no-install-recommends -y locales && rm -rf /var/lib/apt/lists/*
RUN echo "LC_ALL=en_US.UTF-8" >> /etc/environment
RUN echo "en_US.UTF-8 UTF-8" >> /etc/locale.gen
RUN echo "LANG=en_US.UTF-8" > /etc/locale.conf
You can also convert by creating a dictionary of elements and then directly converting to a data frame:
import xml.etree.ElementTree as ET
import pandas as pd
# Contents of test.xml
# <?xml version="1.0" encoding="utf-8"?> <tags> <row Id="1" TagName="bayesian" Count="4699" ExcerptPostId="20258" WikiPostId="20257" /> <row Id="2" TagName="prior" Count="598" ExcerptPostId="62158" WikiPostId="62157" /> <row Id="3" TagName="elicitation" Count="10" /> <row Id="5" TagName="open-source" Count="16" /> </tags>
root = ET.parse('test.xml').getroot()
tags = {"tags":[]}
for elem in root:
tag = {}
tag["Id"] = elem.attrib['Id']
tag["TagName"] = elem.attrib['TagName']
tag["Count"] = elem.attrib['Count']
tags["tags"]. append(tag)
df_users = pd.DataFrame(tags["tags"])
df_users.head()
OK, here is how I did it in Notepad++:
Karate is exactly what you are looking for. Here is an example:
* def myJson = { foo: 'world', hey: 'ho', zee: [5], cat: { name: 'Billie' } }
* match myJson = { cat: { name: 'Billie' }, hey: 'ho', foo: 'world', zee: [5] }
(disclaimer: dev here)
You don't need to do special things in the form. You just build the comment correctly in the show action:
class ArticlesController < ActionController::Base
....
def show
@article = Article.find(params[:id])
@new_comment = @article.comments.build
end
....
end
and then make a form for it in the article view:
<% form_for @new_comment do |f| %>
<%= f.text_area :text %>
<%= f.submit "Post Comment" %>
<% end %>
by default, this comment will go to the create
action of CommentsController
, which you will then probably want to put redirect :back
into so you're routed back to the Article
page.
Try this:
onclick="myfunction(
'/myController/myAction',
function(){myfuncionOnOK('/myController2/myAction2','myParameter2');},
function(){myfuncionOnCancel('/myController3/myAction3','myParameter3');}
);"
Then you just need to call these two functions passed to myfunction
:
function myfunction(url, f1, f2) {
// …
f1();
f2();
}
Getting first and last elements in an array in Java
int[] a = new int[]{1, 8, 5, 9, 4};
First Element: a[0]
Last Element: a[a.length-1]
If you already have a table pre_loaded_tbl with some data. You can use a trick to load the data into your table with following query
INSERT INTO TABLE tweet_table
SELECT "my_data" AS my_column
FROM pre_loaded_tbl
LIMIT 5;
Also please note that "my_data" is independent of any data in the pre_loaded_tbl. You can select any data and write any column name (here my_data and my_column). Hive does not require it to have same column name. However structure of select statement should be same as that of your tweet_table. You can use limit to determine how many times you can insert into the tweet_table.
However if you haven't' created any table, you will have to load the data using file copy or load data commands in above answers.
Here is the HTML:
<div class="icon">
<span class="play">
::before
</span>
</div>
Computed style on 'before' was content: "VERIFY TO WATCH";
Here is my two lines of jQuery, which use the idea of adding an extra class to specifically reference this element and then appending a style tag (with an !important tag) to changes the CSS of the sudo-element's content value:
$("span.play:eq(0)").addClass('G');
$('body').append("<style>.G:before{content:'NewText' !important}</style>");
In my Angular Bootstrap dropdowns I initialize the JSON Array (vm.zoneDropdown) with ng-init (you can also have ng-init inside the directive template) and I pass the Array in a custom src attribute
<custom-dropdown control-id="zone" label="Zona" model="vm.form.zone" src="vm.zoneDropdown"
ng-init="vm.getZoneDropdownSrc()" is-required="true" form="farmaciaForm" css-class="custom-dropdown col-md-3"></custom-dropdown>
Inside the controller:
vm.zoneDropdown = [];
vm.getZoneDropdownSrc = function () {
vm.zoneDropdown = $customService.getZone();
}
And inside the customDropdown directive template(note that this is only one part of the bootstrap dropdown):
<ul class="uib-dropdown-menu" role="menu" aria-labelledby="btn-append-to-body">
<li role="menuitem" ng-repeat="dropdownItem in vm.src" ng-click="vm.setValue(dropdownItem)">
<a ng-click="vm.preventDefault($event)" href="##">{{dropdownItem.text}}</a>
</li>
</ul>
Noticed this was never resolved... You likely have a firewall in front of your machine blocking those ports, or iptables is set up to prevent the use of those ports.
Try running nmap -F localhost when you run your app (install nmap if you don't have it). If it appears that you're running the app on the correct port and you can't access it via a remote browser then there is some middleware or a physical firewall that's blocking the port.
Hope this helps!
For TypeScript 2.0 it would look like this:
MyStore.ts
export namespace Store {
export type Login = { isLoggedIn: boolean }
export type All = {
login: Login
}
}
import { reducers } from '../Reducers'
import * as Redux from 'redux'
const reduxStore: Redux.Store<Store.All> = Redux.createStore(reducers)
export default reduxStore;
MyClient.tsx
import reduxStore from "../Store";
{reduxStore.dispatch(...)}
1) Download the JDBC Driver here.
2) unzip the file and go to sqljdbc_version\fra\auth\x86 or \x64
3) copy the sqljdbc_auth.dll to C:\Program Files\Java\jre_Version\bin
4) Finally restart eclipse
I had same problem on Fedora, and found that problem was selinux. to test that it is problem run command: sudo setenforce 0
Otherwise or change in file /etc/sysconfig/selinux
SELINUX=enforcing
to
SELINUX=disabled
or add rules to selinux to allow http access
Use selectionStart
, it is compatible with all major browsers.
document.getElementById('foobar').addEventListener('keyup', e => {
console.log('Caret at: ', e.target.selectionStart)
})
_x000D_
<input id="foobar" />
_x000D_
Update: This works only when no type is defined or type="text"
or type="textarea"
on the input.
This is based on the assumption that you're getting an error about the date format, such as an invalid month value or non-numeric character when numeric expected.
Dates stored in the database do not have formats. When you query the date your client is formatting the date for display, as 4/16/2011
. Normally the same date format is used for selecting and updating dates, but in this case they appear to be different - so your client is apparently doing something more complicated that SQL*Plus, for example.
When you try to update it it's using a default date format model. Because of how it's displayed you're assuming that is MM/DD/YYYY
, but it seems not to be. You could find out what it is, but it's better not to rely on the default or any implicit format models at all.
Whether that is the problem or not, you should always specify the date model:
UPDATE PASOFDATE SET ASOFDATE = TO_DATE('11/21/2012', 'MM/DD/YYYY');
Since you aren't specifying a time component - all Oracle DATE
columns include a time, even if it's midnight - you could also use a date literal:
UPDATE PASOFDATE SET ASOFDATE = DATE '2012-11-21';
You should maybe check that the current value doesn't include a time, though the column name suggests it doesn't.
In C programming language, \
is used to print some of the special characters which has sepcial meaning in C. Those special characters are listed below
\\ - Backslash
\' - Single Quotation Mark
\" - Double Quatation Mark
\n - New line
\r - Carriage Return
\t - Horizontal Tab
\b - Backspace
\f - Formfeed
\a - Bell(beep) sound
I have implemented many methods to detect adblock in the browser and all solutions failed except below one in javascript:
window.onload = function() {
setTimeout(function() {
var ad = document.querySelector("ins.adsbygoogle");
if (ad && ad.innerHTML.replace(/\s/g, "").length == 0) {
console.log('You seem to blocking Google AdSense ads in your browser.');
}
}, 2000);
};
I hope this javascript solution will help you. Thanks for asking this question.
There's display: none
, but I think that might be a bit more than what you're looking for.
Here's a more complete and flexible example that doesn't omit necessary includes to generate compilation errors:
#include <iostream>
#include <unordered_map>
class Hashtable {
std::unordered_map<const void *, const void *> htmap;
public:
void put(const void *key, const void *value) {
htmap[key] = value;
}
const void *get(const void *key) {
return htmap[key];
}
};
int main() {
Hashtable ht;
ht.put("Bob", "Dylan");
int one = 1;
ht.put("one", &one);
std::cout << (char *)ht.get("Bob") << "; " << *(int *)ht.get("one");
}
Still not particularly useful for keys, unless they are predefined as pointers, because a matching value won't do! (However, since I normally use strings for keys, substituting "string" for "const void *" in the declaration of the key should resolve this problem.)
To expand on what Shimi has said, you should only be running your loop from 1 to the square root of n. Then to find the pair, do n / i
, and this will cover the whole problem space.
As was also noted, this is a NP, or 'difficult' problem. Exhaustive search, the way you are doing it, is about as good as it gets for guaranteed answers. This fact is used by encryption algorithms and the like to help secure them. If someone were to solve this problem, most if not all of our current 'secure' communication would be rendered insecure.
Python code:
import math
def divisorGenerator(n):
large_divisors = []
for i in xrange(1, int(math.sqrt(n) + 1)):
if n % i == 0:
yield i
if i*i != n:
large_divisors.append(n / i)
for divisor in reversed(large_divisors):
yield divisor
print list(divisorGenerator(100))
Which should output a list like:
[1, 2, 4, 5, 10, 20, 25, 50, 100]
Yes. Recent versions of IE (IE8 or above) let you adjust that. Here's how:
That should open the Developer Tools window. That window has two menu items that are of interest:
More at http://blogs.msdn.com/b/ie/archive/2010/06/16/ie-s-compatibility-features-for-site-developers.aspx
The output file needs to be opened in binary mode:
f = open('varstor.txt','w')
needs to be:
f = open('varstor.txt','wb')
This is an amazing function for cross-browser compatible event binding.
Got it from http://js.isite.net.au/snippets/addevent
With it you can just do Events.addEvent(element, event, function);
and be worry free!
For example: (http://jsfiddle.net/Zxeka/)
function hello() {
alert('Hello');
}
var button = document.createElement('input');
button.value = "Hello";
button.type = "button";
Events.addEvent(input_0, "click", hello);
document.body.appendChild(button);
Here's the function:
// We create a function which is called immediately,
// returning the actual function object. This allows us to
// work in a separate scope and only return the functions
// we require.
var Events = (function() {
// For DOM2-compliant browsers.
function addEventW3C(el, ev, f) {
// Since IE only supports bubbling, for
// compatibility we can't use capturing here.
return el.addEventListener(ev, f, false);
}
function removeEventW3C(el, ev, f) {
el.removeEventListener(ev, f, false);
}
// The function as required by IE.
function addEventIE(el, ev, f) {
// This is to work around a bug in IE whereby the
// current element doesn't get passed as context.
// We pass it via closure instead and set it as the
// context using call().
// This needs to be stored for removeEvent().
// We also store the original wrapped function as a
// property, _w.
((el._evts = el._evts || [])[el._evts.length]
= function(e) { return f.call(el, e); })._w = f;
// We prepend "on" to the event name.
return el.attachEvent("on" + ev,
el._evts[el._evts.length - 1]);
}
function removeEventIE(el, ev, f) {
for (var evts = el._evts || [], i = evts.length; i--; )
if (evts[i]._w === f)
el.detachEvent("on" + ev, evts.splice(i, 1)[0]);
}
// A handler to call all events we've registered
// on an element for legacy browsers.
function addEventLegacyHandler(e) {
var evts = this._evts[e.type];
for (var i = 0; i < evts.length; ++i)
if (!evts[i].call(this, e || event))
return false;
}
// For older browsers. We basically reimplement
// attachEvent().
function addEventLegacy(el, ev, f) {
if (!el._evts)
el._evts = {};
if (!el._evts[ev])
el._evts[ev] = [];
el._evts[ev].push(f);
return true;
}
function removeEventLegacy(el, ev, f) {
// Loop through the handlers for this event type
// and remove them if they match f.
for (var evts = el._evts[ev] || [], i = evts.length; i--; )
if (evts[i] === f)
evts.splice(i, 1);
}
// Select the appropriate functions based on what's
// available on the window object and return them.
return window.addEventListener
? {addEvent: addEventW3C, removeEvent: removeEventW3C}
: window.attachEvent
? {addEvent: addEventIE, removeEvent: removeEventIE}
: {addEvent: addEventLegacy, removeEvent: removeEventLegacy};
})();
If you don't want to use such a big function, this should work for almost all browsers, including IE:
if (el.addEventListener) {
el.addEventListener('click', function, false);
} else if (el.attachEvent) {
el.attachEvent('onclick', function);
}
In response to Craig's question. You're going to have to make a new element and copy over the attributes of the old element. This function should do the job: (source)
function changeInputType(oldObject, oType) {
var newObject = document.createElement('input');
newObject.type = oType;
if(oldObject.size) newObject.size = oldObject.size;
if(oldObject.value) newObject.value = oldObject.value;
if(oldObject.name) newObject.name = oldObject.name;
if(oldObject.id) newObject.id = oldObject.id;
if(oldObject.className) newObject.className = oldObject.className;
oldObject.parentNode.replaceChild(newObject,oldObject);
return newObject;
}
In R, you can assign your own operators using %[characters]%
. A trivial example:
'%p%' <- function(x, y){x^2 + y}
2 %p% 3 # result: 7
While I agree with BlueTrin that %%
is pretty standard, I have a suspicion %/%
may have something to do with the sort of operator definitions I showed above - perhaps it was easier to implement, and makes sense: %/%
means do a special sort of division (integer division)
if you open the psql
console in a terminal window, by typing
$ psql
you're super user username will be shown before the =#
, for example:
elisechant=#
$
That will be the user name you should use for localhost.
Increasing column size with ALTER
will not lose any data:
alter table [progennet_dev].PROGEN.LE
alter column UR_VALUE_3 varchar(500)
As @Martin points out, remember to explicitly specify NULL | NOT NULL
To define "soft real-time," it is easiest to compare it with "hard real-time." Below we will see that the term "firm real-time" constitutes a misunderstanding about "soft real-time."
Speaking casually, most people implicitly have an informal mental model that considers information or an event as being "real-time"
• if, or to the extent that, it is manifest to them with a delay (latency) that can be related to its perceived currency
• i.e., in a time frame that the information or event has acceptably satisfactory value to them.
There are numerous different ad hoc definitions of "hard real-time," but in that mental model, hard real-time is represented by the "if" term. Specifically, assuming that real-time actions (such as tasks) have completion deadlines, acceptably satisfactory value of the event that all tasks complete is limited to the special case that all tasks meet their deadlines.
Hard real-time systems make the very strong assumptions that everything about the application and system and environment is static and known a' priori—e.g., which tasks, that they are periodic, their arrival times, their periods, their deadlines, that they won’t have resource conflicts, and overall the time evolution of the system. In an aircraft flight control system or automotive braking system and many other cases those assumptions can usually be satisfied so that all the deadlines will be met.
This mental model is deliberately and very usefully general enough to encompass both hard and soft real-time--soft is accommodated by the "to the extent that" phrase. For example, suppose that the task completions event has suboptimal but acceptable value if
These are all common examples of soft real-time cases in a great many applications.
Consider the single-task application of picking your child up after school. That probably does not have an actual deadline, instead there is some value to you and your child based on when that event takes place. Too early wastes resources (such as your time) and too late has some negative value because your child might be left alone and potentially in harm's way (or at least inconvenienced).
Unlike the static hard real-time special case, soft real-time makes only the minimum necessary application-specific assumptions about the tasks and system, and uncertainties are expected. To pick up your child, you have to drive to the school, and the time to do that is dynamic depending on weather, traffic conditions, etc. You might be tempted to over-provision your system (i.e., allow what you hope is the worst case driving time) but again this is wasting resources (your time, and occupying the family vehicle, possibly denying use by other family members).
That example may not seem to be costly in terms of wasted resources, but consider other examples. All military combat systems are soft real-time. For example, consider performing an aircraft attack on a hostile ground vehicle using a missile guided with updates to it as the target maneuvers. The maximum satisfaction for completing the course update tasks is achieved by a direct destructive strike on the target. But an attempt to over-provision resources to make certain of this outcome is usually far too expensive and may even be impossible. In this case, you may be less but sufficiently satisfied if the missile strikes close enough to the target to disable it.
Obviously combat scenarios have a great many possible dynamic uncertainties that must be accommodated by the resource management. Soft real-time systems are also very common in many civilian systems, such as industrial automation, although obviously military ones are the most dangerous and urgent ones to achieve acceptably satisfactory value in.
The keystone of real-time systems is "predictability." The hard real-time case is interested in only one special case of predictability--i.e., that the tasks will all meet their deadlines and the maximum possible value will be achieved by that event. That special case is named "deterministic."
There is a spectrum of predictability. Deterministic (determinism) is one end-point (maximum predictability) on the predictability spectrum; the other end-point is minimum predictability (maximum non-determinism). The spectrum's metric and end-points have to be interpreted in terms of a chosen predictability model; everything between those two end-points is degrees of unpredictability (= degrees of non-determinism).
Most real-time systems (namely, soft ones) have non-deterministic predictability, for example, of the tasks' completions times and hence the values gained from those events.
In general (in theory), predictability, and hence acceptably satisfactory value, can be made as close to the deterministic end-point as necessary--but at a price which may be physically impossible or excessively expensive (as in combat or perhaps even in picking up your child from school).
Soft real-time requires an application-specific choice of a probability model (not the common frequentist model) and hence predictability model for reasoning about event latencies and resulting values.
Referring back to the above list of events that provide acceptable value, now we can add non-deterministic cases, such as
In a missile defense application, given the fact that in combat the offense always has the advantage over the defense, which of these two real-time computing scenarios would you prefer:
because the perfect destruction of all the hostile missiles is very unlikely or impossible, assign your defensive resources to maximize the probability that as many of the most threatening (e.g., based on their targets) hostile missiles will be successfully intercepted (close interception counts because it can move the hostile missile off-course);
complain that this is not a real-time computing problem because it is dynamic instead of static, and traditional real-time concepts and techniques do not apply, and it sounds more difficult than static hard real-time, so you are not interested in it.
Despite the various misunderstandings about soft real-time in the real-time computing community, soft real-time is very general and powerful, albeit potentially complex compared with hard real-time. Soft real-time systems as summarized here have a lengthy successful history of use outside the real-time computing community.
To directly answer the OP question:
A hard real-time system can provide deterministic guarantees—most commonly that all tasks will meet their deadlines, interrupt or system call response time will always be less than x, etc.—IF AND ONLY IF very strong assumptions are made and are correct that everything that matters is static and known a' priori (in general, such guarantees for hard real-time systems are an open research problem except for rather simple cases)
A soft real-time system does not make deterministic guarantees, it is intended to provide the best possible analytically specified and accomplished probabilistic timeliness and predictability of timeliness that are feasible under the current dynamic circumstances, according to application-specific criteria.
Obviously hard real-time is a simple special case of soft real-time. Obviously soft real-time's analytical non-deterministic assurances can be very complex to provide, but are mandatory in the most common real-time cases (including the most dangerous safety-critical ones such as combat) since most real-time cases are dynamic not static.
"Firm real-time" is an ill-defined special case of "soft real-time." There is no need for this term if the term "soft real-time" is understood and used properly.
I have a more detailed much more precise discussion of real-time, hard real-time, soft real-time, predictability, determinism, and related topics on my web site real-time.org.
Are you certain that the table in question exists?
Have you refreshed the table view in the Object Explorer? This can be done by right clicking the "tables" folder and pressing the F5 key.
You may also need to reresh the Intellisense cache.
This can be done by following the menu route: Edit -> IntelliSense -> Refresh Local Cache
Use the git commit
command without any flags. The configured editor will open (Vim in this case):
To start typing press the INSERT key on your keyboard, then in insert mode create a better commit with description how do you want. For example:
Once you have written all that you need, to returns to git, first you should exit insert mode, for that press ESC. Now close the Vim editor with save changes by typing on the keyboard :wq
(w - write, q - quit):
and press ENTER.
On GitHub this commit will looks like this:
As a commit editor you can use VS Code:
git config --global core.editor "code --wait"
From VS Code docs website: VS Code as Git editor
You could target all text boxes with input[type=text]
and then explicitly define the class for the textboxes who need it.
You can code like below :
input[type=text] {_x000D_
padding: 0;_x000D_
height: 30px;_x000D_
position: relative;_x000D_
left: 0;_x000D_
outline: none;_x000D_
border: 1px solid #cdcdcd;_x000D_
border-color: rgba(0, 0, 0, .15);_x000D_
background-color: white;_x000D_
font-size: 16px;_x000D_
}_x000D_
_x000D_
.advancedSearchTextbox {_x000D_
width: 526px;_x000D_
margin-right: -4px;_x000D_
}
_x000D_
<input type="text" class="advancedSearchTextBox" />
_x000D_
In case someone needs a CSS background with different color repeating horizontal stripes, here is how I managed to achieve this:
body {_x000D_
font-family: 'Lucida Grande', 'Helvetica Neue', Helvetica, Arial, sans-serif;_x000D_
font-size: 13px;_x000D_
}_x000D_
_x000D_
.css-stripes {_x000D_
margin: 0 auto;_x000D_
width: 200px;_x000D_
padding: 100px;_x000D_
text-align: center;_x000D_
/* For browsers that do not support gradients */_x000D_
background-color: #F691FF;_x000D_
/* Safari 5.1 to 6.0 */_x000D_
background: -webkit-repeating-linear-gradient(#F691FF, #EC72A8);_x000D_
/* Opera 11.1 to 12.0 */_x000D_
background: -o-repeating-linear-gradient(#F691FF, #EC72A8);_x000D_
/* Firefox 3.6 to 15 */_x000D_
background: -moz-repeating-linear-gradient(#F691FF, #EC72A8);_x000D_
/* Standard syntax */_x000D_
background-image: repeating-linear-gradient(to top, #F691FF, #EC72A8);_x000D_
background-size: 1px 2px;_x000D_
}
_x000D_
<div class="css-stripes">Hello World!</div>
_x000D_
Instead of letting everything get serialized by default, you can take the "opt-in" approach. In this scenario, only the properties you specify are allowed to be serialized. You do this with the DataContractAttribute
and DataMemberAttribute
, found in the System.Runtime.Serialization namespace.
The DataContactAttribute
is applied to the class, and the DataMemberAttribute
is applied to each member you want to be serialized:
[DataContract]
public class MyClass {
[DataMember]
public int Id { get; set;} // Serialized
[DataMember]
public string Name { get; set; } // Serialized
public string DontExposeMe { get; set; } // Will not be serialized
}
Dare I say this is a better approach because it forces you to make explicit decisions about what will or will not make it through serialization. It also allows your model classes to live in a project by themselves, without taking a dependency on JSON.net just because somewhere else you happen to be serializing them with JSON.net.
/\S/.test(string)
returns true if and only if there's a non-space character in string
. Tab and newline count as spaces.
Try to use the below code:
Date date = new Date();
SimpleDateFormat dateFormatWithZone = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",Locale.getDefault());
String currentDate = dateFormatWithZone.format(date);
Yes, you need to write it like your second line. Java doesn't have the python style syntactic sugar of your first line.
Alternatively you could put your valid values into an array and check for the existence of symbol
in the array.
You can use fuckit module.
Wrap your code in a function with @fuckit
decorator:
@fuckit
def func():
code a
code b #if b fails, it should ignore, and go to c.
code c #if c fails, go to d
code d
Make sure the scp command is available on both sides - both on the client and on the server.
BOTH Server and Client, otherwise you will encounter this kind of (weird)error message on your client: scp: command not found
or something similar even though though you have it all configured locally.
The answer given by alvarolb is definitely the best way to do it. Building upon his answer, an easy way to implement this is to simply store out the active views by position:
SparseArray<View> views = new SparseArray<View>();
@Override
public Object instantiateItem(View container, int position) {
View root = <build your view here>;
((ViewPager) container).addView(root);
views.put(position, root);
return root;
}
@Override
public void destroyItem(View collection, int position, Object o) {
View view = (View)o;
((ViewPager) collection).removeView(view);
views.remove(position);
view = null;
}
Then once by overriding the notifyDataSetChanged
method you can refresh the views...
@Override
public void notifyDataSetChanged() {
int key = 0;
for(int i = 0; i < views.size(); i++) {
key = views.keyAt(i);
View view = views.get(key);
<refresh view with new data>
}
super.notifyDataSetChanged();
}
You can actually use similar code in instantiateItem
and notifyDataSetChanged
to refresh your view. In my code I use the exact same method.
This error may occur when WCF
client tries to send its message using MTOM extension (MIME type application/soap+xml
is used to transfer SOAP XML in MTOM
), but service is just able to understand normal SOAP messages (it doesn't contain MIME parts, only text/xml type in HTTP request).
Be sure you generated your client code against correct WSDL
.
In order to use MTOM on server side, change your configuration file adding messageEncoding attribute:
<binding name="basicHttp" allowCookies="true"
maxReceivedMessageSize="20000000"
maxBufferSize="20000000"
maxBufferPoolSize="20000000"
messageEncoding="Mtom" >
Funny the answer is hidden in among the answers.
str.replace("•", "something")
would work if you use the right semantics.
str.replace(u"\u2022","something")
works wonders ;) , thnx to RParadox for the hint.
https://bugs.eclipse.org/bugs/show_bug.cgi?id=102239 states that there is no substitution mechanics implemented in Eclipse's launcher, at least no up to release Juno.
Thus it is (almost) impossible to append or prepend another library folder to java.library.path when launching Eclipse without prior knowledge of the default setting.
I wrote almost, cause it should be possible to let Eclipse startup, dump the content of java.library.path and stop Eclipse in one command. The dump would the be parsed and then taken as the input for launching Eclipse, i.e.
#!/bin/bash
# get default value of java.library.path (somehow)
default_lib_path=$( start_dump_stop_eclipse_somehow )
# now launch Eclipse
eclipse --launcher.appendVmargs \
-vmargs \
-Djava.library.path="/my/native/lib/folder:${default_lib_path}"
First use pkill
or kill -9 <pid>
to kill the process.
Then use following userdel
command to delete user,
userdel -f cafe_fixer
According to userdel
man page:
-f, --force
This option forces the removal of the user account, even if the user is still logged in. It also forces userdel to remove the user's home directory and mail spool, even if another user uses the same home directory or if the mail spool is not owned by the specified user. If USERGROUPS_ENAB is defined to yes in /etc/login.defs and if a group exists with the same name as the deleted user, then this group will be removed, even if it is still the primary group of another user.
Edit 1: (by @Ajedi32)
Note: This option (i.e. --force
) is dangerous and may leave your system in an inconsistent state.
Edit 2: (by @socketpair)
In spite of the description about some files, this key allows removing the user while it is in use. Don't forget to chdir /
before, because this command will also remove home directory.
I have same issue, I found a working solution as below:
The reason is
if (0) means false, if (-1, or any other number than 0) means true. following value are not truthy, null, undefined, 0, ""empty string, false, NaN
never use number type like id as
if (id) {}
for id type with possible value 0, we can not use if (id) {}, because if (0) will means false, invalid, which we want it means valid as true id number.
So for id type, we must use following:
if ((Id !== undefined) && (Id !== null) && (Id !== "")){
} else {
}
for other string type, we can use if (string) {}, because null, undefined, empty string all will evaluate at false, which is correct.
if (string_type_variable) { }
Another alternative is to re-run the JRE setup. It typically installs a default JRE by placing java.exe, javaw.exe, etc. in your system folder. That would place the executables in your path, which should be sufficient, based on the note in the error message that it searched your path for javaw.exe
Do you mean this?
var listOfList = new List<List<int>>() {
new List<int>() { 1, 2 },
new List<int>() { 3, 4 },
new List<int>() { 5, 6 }
};
var list = new List<int> { 9, 9, 9 };
var result = list.Concat(listOfList.SelectMany(x => x));
foreach (var x in result) Console.WriteLine(x);
Results in: 9 9 9 1 2 3 4 5 6
Use .length
to count number of characters, and $.trim()
function to remove spaces, and replace(/ /g,'')
to replace multiple spaces with just one. Here is an example:
var str = " Hel lo ";
console.log(str.length);
console.log($.trim(str).length);
console.log(str.replace(/ /g,'').length);
Output:
20
7
5
Source: How to count number of characters in a string with JQuery
Now with new JavaScript version (ECMAScript 6 http://es6-features.org/#ClassDefinition) there is a better way to submit requests using nodejs and Promise request (http://www.wintellect.com/devcenter/nstieglitz/5-great-features-in-es6-harmony)
Using library: https://github.com/request/request-promise
npm install --save request
npm install --save request-promise
client:
//Sequential execution for node.js using ES6 ECMAScript
var rp = require('request-promise');
rp({
method: 'POST',
uri: 'http://localhost:3000/',
body: {
val1 : 1,
val2 : 2
},
json: true // Automatically stringifies the body to JSON
}).then(function (parsedBody) {
console.log(parsedBody);
// POST succeeded...
})
.catch(function (err) {
console.log(parsedBody);
// POST failed...
});
server:
var express = require('express')
, bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/', function(request, response){
console.log(request.body); // your JSON
var jsonRequest = request.body;
var jsonResponse = {};
jsonResponse.result = jsonRequest.val1 + jsonRequest.val2;
response.send(jsonResponse);
});
app.listen(3000);
No REAL easy way to do this. Lots of ideas out there, though.
SELECT table_name, LEFT(column_names , LEN(column_names )-1) AS column_names
FROM information_schema.columns AS extern
CROSS APPLY
(
SELECT column_name + ','
FROM information_schema.columns AS intern
WHERE extern.table_name = intern.table_name
FOR XML PATH('')
) pre_trimmed (column_names)
GROUP BY table_name, column_names;
Or a version that works correctly if the data might contain characters such as <
WITH extern
AS (SELECT DISTINCT table_name
FROM INFORMATION_SCHEMA.COLUMNS)
SELECT table_name,
LEFT(y.column_names, LEN(y.column_names) - 1) AS column_names
FROM extern
CROSS APPLY (SELECT column_name + ','
FROM INFORMATION_SCHEMA.COLUMNS AS intern
WHERE extern.table_name = intern.table_name
FOR XML PATH(''), TYPE) x (column_names)
CROSS APPLY (SELECT x.column_names.value('.', 'NVARCHAR(MAX)')) y(column_names)
Java Language Specification says that
Program Exit
A program terminates all its activity and exits when one of two things happens:
All the threads that are not daemon threads terminate.
Some thread invokes the exit method of class Runtime or class System, and the exit operation is not forbidden by the security manager.
It means that You should use it when You have big program (well, at lest bigger than this one) and want to finish its execution.
You can change the value of a bool all you want. As for an if:
if randombool == True:
works, but you can also use:
if randombool:
If you want to test whether something is false you can use:
if randombool == False
but you can also use:
if not randombool:
To see the public tables you can do
list tables
\dt
list table, view, and access privileges
\dp or \z
or just the table names
select table_name from information_schema.tables where table_schema = 'public';
I was recently working with IPFS and worked this out. A curl example for IPFS to upload a file looks like this:
curl -i -H "Content-Type: multipart/form-data; boundary=CUSTOM" -d $'--CUSTOM\r\nContent-Type: multipart/octet-stream\r\nContent-Disposition: file; filename="test"\r\n\r\nHello World!\n--CUSTOM--' "http://localhost:5001/api/v0/add"
The basic idea is that each part (split by string in boundary
with --
) has it's own headers (Content-Type
in the second part, for example.) The FormData
object manages all this for you, so it's a better way to accomplish our goals.
This translates to fetch API like this:
const formData = new FormData()
formData.append('blob', new Blob(['Hello World!\n']), 'test')
fetch('http://localhost:5001/api/v0/add', {
method: 'POST',
body: formData
})
.then(r => r.json())
.then(data => {
console.log(data)
})
Another pre-5.14 solution: http://www.perlmonks.org/?node_id=346719 (see japhy's post)
As his approach uses map
, it also works well for arrays, but requires cascading map
to produce a temporary array (otherwise the original would be modified):
my @orig = ('this', 'this sucks', 'what is this?');
my @list = map { s/this/that/; $_ } map { $_ } @orig;
# @orig unmodified
Going by the comments as well as personal experience, I say no, there is no need for range(len(a))
. Everything you can do with range(len(a))
can be done in another (usually far more efficient) way.
You gave many examples in your post, so I won't repeat them here. Instead, I will give an example for those who say "What if I want just the length of a
, not the items?". This is one of the only times you might consider using range(len(a))
. However, even this can be done like so:
>>> a = [1, 2, 3, 4]
>>> for _ in a:
... print True
...
True
True
True
True
>>>
Clements answer (as shown by Allik) can also be reworked to remove range(len(a))
:
>>> a = [6, 3, 1, 2, 5, 4]
>>> sorted(range(len(a)), key=a.__getitem__)
[2, 3, 1, 5, 4, 0]
>>> # Note however that, in this case, range(len(a)) is more efficient.
>>> [x for x, _ in sorted(enumerate(a), key=lambda i: i[1])]
[2, 3, 1, 5, 4, 0]
>>>
So, in conclusion, range(len(a))
is not needed. Its only upside is readability (its intention is clear). But that is just preference and code style.
Thanks to Mike's comment, I've re-read the doc and I've realised that my current user (i.e. userA that already has the create privilege) wasn't a direct/indirect member of the new owning role...
So the solution was quite simple - I've just done this grant:
grant userB to userA;
That's all folks ;-)
Another requirement is that the object has to be owned by user userA before altering it...
I did something close to that, the compiler is seeing that your return statement is in an If() statement. If you wish to resolve this error, simply create a new local variable called customerId before the If statement, then assign a value inside of the if statement. After the if statement, call your return statement, and return cstomerId. Like this:
Customer findCustomerByid(int id)
{
boolean exist=false;
if(this.customers.isEmpty()) {
return null;
}
for(int i=0;i<this.customers.size();i++) {
if(this.customers.get(i).getId() == id) {
exist=true;
break;
}
int customerId;
if(exist) {
customerId = this.customers.get(id);
} else {
customerId = this.customers.get(id);
}
}
return customerId;
}
git branch --set-upstream <<origin/branch>>
is officially not supported anymore and is replaced by git branch --set-upstream-to <<origin/branch>>
To answer the question more generaly how to redirect standard output to a variable ?
do the following :
from io import StringIO
import sys
result = StringIO()
sys.stdout = result
result_string = result.getvalue()
If you need to do that only in some function do the following :
old_stdout = sys.stdout
# your function containing the previous lines
my_function()
sys.stdout = old_stdout
The quickest way to get around the error is add on the -k option somewhere in your curl request. That option "allows connections to SSL cites without certs." (from curl --help)
Be aware that this may mean that you're not talking to the endpoint you think you are, as they are presenting a certificate not signed by a CA you trust.
For example:
$ curl -o /usr/bin/apt-cyg https://raw.github.com/cfg/apt-cyg/master/apt-cyg
gave me the following error response:
curl: (77) error setting certificate verify locations:
CAfile: /usr/ssl/certs/ca-bundle.crt
CApath: none
I added on -k:
curl -o /usr/bin/apt-cyg https://raw.github.com/cfg/apt-cyg/master/apt-cyg -k
and no error message. As a bonus, now I have apt-cyg installed. And ca-certificates.
Got this exception when maintaining very old application on Server 2003 using Asp classic on IIS6 with Oracle 9.2.0.1. The fix is by updating oracle to 9.2.0.6.
The server certificate is invalid, either because it is signed by an invalid CA (internal CA, self signed,...), doesn't match the server's name or because it is expired.
Either way, you need to find how to tell to the Python library that you are using that it must not stop at an invalid certificate if you really want to download files from this server.
After hours of struggling, I solved it by including the following within app/build.gradle:
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
If you're only working with the single digits 0-9, it's likely faster to build a lookup table so you don't have to call the conversion functions every time.
lookup_table = Hash.new
(0..9).each {|x|
lookup_table[x] = x.to_s(2)
lookup_table[x.to_s] = x.to_s(2)
}
lookup_table[5]
=> "101"
lookup_table["8"]
=> "1000"
Indexing into this hash table using either the integer or string representation of a number will yield its binary representation as a string.
If you require the binary strings to be a certain number of digits long (keep leading zeroes), then change x.to_s(2)
to sprintf "%04b", x
(where 4
is the minimum number of digits to use).
Take a look at the formats in ?strptime
R> foo <- factor("1/15/2006 0:00:00")
R> foo <- as.Date(foo, format = "%m/%d/%Y %H:%M:%S")
R> foo
[1] "2006-01-15"
R> class(foo)
[1] "Date"
Note that this will work even if foo
starts out as a character. It will also work if using other date formats (as.POSIXlt
, as.POSIXct
).
In the latest version of Angular, this is set in the angular.json
config file. Example:
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"projects": {
"my-project": {
"architect": {
"serve": {
"options": {
"port": 4444
}
}
}
}
}
}
You can also use ng config
to view/edit values:
ng config projects["my-project"].architect["serve"].options {port:4444}
In previous versions, this was set in angular-cli.json
underneath the defaults
element:
{
"defaults": {
"serve": {
"port": 4444,
"host": "10.1.2.3"
}
}
}
Very simple :)
<a href="#" id="blob" class="btn large primary" rel="popover">hover for popover</a>
var img = '<img src="https://si0.twimg.com/a/1339639284/images/three_circles/twitter-bird-white-on-blue.png" />';
$("#blob").popover({ title: 'Look! A bird!', content: img, html:true });
Solution(s) for this, found in the official wampserver.com forums:
This problem is caused by Windows (7) in combination with any software that also uses port 80 (like Skype or IIS (which is installed on most developer machines)). A video solution can be found here (34.500+ views, damn, this seems to be a big thing ! EDIT: The video now has ~60.000 views ;) )
To make it short: open command line tool, type "netstat -aon" and look for any lines that end of ":80"
. Note thatPID
on the right side. This is the process id of the software which currently usesport 80
. Press AltGr + Ctrl + Del to get into the Taskmanager. Switch to the tab where you can see all services currently running, ordered by PID. Search for that PID
you just notices and stop that thing (right click). To prevent this in future, you should config the software's port settings (skype can do that).
left click the wamp icon in the taskbar, go to apache > httpd.conf and edit this file: change "listen to port .... 80"
to 8080
. Restart. Done !
Port 80 blocked by "Microsoft Web Deployment Service", simply deinstall this, more info here
By the way, it's not Microsoft's fault, it's a stupid usage of ports by most WAMP stacks.
IMPORTANT: you have to use localhost
or 127.0.0.1
now with port 8080
, this means 127.0.0.1:8080
or localhost:8080
.
This is a MultiThreading Issue and Using Properly Synchronized Blocks This can be prevented. Without putting extra things on UI Thread and causing loss of responsiveness of app.
I also faced the same. And as the most accepted answer suggests making change to adapter data from UI Thread can solve the issue. That will work but is a quick and easy solution but not the best one.
As you can see for a normal case. Updating data adapter from background thread and calling notifyDataSetChanged in UI thread works.
This illegalStateException arises when a ui thread is updating the view and another background thread changes the data again. That moment causes this issue.
So if you will synchronize all the code which is changing the adapter data and making notifydatasetchange call. This issue should be gone. As gone for me and i am still updating the data from background thread.
Here is my case specific code for others to refer.
My loader on the main screen loads the phone book contacts into my data sources in the background.
@Override
public Void loadInBackground() {
Log.v(TAG, "Init loadings contacts");
synchronized (SingleTonProvider.getInstance()) {
PhoneBookManager.preparePhoneBookContacts(getContext());
}
}
This PhoneBookManager.getPhoneBookContacts reads contact from phonebook and fills them in the hashmaps. Which is directly usable for List Adapters to draw list.
There is a button on my screen. That opens a activity where these phone numbers are listed. If i directly setAdapter over the list before the previous thread finishes its work which is fast naviagtion case happens less often. It pops up the exception .Which is title of this SO question. So i have to do something like this in the second activity.
My loader in the second activity waits for first thread to complete. Till it shows a progress bar. Check the loadInBackground of both the loaders.
Then it creates the adapter and deliver it to the activity where on ui thread i call setAdapter.
That solved my issue.
This code is a snippet only. You need to change it to compile well for you.
@Override
public Loader<PhoneBookContactAdapter> onCreateLoader(int arg0, Bundle arg1) {
return new PhoneBookContactLoader(this);
}
@Override
public void onLoadFinished(Loader<PhoneBookContactAdapter> arg0, PhoneBookContactAdapter arg1) {
contactList.setAdapter(adapter = arg1);
}
/*
* AsyncLoader to load phonebook and notify the list once done.
*/
private static class PhoneBookContactLoader extends AsyncTaskLoader<PhoneBookContactAdapter> {
private PhoneBookContactAdapter adapter;
public PhoneBookContactLoader(Context context) {
super(context);
}
@Override
public PhoneBookContactAdapter loadInBackground() {
synchronized (SingleTonProvider.getInstance()) {
return adapter = new PhoneBookContactAdapter(getContext());
}
}
}
Hope this helps
Try grabbing the path using:
document.location.pathname
In Javascript you can the current URL in parts. Check out: https://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
Hmm... actually i dont know how this solved it? But the following steps solved it for me:
find / -name 'config.m4'
Now look if the config.m4 is anywhere in a folder of that stuff you want to phpize. Go to that folder and run phpize directly in there.
Using BalusC's suggestion of implementing Collection i can now hide my primefaces p:dataTable
using not empty operator on my dataModel
that extends javax.faces.model.ListDataModel
Code sample:
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import javax.faces.model.ListDataModel;
import org.primefaces.model.SelectableDataModel;
public class EntityDataModel extends ListDataModel<Entity> implements
Collection<Entity>, SelectableDataModel<Entity>, Serializable {
public EntityDataModel(List<Entity> data) { super(data); }
@Override
public Entity getRowData(String rowKey) {
// In a real app, a more efficient way like a query by rowKey should be
// implemented to deal with huge data
List<Entity> entitys = (List<Entity>) getWrappedData();
for (Entity entity : entitys) {
if (Integer.toString(entity.getId()).equals(rowKey)) return entity;
}
return null;
}
@Override
public Object getRowKey(Entity entity) {
return entity.getId();
}
@Override
public boolean isEmpty() {
List<Entity> entity = (List<Entity>) getWrappedData();
return (entity == null) || entity.isEmpty();
}
// ... other not implemented methods of Collection...
}
If the formulas are identical you can use Find and Replace with Match entire cell contents
checked and Look in: Formulas
. Select the range, go into Find and Replace, make your entries and `Replace All.
Or do you mean that there are several formulas with this same form, but different cell references? If so, then one way to go is a regular expression match and replace. Regular expressions are not built into Excel (or VBA), but can be accessed via Microsoft's VBScript Regular Expressions library.
The following function provides the necessary match and replace capability. It can be used in a subroutine that would identify cells with formulas in the specified range and use the formulas as inputs to the function. For formulas strings that match the pattern you are looking for, the function will produce the replacement formula, which could then be written back to the worksheet.
Function RegexFormulaReplace(formula As String)
Dim regex As New RegExp
regex.Pattern = "=\(\(([A-Z]+\d+)-([A-Z]+\d+)\)/([A-Z]+\d+)\)"
' Test if a match is found
If regex.Test(formula) = True Then
RegexFormulaReplace = regex.Replace(formula, "=(EXP((LN($1/$2)/14.32))-1")
Else
RegexFormulaReplace = CVErr(xlErrValue)
End If
Set regex = Nothing
End Function
In order for the function to work, you would need to add a reference to the Microsoft VBScript Regular Expressions 5.5 library. From the Developer
tab of the main ribbon, select VBA
and then References
from the main toolbar. Scroll down to find the reference to the library and check the box next to it.
I'm the author of modular-spring-contexts.
This is a small utility library to allow a more modular organization of spring contexts than is achieved by using Composing XML-based configuration metadata. modular-spring-contexts
works by defining modules, which are basically stand alone application contexts and allowing modules to import beans from other modules, which are exported ín their originating module.
The key points then are
A simple example would look like this:
File moduleDefinitions.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:module="http://www.gitlab.com/SpaceTrucker/modular-spring-contexts"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.gitlab.com/SpaceTrucker/modular-spring-contexts xsd/modular-spring-contexts.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config />
<module:module id="serverModule">
<module:config location="/serverModule.xml" />
</module:module>
<module:module id="clientModule">
<module:config location="/clientModule.xml" />
<module:requires module="serverModule" />
</module:module>
</beans>
File serverModule.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:module="http://www.gitlab.com/SpaceTrucker/modular-spring-contexts"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.gitlab.com/SpaceTrucker/modular-spring-contexts xsd/modular-spring-contexts.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config />
<bean id="serverSingleton" class="java.math.BigDecimal" scope="singleton">
<constructor-arg index="0" value="123.45" />
<meta key="exported" value="true"/>
</bean>
</beans>
File clientModule.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:module="http://www.gitlab.com/SpaceTrucker/modular-spring-contexts"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.gitlab.com/SpaceTrucker/modular-spring-contexts xsd/modular-spring-contexts.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config />
<module:import id="importedSingleton" sourceModule="serverModule" sourceBean="serverSingleton" />
</beans>
Change all "es6" and "es7" to "es" in your polyfills.ts and polyfills.ts
You want to check if an object is NULL/empty. Being NULL and empty are not the same. Like Justin and Brian have already mentioned, in C++ NULL is an assignment you'd typically associate with pointers. You can overload operator= perhaps, but think it through real well if you actually want to do this. Couple of other things:
bool IsEmpty()
method that returns true if an object's variables are reset to some default state? Guess that might bypass the NULL usage.A* p = new A; ... p = NULL;
is bad (no delete p) unless you can ensure your code will be garbage collected. If anything, this'd lead to memory leaks and with several such leaks there's good chance you'd have slow code. class Null {}; Null _NULL;
and then overload operator= and operator!= of other classes depending on your situation. Perhaps you should post us some details about the context to help you better with option 4.
Arpan
You have not specified the version, I'm assuming you are using Powershell v3.
Try this:
$path = "C:\Users\abc\Desktop\File\abc.txt"
(Get-Content $path -Raw).Replace("`r`n","`n") | Set-Content $path -Force
Editor's note: As mike z points out in the comments, Set-Content
appends a trailing CRLF, which is undesired. Verify with: 'hi' > t.txt; (Get-Content -Raw t.txt).Replace("`r`n","`n") | Set-Content t.txt; (Get-Content -Raw t.txt).EndsWith("`r`n")
, which yields $True
.
Note this loads the whole file in memory, so you might want a different solution if you want to process huge files.
UPDATE
This might work for v2 (sorry nowhere to test):
$in = "C:\Users\abc\Desktop\File\abc.txt"
$out = "C:\Users\abc\Desktop\File\abc-out.txt"
(Get-Content $in) -join "`n" > $out
Editor's note: Note that this solution (now) writes to a different file and is therefore not equivalent to the (still flawed) v3 solution. (A different file is targeted to avoid the pitfall Ansgar Wiechers points out in the comments: using >
truncates the target file before execution begins). More importantly, though: this solution too appends a trailing CRLF, which may be undesired. Verify with 'hi' > t.txt; (Get-Content t.txt) -join "`n" > t.NEW.txt; [io.file]::ReadAllText((Convert-Path t.NEW.txt)).endswith("`r`n")
, which yields $True
.
Same reservation about being loaded to memory though.
Another method (2's complement):
public int reverse(int x){
x~=x;
x++;
return x;
}
It does a one's complement first (by complementing all the bits) and then adds 1 to x. This method does the job as well.
Note: This method is written in Java, and will be similar to a lot of other languages
If you absolutely must use HTML to give your text color, you have to use the (deprecated) <font>
-tag:
<h2><font color="#006699">Process Report</font></h2>
But otherwise, I strongly recommend you to do as rekire said: use CSS.
This actually sums it up pretty nicely.
API Levels generally mean that as a programmer, you can communicate with the devices' built in functions and functionality. As the API level increases, functionality adds up (although some of it can get deprecated).
Choosing an API level for an application development should take at least two thing into account:
Android API levels can be divided to five main groups (not scientific, but what the heck):
I am using a com.google.android.material.bottomnavigation.BottomNavigationView
(not the same as OP's) and I tried a variety of the suggested solutions above, but the only thing that worked was setting app:itemBackground
and app:itemIconTint
to my selector color worked for me.
<com.google.android.material.bottomnavigation.BottomNavigationView
style="@style/BottomNavigationView"
android:foreground="?attr/selectableItemBackground"
android:theme="@style/BottomNavigationView"
app:itemBackground="@color/tab_color"
app:itemIconTint="@color/tab_color"
app:itemTextColor="@color/bottom_navigation_text_color"
app:labelVisibilityMode="labeled"
app:menu="@menu/bottom_navigation" />
My color/tab_color.xml
uses android:state_checked
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/grassSelected" android:state_checked="true" />
<item android:color="@color/grassBackground" />
</selector>
and I am also using a selected state color for color/bottom_navigation_text_color.xml
Not totally relevant here but for full transparency, my BottomNavigationView
style is as follows:
<style name="BottomNavigationView" parent="Widget.Design.BottomNavigationView">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">@dimen/bottom_navigation_height</item>
<item name="android:layout_gravity">bottom</item>
<item name="android:textSize">@dimen/bottom_navigation_text_size</item>
</style>
Ctrl + F5 is better, because you don't need additional lines. And you can, in the end, hit enter and exit running mode.
But, when you start a program with F5 and put a break-point, you can debug your application and that gives you other advantages.
An other way is to set the value directly in the flow layout
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width: size, height: size)
Please check below javascript in IE. Don't know if other modern browser will work or not.
<html>
<head>
<script type="text/javascript">
function OpenOutlookDoc(){
try {
var outlookApp = new ActiveXObject("Outlook.Application");
var nameSpace = outlookApp.getNameSpace("MAPI");
mailFolder = nameSpace.getDefaultFolder(6);
mailItem = mailFolder.Items.add('IPM.Note.FormA');
mailItem.Subject="a subject test";
mailItem.To = "[email protected]";
mailItem.HTMLBody = "<b>bold</b>";
mailItem.display (0);
}
catch(e){
alert(e);
// act on any error that you get
}
}
</script>
</head>
<body>
<a href="javascript:OpenOutlookDoc()">Click</a>
</body>
</html>
On my projects i give all rows the class "borders" which I want it to display more like a table with even borders. Giving each child element a border on the bottom and right and the first element of each row a left border will make all of your boxes have an even border:
First give all of the rows children a border on the right and bottom
.borders div{
border-right:1px solid #999;
border-bottom:1px solid #999;
}
Next give the first child of each or a left border
.borders div:first-child{
border-left:
1px solid #999;
}
Last make sure to clear the borders for their child elements
.borders div > div{
border:0;
}
HTML:
<div class="row borders">
<div class="col-xs-5 col-md-2">Email</div>
<div class="col-xs-7 col-md-4">[email protected]</div>
<div class="col-xs-5 col-md-2">Phone</div>
<div class="col-xs-7 col-md-4">555-123-4567</div>
</div>
With less you can set it up like this;
.table tbody tr {
&.error > td { background-color: red !important; }
&.error:hover > td { background-color: yellow !important; }
&.success > td { background-color: green !important; }
&.success:hover > td { background-color: yellow !important; }
...
}
That did the trick for me.
For Kotlin:
Just create a new file with name URIPathHelper.kt. Then copy and paste the following Utility class in your file. It covers all scenarios and works perfectly for all Android versions. Its explanation will be discussed later.
package com.mvp.handyopinion
import android.content.ContentUris
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.DocumentsContract
import android.provider.MediaStore
class URIPathHelper {
fun getPath(context: Context, uri: Uri): String? {
val isKitKatorAbove = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
// DocumentProvider
if (isKitKatorAbove && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
val docId = DocumentsContract.getDocumentId(uri)
val split = docId.split(":".toRegex()).toTypedArray()
val type = split[0]
if ("primary".equals(type, ignoreCase = true)) {
return Environment.getExternalStorageDirectory().toString() + "/" + split[1]
}
} else if (isDownloadsDocument(uri)) {
val id = DocumentsContract.getDocumentId(uri)
val contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), java.lang.Long.valueOf(id))
return getDataColumn(context, contentUri, null, null)
} else if (isMediaDocument(uri)) {
val docId = DocumentsContract.getDocumentId(uri)
val split = docId.split(":".toRegex()).toTypedArray()
val type = split[0]
var contentUri: Uri? = null
if ("image" == type) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
} else if ("video" == type) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
} else if ("audio" == type) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
}
val selection = "_id=?"
val selectionArgs = arrayOf(split[1])
return getDataColumn(context, contentUri, selection, selectionArgs)
}
} else if ("content".equals(uri.scheme, ignoreCase = true)) {
return getDataColumn(context, uri, null, null)
} else if ("file".equals(uri.scheme, ignoreCase = true)) {
return uri.path
}
return null
}
fun getDataColumn(context: Context, uri: Uri?, selection: String?, selectionArgs: Array<String>?): String? {
var cursor: Cursor? = null
val column = "_data"
val projection = arrayOf(column)
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,null)
if (cursor != null && cursor.moveToFirst()) {
val column_index: Int = cursor.getColumnIndexOrThrow(column)
return cursor.getString(column_index)
}
} finally {
if (cursor != null) cursor.close()
}
return null
}
fun isExternalStorageDocument(uri: Uri): Boolean {
return "com.android.externalstorage.documents" == uri.authority
}
fun isDownloadsDocument(uri: Uri): Boolean {
return "com.android.providers.downloads.documents" == uri.authority
}
fun isMediaDocument(uri: Uri): Boolean {
return "com.android.providers.media.documents" == uri.authority
}
}
How to Use URIPathHelper class to get path from URI
val uriPathHelper = URIPathHelper()
val filePath = uriPathHelper.getPath(this, YOUR_URI_OBJECT)
Cents? If you're calculationg money values you really shouldn't use float values. Money is actually countable values. The cents or pennys etc. could be considered the two (or whatever) least significant digits of an integer. You could store, and calculate money values as integers and divide by 100 (e.g. place dot or comma two before the two last digits). Using float's can lead to strange rounding errors...
Anyway, if your epsilon is supposed to define the accuracy, it looks a bit too small (too accurate)...
1)
npm uninstall -g create-react-app
or
yarn global remove create-react-app
2)
There seems to be a bug where create-react-app isn't properly uninstalled and using one of the new commands lead to:
A template was not provided. This is likely because you're using an outdated version of create-react-app.
After uninstalling it with npm uninstall -g create-react-app
, check whether you still have it "installed" with which create-react-app
(Windows: where create-react-app
) on your command line. If it returns something (e.g. /usr/local/bin/create-react-app), then do a rm -rf /usr/local/bin/create-react-app
to delete manually.
3)
Then one of these ways:
npx create-react-app my-app
npm init react-app my-app
yarn create react-app my-app
You could look at the Wikipedia article on Standard Deviation, in particular the section about Rapid calculation methods.
There's also an article I found that uses Python, you should be able to use the code in it without much change: Subliminal Messages - Running Standard Deviations.
UPDATE: I've since changed my mind on this solution. After more development and time spent working on this, I believe a better solution to this problem is to do the following:
<a ng-click="myFunction()">Click Here</a>
And then update your css
to have an extra rule:
a[ng-click]{
cursor: pointer;
}
Its much more simple and provides the exact same functionality and is much more efficient. Hope that might be helpful to anyone else looking up this solution in the future.
The following is my previous solution, which I am leaving here just for legacy purposes:
If you are having this problem a lot, a simple directive that would fix this issue is the following:
app.directive('a', function() {
return {
restrict: 'E',
link: function(scope, elem, attrs) {
if(attrs.ngClick || attrs.href === '' || attrs.href === '#'){
elem.on('click', function(e){
e.preventDefault();
});
}
}
};
});
It checks all anchor tags (<a></a>
) to see if their href
attribute is either an empty string (""
) or a hash ('#'
) or there is an ng-click
assignment. If it finds any of these conditions, it catches the event and prevents the default behavior.
The only down side is that it runs this directive for all anchor tags. So if you have a lot of anchor tags on the page and you only want to prevent the default behavior for a small number of them, then this directive isn't very efficient. However, I almost always want to preventDefault
, so I use this directive all over in my AngularJS apps.
Add the text-align
css property to its parent style attribute
Eg:
<div style="text-align:center">
<a href="http://www.example.com">example</a>????????????????????????????????????
</div>?
Or using a class (recommended)
<div class="my-class">
<a href="http://www.example.com">example</a>????????????????????????????????????
</div>?
.my-class {
text-align: center;
}
See below working example:
.my-class {_x000D_
text-align: center;_x000D_
background:green;_x000D_
width:400px;_x000D_
padding:15px; _x000D_
}_x000D_
.my-class a{text-decoration:none; color:#fff;}
_x000D_
<!--EXAMPLE-ONE-->_x000D_
<div style="text-align:center; border:solid 1px #000; padding:15px;">_x000D_
<a href="http://www.example.com">example</a>????????????????????????????????????_x000D_
</div>?_x000D_
_x000D_
<!--EXAMPLE-TWO-->_x000D_
<div class="my-class">_x000D_
<a href="http://www.example.com">example</a>????????????????????????????????????_x000D_
</div>?
_x000D_
Q: Why doesn't the text-align
style get applied to the a
element instead of the div
?
A: The text-align
style describes how inline
content is aligned within a block
element. In this case the div
is an block element and it's inline content is the a
. To further explore this consider how little sense it would make to apply the text-align
style to the a
element when it is accompanied by more text
<div>
Plain text is inline content.
<a href="http://www.example.com" style="text-align: center">example</a>
<span>Spans are also inline content</span>
</div>
Even though threre are line breaks here all the contents of div
are inline content and therefore will produce something like:
Plain text is inline content. example Spans are also inline content
It doesnt' make much sense as to how "example" in this case would be displayed if the text-align
property were to be applied it it.
You can write the php code in another file and include it in the proper place where you want it.
AJAX is also used to display HTML content that is formed by PHP into a specified HTML tag.
Using jQuery:
$.ajax({url: "test.php"}).done(function( html ) {
$("#results").append(html);
});
Above code will execute test.php and result will be displayed in the element with id results.
For Windows 10
Download whl file for the apropriate python version from http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy
put it under directory run the below command
C:\directory> pip install scipy-0.19.0rc2-cp35-cp35m-win_amd64.whl
If you need subsecond precision, you need to use system-specific extensions, and will have to check with the documentation for the operating system. POSIX supports up to microseconds with gettimeofday, but nothing more precise since computers didn't have frequencies above 1GHz.
If you are using Boost, you can check boost::posix_time.
Change this line:
if (typeof(T) == typeof(string))
For this line:
if (t.GetType() == typeof(string))
Your compiled classes may need to be recompiled from the source with the new jars.
Try running "mvn clean" and then rebuild
var audio = new Audio("http://rho.nu/pub/Game%20Of%20Thrones%20-%20Main%20Theme%20-%20Soundtrack.mp3");
audio.addEventListener('canplaythrough', function() {
this.currentTime = this.duration - 10;
this.loop = true;
this.play();
});
Just set loop = true in the canplaythrough eventlistener.
onActivityCreated()
is now deprecated as Fragments Version 1.3.0-alpha02
The onActivityCreated() method is now deprecated. Code touching the fragment's view should be done in onViewCreated() (which is called immediately before onActivityCreated()) and other initialization code should be in onCreate(). To receive a callback specifically when the activity's onCreate() is complete, a LifeCycleObserver should be registered on the activity's Lifecycle in onAttach(), and removed once the onCreate() callback is received.
Detailed information can be found here
UPDATE for Django >= 1.7
Per Django 2.1 documentation: Serving files uploaded by a user during development
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
You no longer need if settings.DEBUG
as Django will handle ensuring this is only used in Debug mode.
ORIGINAL answer for Django <= 1.6
Try putting this into your urls.py
from django.conf import settings
# ... your normal urlpatterns here
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
With this you can serve the static media from Django when DEBUG = True
(when you run on local computer) but you can let your web server configuration serve static media when you go to production and DEBUG = False
I have mysql version 5.6.27 on my LEMP and CURRENT_TIMESTAMP as default value works fine.
MySQL Migration Toolkit (1.1.10) still available for download from here:
http://downloads.mysql.com/archives.php?p=MySQLDeveloperSuite&v=1.1.10
solve this problem using single line of code..
function unflatten(arr){_x000D_
return arr.reduce((prevProps, nextProps) => {_x000D_
return prevProps.concat(Array.isArray(nextProps) ? unflatten(nextProps) : nextProps)_x000D_
}, [])_x000D_
}
_x000D_
Color? color = null;
or you can use
Color? color = new Color?();
example where assigning null wont work
color = x == 5 ? Color.Red : x == 9 ? Color.Black : null ;
so you can use :
color = x == 5 ? Color.Red : x == 9 ? Color.Black : new Color?();
You're missing the ()
after ToString
that marks it as a function call vs. a function reference (the kind you pass to delegates), which incidentally is why c# has no AddressOf
operator, it's implied by how you type it.
Try this:
string guid = System.Guid.NewGuid().ToString();
We use something like this [use in one line]:
<a title="send to Facebook"
href="http://www.facebook.com/sharer.php?s=100&p[title]=YOUR_TITLE&p[summary]=YOUR_SUMMARY&p[url]=YOUR_URL&p[images][0]=YOUR_IMAGE_TO_SHARE_OBJECT"
target="_blank">
<span>
<img width="14" height="14" src="'icons/fb.gif" alt="Facebook" /> Facebook
</span>
</a>
Use this code:
internal void SomeFunction() {
Dictionary<string, string> formField = new Dictionary<string, string>();
formField.Add("Name", "Henry");
formField.Add("Age", "21");
string body = GetBodyStringFromDictionary(formField);
// output : Name=Henry&Age=21
}
internal string GetBodyStringFromDictionary(Dictionary<string, string> formField)
{
string body = string.Empty;
foreach (var pair in formField)
{
body += $"{pair.Key}={pair.Value}&";
}
// delete last "&"
body = body.Substring(0, body.Length - 1);
return body;
}
You can use vector
to make triangle like this
ic_triangle_right.xml
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:pathData="M0,12l0,12 11.5,-5.7c6.3,-3.2 11.5,-6 11.5,-6.3 0,-0.3 -5.2,-3.1 -11.5,-6.3l-11.5,-5.7 0,12z"
android:strokeColor="#00000000"
android:fillColor="#000000"/>
</vector>
Then use it like
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/ic_triangle_right"
/>
For change the color and direction, use android:tint
and android:rotation
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/ic_triangle_right"
android:rotation="180" // change direction
android:tint="#00f" // change color
/>
Result
For change the shape of vector, you can change the width/height of vector. Example change width to 10dp
<vector
android:width="10dp"
android:height="24dp"
>
...
</vector>
geckodriver
), x86 or 64.As @Nakilon said, their is a comparing tool built in github if that's what you use.
To use it, append the url of the repo with "/compare".
itertools
provides the chain function for that:
From http://docs.python.org/library/itertools.html#recipes:
def flatten(listOfLists):
"Flatten one level of nesting"
return chain.from_iterable(listOfLists)
Note that the result is an iterable, so you may need list(flatten(...))
.
Be careful, characters like ’ or » are considered as alpha by MySQL. It better to use something like :
IF c BETWEEN 'a' AND 'z' OR c BETWEEN 'A' AND 'Z' OR c BETWEEN '0' AND '9' OR c = '-' THEN
opacity
applies to the whole element, so if you have a background, border or other effects on that element, those will also become transparent. If you only want the text to be transparent, use rgba
.
#foo {
color: #000; /* Fallback for older browsers */
color: rgba(0, 0, 0, 0.5);
font-size: 16pt;
font-family: Arial, sans-serif;
}
Also, steer far, far away from <font>
. We have CSS for that now.
No, actually the same result would be:
$('#contents')[0]
jQuery does not know how many results would be returned from the query. What you get back is a special jQuery object which is a collection of all the controls that matched the query.
Part of what makes jQuery so convenient is that MOST methods called on this object that look like they are meant for one control, are actually in a loop called on all the members int he collection
When you use the [0] syntax you take the first element from the inner collection. At this point you get a DOM object
In Ember.js you can use inline if helper in if block helper. It can replace ||
logical operator, for example:
{{#if (if firstCondition firstCondition secondCondition)}}
(firstCondition || (or) secondCondition) === true
{{/if}}
This is what I've used for my latest app.
# redirect the main page to landing
##RedirectMatch 302 ^/$ /landing
# remove php ext from url
# https://stackoverflow.com/questions/4026021/remove-php-extension-with-htaccess
RewriteEngine on
# File exists but has a trailing slash
# https://stackoverflow.com/questions/21417263/htaccess-add-remove-trailing-slash-from-url
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?(.*)/+$ /$1 [R=302,L,QSA]
# ok. It will still find the file but relative assets won't load
# e.g. page: /landing/ -> assets/js/main.js/main
# that's we have the rules above.
RewriteCond %{REQUEST_FILENAME} !\.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^/?(.*?)/?$ $1.php
List<string> empnames = emplist.Select(e => e.Ename).ToList();
This is an example of Projection in Linq. Followed by a ToList
to resolve the IEnumerable<string>
into a List<string>
.
Alternatively in Linq syntax (head compiled):
var empnamesEnum = from emp in emplist
select emp.Ename;
List<string> empnames = empnamesEnum.ToList();
Projection is basically representing the current type of the enumerable as a new type. You can project to anonymous types, another known type by calling constructors etc, or an enumerable of one of the properties (as in your case).
For example, you can project an enumerable of Employee
to an enumerable of Tuple<int, string>
like so:
var tuples = emplist.Select(e => new Tuple<int, string>(e.EID, e.Ename));
Isn't string.replace returning a value, rather than modifying the source string?
So if you wanted to modify variableABC, you'd need to do this:
var variableABC = "A B C";
variableABC = variableABC.replace('B', 'D') //output: 'A D C'
Just a remark about your saying
Hi, I tried searching a way to insert information in multiple tables in the same query
Do you eat all your lunch dishes mixed with drinks in the same bowl?
I suppose - no.
Same here.
There are things we do separately.
2 insert queries are 2 insert queries. It's all right. Nothing wrong with it. No need to mash it in one.
Same for select. Query must be sensible and do it's job. That's the only reasons. Number of queries is not.
As for the transactions - you may use them, but it's not THAT big deal for the average web-site. If it happened once a year (if ever) that one user registration being broken you'll be able to fix, no doubt.
there are hundreds of thousands sites running mysql with no transaction support driver. Have you heard of terrible disasters breaking these sites apart? Me neither.
And mysql_insert_id() has noting to do with transactions. you may include in into transaction all right. it's just different matters. Someone raised this question out of nowhere.
char check1[10], check2[10];
int foo;
do{
printf(">> ");
scanf(" %s", check1);
foo = strtol(check1, NULL, 10); // convert the string to decimal number
sprintf(check2, "%d", foo); // re-convert "foo" to string for comparison
} while (!(strcmp(check1, check2) == 0 && 0 < foo && foo < 24)); // repeat if the input is not number
If the input is number, you can use foo
as your input.
IOC (Inversion Of Control): Giving control to the container to get an instance of the object is called Inversion of Control, means instead of you are creating an object using the new operator, let the container do that for you.
DI (Dependency Injection): Way of injecting properties to an object is called Dependency Injection.
We have three types of Dependency Injection:
Spring supports only Constructor Injection and Setter/Getter Injection.
You can use a variable to count places in the array, so when ever you add a new element, you put it in the right place. For example:
int a = 0;
int arr[5] = { };
arr[a] = 6;
a++;
You can submit the IP you receive to an online geolocation service, such as http://www.geoplugin.net/json.gp?ip=<your ip here>&jsoncallback=<suitable javascript function in your source>
, then including the source it returns which will run the function you specify in jsoncallback
with the geolocation information.
Alternatively, you may want to look into HTML5's geolocation features -- you can see a demo of it in action here. The advantage of this is that you do not need to make requests to foreign servers, but it may not work on browsers that do not support HTML5.
Copy-and-paste version of the winner answer :)
Create this file with only this content:
$ sudo vi /etc/docker/daemon.json
{
"graph": "/my-docker-images"
}
Tested on Ubuntu 16.04.2 LTS
in docker 1.12.6
1 -Exactly like StErMi said.
2 - Please read this: http://www.vogella.de/articles/AndroidSQLite/article.html
3 -
Cursor cursor = db.query(TABLE_NAME, new String[] {"_id", "title", "title_raw", "timestamp"},
"//** YOUR REQUEST**//", null, null, "timestamp", null);
see here:
4 - see answer 3
You can get the user name using System.Security.Principal.WindowsIdentity.GetCurrent() but there is not way to get current user password!
I spent ages going through all the answers on this page but found the one that worked for me in the comments of the OP question by s-walsh
The answer is to use pip3:
$ pip3 install <name-of-install>
You can follow below steps to uninstall the app from the device via command prompt.
if it shows sucess your app is uninstalled successfully'
It is work 100%
sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}
You need to merge the remote branch into your current branch by running git pull
.
If your local branch is already up-to-date, you may also need to run git pull --rebase
.
A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.
If you include a file input box you can access the file as a base64 encoded string by using the FileReader object. If it's a text file a simple base64 decode will work to get the text.
Assuming the following HTML:
<input type="file" id="myfile" />
You can access using the following JQuery JS:
var file = $('#myfile').get(0).files[0];
var reader = new FileReader();
reader.onload = function (e) {
//get the file result, split by comma to remove the prefix, then base64 decode the contents
var decodedText = atob(e.target.result.split(',')[1]);
//show the file contents
alert(decoded);
};
reader.readAsDataURL(file);
you can use JsonConvert.SerializeObject()
JsonConvert.SerializeObject(myObject) // myObject is returned by JObject.Parse() method
Both malloc
and calloc
allocate memory, but calloc
initialises all the bits to zero whereas malloc
doesn't.
Calloc could be said to be equivalent to malloc + memset
with 0 (where memset sets the specified bits of memory to zero).
So if initialization to zero is not necessary, then using malloc could be faster.
Java 8:
LocalDateTime toDate = LocalDateTime.now();
LocalDateTime fromDate = LocalDateTime.of(toDate.getYear(), toDate.getMonth(),
toDate.getDayOfMonth(), 0, 0, 0);
long millis = ChronoUnit.MILLIS.between(fromDate, toDate);
Import the view controller class which you want to show and use the following code
KartViewController *viewKart = [[KartViewController alloc]initWithNibName:@"KartViewController" bundle:nil];
[self presentViewController:viewKart animated:YES completion:nil];