Documentation says:
DISTINCT ON ( expression [, ...] ) keeps only the first row of each set of rows where the given expressions evaluate to equal. [...] Note that the "first row" of each set is unpredictable unless ORDER BY is used to ensure that the desired row appears first. [...] The DISTINCT ON expression(s) must match the leftmost ORDER BY expression(s).
So you'll have to add the address_id
to the order by.
Alternatively, if you're looking for the full row that contains the most recent purchased product for each address_id
and that result sorted by purchased_at
then you're trying to solve a greatest N per group problem which can be solved by the following approaches:
The general solution that should work in most DBMSs:
SELECT t1.* FROM purchases t1
JOIN (
SELECT address_id, max(purchased_at) max_purchased_at
FROM purchases
WHERE product_id = 1
GROUP BY address_id
) t2
ON t1.address_id = t2.address_id AND t1.purchased_at = t2.max_purchased_at
ORDER BY t1.purchased_at DESC
A more PostgreSQL-oriented solution based on @hkf's answer:
SELECT * FROM (
SELECT DISTINCT ON (address_id) *
FROM purchases
WHERE product_id = 1
ORDER BY address_id, purchased_at DESC
) t
ORDER BY purchased_at DESC
Problem clarified, extended and solved here: Selecting rows ordered by some column and distinct on another
with php you can use two redirections. It works same as refresh in some issues.
you can use a page redirect.php and post your last url to it by GET method (for example). then in redirect.php you can change header to location you`ve sent to it by GET method.
like this: your page:
<?php
header("location:redirec.php?ref=".$your_url);
?>
redirect.php:
<?php
$ref_url=$_GET["ref"];
header("location:redirec.php?ref=".$ref_url);
?>
that worked for me good.
SELECT * FROM table
WHERE exec_datetime BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW();
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add
You can do this with XSLT but I'm not sure about straight XPath.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="utf-8" indent="yes"
omit-xml-declaration="yes"/>
<xsl:template match="a/*[text()='tsr']">
<xsl:number value-of="position()"/>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
datetime.time
does not support this, because it's nigh meaningless to subtract times in this manner. Use a full datetime.datetime
if you want to do this.
Using a variant on @wisbucky's answer, I added the following as an alias to my ~/.gitconfig
file:
pruneitgood = "!f() { \
git remote prune origin; \
git branch -vv | perl -nae 'system(qw(git branch -d), $F[0]) if $F[3] eq q{gone]}'; \
}; f"
With this, a simple git pruneitgood
will clean up both local & remote branches that are no longer needed after merges.
If you are using AngularJS, and you are using Angular Bootstrap : https://angular-ui.github.io/bootstrap/
You can do this so nice like this :
HTML:
<nav id="header-navbar" class="navbar navbar-default" ng-class="{'navbar-fixed-top':scrollDown}" role="navigation" scroll-nav>
<div class="container-fluid top-header">
<!--- Rest of code --->
</div>
</nav>
CSS: (Note here I use padding as bigger nav to shrink without padding you can modify as you want)
nav.navbar {
-webkit-transition: all 0.4s ease;
transition: all 0.4s ease;
background-color: white;
margin-bottom: 0;
padding: 25px;
}
.navbar-fixed-top {
padding: 0;
}
And then add your directive
Directive: (Note you may need to change this.pageYOffset >= 50
from 50 to more or less to fulfill your needs)
angular.module('app')
.directive('scrollNav', function ($window) {
return function(scope, element, attrs) {
angular.element($window).bind("scroll", function() {
if (this.pageYOffset >= 50) {
scope.scrollDown = true;
} else {
scope.scrollDown = false;
}
scope.$apply();
});
};
});
This will do the job nicely, animated and cool way.
The 2018 ES6+ ANSWER IS:
const arr = [1, 2, 3];
arr.forEach((val, key, arr) => {
if (Object.is(arr.length - 1, key)) {
// execute last item logic
console.log(`Last callback call at index ${key} with value ${val}` );
}
});
Arrays in Java start indexing at 0. So in your example you are referring to an element that is outside the array by one.
It should probably be something like freq[Global.iParameter[2]-1]=false;
You would need to loop through the array to initialize all of it, this line only initializes the last element.
Actually, I'm pretty sure that false is default for booleans in Java, so you might not need to initialize at all.
Best Regards
Database Input - How to prevent SQL Injection
You need to escape user input before inserting or updating it into the database. Here is an older way to do it. You would want to use parameterized queries now (probably from the PDO class).
$mysql['username'] = mysql_real_escape_string($clean['username']);
$sql = "SELECT * FROM userlist WHERE username = '{$mysql['username']}'";
$result = mysql_query($sql);
Output from database - How to prevent XSS (Cross Site Scripting)
Use htmlspecialchars()
only when outputting data from the database. The same applies for HTML Purifier. Example:
$html['username'] = htmlspecialchars($clean['username'])
And Finally... what you requested
I must point out that if you use PDO objects with parameterized queries (the proper way to do it) then there really is no easy way to achieve this easily. But if you use the old 'mysql' way then this is what you would need.
function filterThis($string) {
return mysql_real_escape_string($string);
}
Quick fix that works for me. Navigate to the root directory of your folder from command line (cmd). then once you are on your root directory, type:
code .
Then, press enter. Note the ".", don't forget it. Now try to debug and see if you get the same error.
Let me show you a little trick.
As Arkanciscan said, you can use CSS3 transitions. But his solution looks different from the original tag.
What you really need to do is this:
@keyframes blink {_x000D_
50% {_x000D_
opacity: 0.0;_x000D_
}_x000D_
}_x000D_
@-webkit-keyframes blink {_x000D_
50% {_x000D_
opacity: 0.0;_x000D_
}_x000D_
}_x000D_
.blink {_x000D_
animation: blink 1s step-start 0s infinite;_x000D_
-webkit-animation: blink 1s step-start 0s infinite;_x000D_
}
_x000D_
<span class="blink">Blink</span>
_x000D_
I found an following official matplotlib example that uses host_subplot to display multiple y-axes and all the different labels in one legend. No workaround necessary. Best solution I found so far. http://matplotlib.org/examples/axes_grid/demo_parasite_axes2.html
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt
host = host_subplot(111, axes_class=AA.Axes)
plt.subplots_adjust(right=0.75)
par1 = host.twinx()
par2 = host.twinx()
offset = 60
new_fixed_axis = par2.get_grid_helper().new_fixed_axis
par2.axis["right"] = new_fixed_axis(loc="right",
axes=par2,
offset=(offset, 0))
par2.axis["right"].toggle(all=True)
host.set_xlim(0, 2)
host.set_ylim(0, 2)
host.set_xlabel("Distance")
host.set_ylabel("Density")
par1.set_ylabel("Temperature")
par2.set_ylabel("Velocity")
p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2], label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], label="Velocity")
par1.set_ylim(0, 4)
par2.set_ylim(1, 65)
host.legend()
plt.draw()
plt.show()
You can use implode to return your array with a string separator.
$withComma = implode(",", $array);
echo $withComma;
// Will display apple,banana,orange
The easiest way to do it, that I have found.. Apply the System.Xml.Serialization.XmlArray
attribute to it.
[System.Xml.Serialization.XmlArray] //This is the part that makes it work
List<object> serializableList = new List<object>();
XmlSerializer xmlSerializer = new XmlSerializer(serializableList.GetType());
serializableList.Add(PersonList);
using (StreamWriter streamWriter = System.IO.File.CreateText(fileName))
{
xmlSerializer.Serialize(streamWriter, serializableList);
}
The serializer will pick up on it being an array and serialize the list's items as child nodes.
You could skip all this and just put your data in a table. Then refer to the table and header and it will be completely dynamic. I know this is from 3 years ago but someone may still find this useful.
Example code:
Activesheet.Range("TableName[ColumnName]").Copy
You can also use :
activesheet.listobjects("TableName[ColumnName]").Copy
You can even use this reference system in worksheet formulas as well. Its very dynamic.
Hope this helps!
My coworker and I used the script from https://github.com/tombigel/detect-zoom. In addition, we also dynamically created a svg element and check its currentScale property. It works great on Chrome and likely most browsers too. On FF the "zoom text only" feature has to be turned off though. SVG is supported on most browsers. At the time of this writing, tested on IE10, FF19 and Chrome28.
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
svg.setAttribute('version', '1.1');
document.body.appendChild(svg);
var z = svg.currentScale;
... more code ...
document.body.removeChild(svg);
Use the code
x = seq(0,100,5) #this means (starting number, ending number, interval)
the output will be
[1] 0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75
[17] 80 85 90 95 100
Setting Up the database
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "database_name";
// Table Names
private static final String DB_TABLE = "table_image";
// column names
private static final String KEY_NAME = "image_name";
private static final String KEY_IMAGE = "image_data";
// Table create statement
private static final String CREATE_TABLE_IMAGE = "CREATE TABLE " + DB_TABLE + "("+
KEY_NAME + " TEXT," +
KEY_IMAGE + " BLOB);";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// creating table
db.execSQL(CREATE_TABLE_IMAGE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
// create new table
onCreate(db);
}
}
Insert in the Database:
public void addEntry( String name, byte[] image) throws SQLiteException{
SQLiteDatabase database = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_IMAGE, image);
database.insert( DB_TABLE, null, cv );
}
Retrieving data:
byte[] image = cursor.getBlob(1);
Note:
Below is an Utility class which I hope could help you:
public class DbBitmapUtility {
// convert from bitmap to byte array
public static byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, stream);
return stream.toByteArray();
}
// convert from byte array to bitmap
public static Bitmap getImage(byte[] image) {
return BitmapFactory.decodeByteArray(image, 0, image.length);
}
}
Further reading
If you are not familiar how to insert and retrieve into a database, go through this tutorial.
You could write something like that :
public static bool HasMethod(this object objectToCheck, string methodName)
{
var type = objectToCheck.GetType();
return type.GetMethod(methodName) != null;
}
Edit : you can even do an extension method and use it like this
myObject.HasMethod("SomeMethod");
if (Arrays.asList("John", "Mary", "Peter").contains(name)) {
}
Yes, there's in fact many reasons why you can access AWS Lambda like and HTTP Endpoint.
The architecture of AWS Lambda
It's a microservice. Running inside EC2 with Amazon Linux AMI (Version 3.14.26–24.46.amzn1.x86_64) and runs with Node.js. The memory can be beetwen 128mb and 1gb. When the data source triggers the event, the details are passed to a Lambda function as parameter's.
What happen?
AWS Lambda run's inside a container, and the code is directly uploaded to this container with packages or modules. For example, we NEVER can do SSH for the linux machine running your lambda function. The only things that we can monitor are the logs, with CloudWatchLogs and the exception that came from the runtime.
AWS take care of launch and terminate the containers for us, and just run the code. So, even that you use require('http'), it's not going to work, because the place where this code runs, wasn't made for this.
Try this function:
=SUBTOTAL(3, B$2:B2)
You can find more details in this blog entry.
extension UIViewController {
func removeFromNavigationController() { navigationController?.removeController(.last) { self == $0 } }
}
extension UINavigationController {
enum ViewControllerPosition { case first, last }
enum ViewControllersGroupPosition { case first, last, all }
func removeController(_ position: ViewControllerPosition, animated: Bool = true,
where closure: (UIViewController) -> Bool) {
var index: Int?
switch position {
case .first: index = viewControllers.firstIndex(where: closure)
case .last: index = viewControllers.lastIndex(where: closure)
}
if let index = index { removeControllers(animated: animated, in: Range(index...index)) }
}
func removeControllers(_ position: ViewControllersGroupPosition, animated: Bool = true,
where closure: (UIViewController) -> Bool) {
var range: Range<Int>?
switch position {
case .first: range = viewControllers.firstRange(where: closure)
case .last:
guard let _range = viewControllers.reversed().firstRange(where: closure) else { return }
let count = viewControllers.count - 1
range = .init(uncheckedBounds: (lower: count - _range.min()!, upper: count - _range.max()!))
case .all:
let viewControllers = self.viewControllers.filter { !closure($0) }
setViewControllers(viewControllers, animated: animated)
return
}
if let range = range { removeControllers(animated: animated, in: range) }
}
func removeControllers(animated: Bool = true, in range: Range<Int>) {
var viewControllers = self.viewControllers
viewControllers.removeSubrange(range)
setViewControllers(viewControllers, animated: animated)
}
func removeControllers(animated: Bool = true, in range: ClosedRange<Int>) {
removeControllers(animated: animated, in: Range(range))
}
}
private extension Array {
func firstRange(where closure: (Element) -> Bool) -> Range<Int>? {
guard var index = firstIndex(where: closure) else { return nil }
var indexes = [Int]()
while index < count && closure(self[index]) {
indexes.append(index)
index += 1
}
if indexes.isEmpty { return nil }
return Range<Int>(indexes.min()!...indexes.max()!)
}
}
removeFromParent()
navigationController?.removeControllers(in: 1...3)
navigationController?.removeController(.first) { $0 != self }
navigationController?.removeController(.last) { $0 != self }
navigationController?.removeControllers(.all) { $0.isKind(of: ViewController.self) }
navigationController?.removeControllers(.first) { !$0.isKind(of: ViewController.self) }
navigationController?.removeControllers(.last) { $0 != self }
Do not forget to paste here the solution code
import UIKit
class ViewController2: ViewController {}
class ViewController: UIViewController {
private var tag: Int = 0
deinit { print("____ DEINITED: \(self), tag: \(tag)" ) }
override func viewDidLoad() {
super.viewDidLoad()
print("____ INITED: \(self)")
let stackView = UIStackView()
stackView.axis = .vertical
view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
stackView.addArrangedSubview(createButton(text: "Push ViewController() white", selector: #selector(pushWhiteViewController)))
stackView.addArrangedSubview(createButton(text: "Push ViewController() gray", selector: #selector(pushGrayViewController)))
stackView.addArrangedSubview(createButton(text: "Push ViewController2() green", selector: #selector(pushController2)))
stackView.addArrangedSubview(createButton(text: "Push & remove previous VC", selector: #selector(pushViewControllerAndRemovePrevious)))
stackView.addArrangedSubview(createButton(text: "Remove first gray VC", selector: #selector(dropFirstGrayViewController)))
stackView.addArrangedSubview(createButton(text: "Remove last gray VC", selector: #selector(dropLastGrayViewController)))
stackView.addArrangedSubview(createButton(text: "Remove all gray VCs", selector: #selector(removeAllGrayViewControllers)))
stackView.addArrangedSubview(createButton(text: "Remove all VCs exept Last", selector: #selector(removeAllViewControllersExeptLast)))
stackView.addArrangedSubview(createButton(text: "Remove all exept first and last VCs", selector: #selector(removeAllViewControllersExeptFirstAndLast)))
stackView.addArrangedSubview(createButton(text: "Remove all ViewController2()", selector: #selector(removeAllViewControllers2)))
stackView.addArrangedSubview(createButton(text: "Remove first VCs where bg != .gray", selector: #selector(dropFirstViewControllers)))
stackView.addArrangedSubview(createButton(text: "Remove last VCs where bg == .gray", selector: #selector(dropLastViewControllers)))
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if title?.isEmpty ?? true { title = "First" }
}
private func createButton(text: String, selector: Selector) -> UIButton {
let button = UIButton()
button.setTitle(text, for: .normal)
button.setTitleColor(.blue, for: .normal)
button.addTarget(self, action: selector, for: .touchUpInside)
return button
}
}
extension ViewController {
private func createViewController<VC: ViewController>(backgroundColor: UIColor = .white) -> VC {
let viewController = VC()
let counter = (navigationController?.viewControllers.count ?? -1 ) + 1
viewController.tag = counter
viewController.title = "Controller \(counter)"
viewController.view.backgroundColor = backgroundColor
return viewController
}
@objc func pushWhiteViewController() {
navigationController?.pushViewController(createViewController(), animated: true)
}
@objc func pushGrayViewController() {
navigationController?.pushViewController(createViewController(backgroundColor: .lightGray), animated: true)
}
@objc func pushController2() {
navigationController?.pushViewController(createViewController(backgroundColor: .green) as ViewController2, animated: true)
}
@objc func pushViewControllerAndRemovePrevious() {
navigationController?.pushViewController(createViewController(), animated: true)
removeFromNavigationController()
}
@objc func removeAllGrayViewControllers() {
navigationController?.removeControllers(.all) { $0.view.backgroundColor == .lightGray }
}
@objc func removeAllViewControllersExeptLast() {
navigationController?.removeControllers(.all) { $0 != self }
}
@objc func removeAllViewControllersExeptFirstAndLast() {
guard let navigationController = navigationController, navigationController.viewControllers.count > 1 else { return }
let lastIndex = navigationController.viewControllers.count - 1
navigationController.removeControllers(in: 1..<lastIndex)
}
@objc func removeAllViewControllers2() {
navigationController?.removeControllers(.all) { $0.isKind(of: ViewController2.self) }
}
@objc func dropFirstViewControllers() {
navigationController?.removeControllers(.first) { $0.view.backgroundColor != .lightGray }
}
@objc func dropLastViewControllers() {
navigationController?.removeControllers(.last) { $0.view.backgroundColor == .lightGray }
}
@objc func dropFirstGrayViewController() {
navigationController?.removeController(.first) { $0.view.backgroundColor == .lightGray }
}
@objc func dropLastGrayViewController() {
navigationController?.removeController(.last) { $0.view.backgroundColor == .lightGray }
}
}
Since typeof
is a compiler extension, there is not really a definition for it, but in the tradition of C it would be an operator, e.g sizeof
and _Alignof
are also seen as an operators.
And you are mistaken, C has dynamic types that are only determined at run time: variable modified (VM) types.
size_t n = strtoull(argv[1], 0, 0);
double A[n][n];
typeof(A) B;
can only be determined at run time.
First get Latitude and Longitude using Location and LocationManager class. Now try the code below for Get the city,address info
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(lat, lng, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)).append("\n");
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
}
City info is now in sb. Now convert the sb to String (using sb.toString() ).
userInfos.GroupBy(userInfo => userInfo.metric)
.OrderBy(group => group.Key)
.Select(group => Tuple.Create(group.Key, group.Count()));
in visualstudio 2008 you could use this code :
var _assembly = System.Reflection.Assembly
.GetExecutingAssembly().GetName().CodeBase;
var _path = System.IO.Path.GetDirectoryName(_assembly) ;
The Elements()
method returns an IEnumerable<XElement>
containing all child elements of the current node. For an XDocument, that collection only contains the Root element. Therefore the following is required:
var query = from c in xmlFile.Root.Elements("Band")
select c;
Closing the services console as suggested by a few of the answers here did allow me to remove the service. In my scenario this was only a short term fix since all subsequent reinstalls and removal of the service would require me to take these additional steps. Reviewing my web.config file, it was discovered that there was an error that once fixed, allowed me to easily remove the service without the additional closing of the services console step.
SQlite3 has a method named row_factory. This method would allow you to access the values by column name.
https://www.kite.com/python/examples/3884/sqlite3-use-a-row-factory-to-access-values-by-column-name
I use a Mac with Visual Studio Code and this is what worked:
Shutdown your PC and switch it on again. Don't use the restart function. I restarted 2 times and it didn't work. Only shutdown worked.
PS: I tried out the following:
killall -9 dart
;But they all didn't work.
While it's true that json
is a built-in module, I also found that on an Ubuntu system with python-minimal
installed, you DO have python
but you can't do import json
. And then I understand that you would try to install the module using pip!
If you have python-minimal
you'll get a version of python with less modules than when you'd typically compile python yourself, and one of the modules you'll be missing is the json
module. The solution is to install an additional package, called libpython2.7-stdlib
, to install all 'default' python libraries.
sudo apt install libpython2.7-stdlib
And then you can do import json
in python and it would work!
xmlns refers to the XML namespace
When using prefixes in XML, a so-called namespace for the prefix must be defined. The namespace is defined by the xmlns attribute in the start tag of an element. The namespace declaration has the following syntax. xmlns:prefix="URI".
Note: The namespace URI is not used by the parser to look up information.
The purpose is to give the namespace a unique name. However, often companies use the namespace as a pointer to a web page containing namespace information.
function stringToUint(string) {
var string = btoa(unescape(encodeURIComponent(string))),
charList = string.split(''),
uintArray = [];
for (var i = 0; i < charList.length; i++) {
uintArray.push(charList[i].charCodeAt(0));
}
return new Uint8Array(uintArray);
}
function uintToString(uintArray) {
var encodedString = String.fromCharCode.apply(null, uintArray),
decodedString = decodeURIComponent(escape(atob(encodedString)));
return decodedString;
}
I have done, with some help from the internet, these little functions, they should solve your problems! Here is the working JSFiddle.
EDIT:
Since the source of the Uint8Array is external and you can't use atob
you just need to remove it(working fiddle):
function uintToString(uintArray) {
var encodedString = String.fromCharCode.apply(null, uintArray),
decodedString = decodeURIComponent(escape(encodedString));
return decodedString;
}
Warning: escape and unescape is removed from web standards. See this.
select convert(time,GETDATE())
On Windows you can try these steps:
/lib/security
with JRE (you can use a comand System.out.println(System.getProperty("java.home");
to find the folder with the current JRE). Make a backup of the file.Compared to window.location="url";
it is much easyer to do just location="url";
I always use that
I found that for a simple print statement in python 2.7, just put a comma at the end after your '\r'
.
print os.path.getsize(file_name)/1024, 'KB / ', size, 'KB downloaded!\r',
This is shorter than other non-python 3 solutions, but also more difficult to maintain.
Maybe this can help: Advanced Python Scheduler
Here's a small piece of code from their documentation:
from apscheduler.schedulers.blocking import BlockingScheduler
def some_job():
print "Decorated job"
scheduler = BlockingScheduler()
scheduler.add_job(some_job, 'interval', hours=1)
scheduler.start()
The appropriate regex would be the ' char followed by any number of any chars [including zero chars] ending with an end of string/line token:
'.*$
And if you wanted to capture everything after the ' char but not include it in the output, you would use:
(?<=').*$
This basically says give me all characters that follow the ' char until the end of the line.
Edit: It has been noted that $ is implicit when using .* and therefore not strictly required, therefore the pattern:
'.*
is technically correct, however it is clearer to be specific and avoid confusion for later code maintenance, hence my use of the $. It is my belief that it is always better to declare explicit behaviour than rely on implicit behaviour in situations where clarity could be questioned.
According to Google documentation they said that this is the best way to do it. First create this function to find out how many markers there are/
function setMapOnAll(map1) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map1);
}
}
Next create another function to take away all these markers
function clearMarker(){
setMapOnAll(null);
}
Then create this final function to erase all the markers when ever this function is called upon.
function delateMarkers(){
clearMarker()
markers = []
//console.log(markers) This is just if you want to
}
Hope that helped good luck
Aside from the ternary operator, you can also use Builder
widget if you have operation needs to be performed before the condition statement.
Container(
child: Builder(builder: (context) {
/// some operation here ...
if(someCondition) {
return Text('A');
}
else return Text('B');
})
)
You can use maven-shade plugin to build a uber jar like below
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
HTTPS is supported starting from PHP 4.3.0, if you have compiled in support for OpenSSL.
Also, make sure the target server has a valid certificate, the firewall allows outbound connections and allow_url_fopen
in php.ini is set to true.
Cut can take several ranges in -f
:
Columns up to 4 and from 7 onwards:
cut -f -4,7-
or for fields 1,2,5,6 and from 10 onwards:
cut -f 1,2,5,6,10-
etc
For those who didn't know what next, just add new module file and put @jor code (with my little hacked, supporting 'nothing' array) below.
Module ArrayExtension
<Extension()> _
Public Sub Add(Of T)(ByRef arr As T(), item As T)
If arr IsNot Nothing Then
Array.Resize(arr, arr.Length + 1)
arr(arr.Length - 1) = item
Else
ReDim arr(0)
arr(0) = item
End If
End Sub
End Module
In my Case there was problem with "Bearer" in header ideally it should be "Bearer "(space after the end character) but in my case it was "Bearer" there was no space after the character. Hope it helps some one!
foo(*ob);
You don't need to cast it because it's the same Object type, you just need to dereference it.
In my opinion, Sergiy's answer should be the selected answer for the given question. I'm sharing my understanding.
I was looking to autoload my package files using composer which I have under the dir structure given below.
<web-root>
|--------src/
| |--------App/
| |
| |--------Test/
|
|---------library/
|
|---------vendor/
| |
| |---------composer/
| | |---------autoload_psr4.php
| |
| |----------autoload.php
|
|-----------composer.json
|
I'm using psr-4 autoloading specification.
Had to add below lines to the project's composer.json. I intend to place my class files inside src/App , src/Test and library directory.
"autoload": {
"psr-4": {
"OrgName\\AppType\\AppName\\": ["src/App", "src/Test", "library/"]
}
}
This is pretty much self explaining. OrgName\AppType\AppName is my intended namespace prefix. e.g for class User in src/App/Controller/Provider/User.php -
namespace OrgName\AppType\AppName\Controller\Provider; // namespace declaration
use OrgName\AppType\AppName\Controller\Provider\User; // when using the class
Also notice "src/App", "src/Test" .. are from your web-root that is where your composer.json is. Nothing to do with the vendor dir. take a look at vendor/autoload.php
Now if composer is installed properly all that is required is #composer update
After composer update my classes loaded successfully. What I observed is that composer is adding a line in vendor/composer/autoload_psr4.php
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
'OrgName\\AppType\\AppName\\' => array($baseDir . '/src/App', $baseDir . '/src/Test', $baseDir . '/library'),
);
This is how composer maps. For psr-0 mapping is in vendor/composer/autoload_classmap.php
You are tying one had behind your back saying that you won't use the LESS files. I built my first Twitter Bootstrap theme using 2.0, and I did everything in CSS -- creating an override.css file. It took days to get things to work correctly.
Now we have 3.0. Let me assure you that it takes less time to learn LESS, which is pretty straight forward if you're comfortable with CSS, than doing all of those crazy CSS overrides. Making changes like the one you want is a piece of cake.
In Bootstrap 3.0, the container class controls the width, and all of the contained styles adjust to fill the container. The container width variables are at the bottom of the variables.less file.
// Container sizes
// --------------------------------------------------
// Small screen / tablet
@container-tablet: ((720px + @grid-gutter-width));
// Medium screen / desktop
@container-desktop: ((940px + @grid-gutter-width));
// Large screen / wide desktop
@container-lg-desktop: ((1020px + @grid-gutter-width));
Some sites either don't have enough content to fill the 1020 display or you want a narrower frame for aesthetic reasons. Because BS uses a 12-column grid I use a multiple like 960.
Error is something that most of the time you cannot handle it.
Exception was meant to give you an opportunity to do something with it. like try something else or write to the log.
try{
//connect to database 1
}
catch(DatabaseConnctionException err){
//connect to database 2
//write the err to log
}
Well, using LIKE
in statement is the best option
WHERE datetime LIKE '2009-10-20%'
it should work in this case
We can use append
append(l1, l2)
It also has arguments to insert element at a particular location.
Use <button> tag instead of <input type="button"..>. It is the advised practice in bootstrap 3.
http://getbootstrap.com/css/#buttons-tags
"Cross-browser rendering
As a best practice, we highly recommend using the <button> element whenever possible to ensure matching cross-browser rendering.
Among other things, there's a Firefox bug that prevents us from setting the line-height of <input>-based buttons, causing them to not exactly match the height of other buttons on Firefox."
There is no problem with whitespaces in the path since you're not using the "shell" to open the file. Here is a session from the windows console to prove the point. You're doing something else wrong
Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on wi
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>>
>>> os.makedirs("C:/ABC/SEM 2/testfiles")
>>> open("C:/ABC/SEM 2/testfiles/all.txt","w")
<open file 'C:/ABC/SEM 2/testfiles/all.txt', mode 'w' at 0x0000000001D95420>
>>> exit()
C:\Users\Gnibbler>dir "C:\ABC\SEM 2\testfiles"
Volume in drive C has no label.
Volume Serial Number is 46A0-BB64
Directory of c:\ABC\SEM 2\testfiles
13/02/2013 10:20 PM <DIR> .
13/02/2013 10:20 PM <DIR> ..
13/02/2013 10:20 PM 0 all.txt
1 File(s) 0 bytes
2 Dir(s) 78,929,309,696 bytes free
C:\Users\Gnibbler>
import java.text.DateFormatSymbols;
public String getMonth(int month) {
return new DateFormatSymbols().getMonths()[month-1];
}
I live in uk was keep on trying for 'us-west-2'region. So redirected to 'eu-west-2'. The correct region for S3 is 'eu-west-2'
If you're testing for all zeros to avoid a warning on another numpy function then wrapping the line in a try, except block will save having to do the test for zeros before the operation you're interested in i.e.
try: # removes output noise for empty slice
mean = np.mean(array)
except:
mean = 0
Give the container class
.container{
height: 100vh;
width: 100vw;
display: flex;
}
Give the div that's inside the container:
align-content: center;
All the content inside this div will show up in the middle of the page.
I prefer /^\s+$|^$/gi
to match empty and empty spaces.
console.log(" ".match(/^\s+$|^$/gi));_x000D_
console.log("".match(/^\s+$|^$/gi));
_x000D_
See the javadoc
of List
list.get(0);
or Set
set.iterator().next();
and check the size before using the above methods by invoking isEmpty()
!list_or_set.isEmpty()
First, having the url in href
is best because it allows users to copy links, open in another tab, etc.
In some cases (e.g. sites with frequent HTML changes) it is not practical to bind links every time there is an update.
Normal link:
<a href="https://www.google.com/">Google<a/>
And something like this for JS:
$("a").click(function (e) {
e.preventDefault();
var href = $(this).attr("href");
window.open(href);
return false;
});
The benefits of this method are clean separation of markup and behavior and doesn't have to repeat the function calls in every link.
If you don't want to bind every time, however, you can use onclick and pass in the element and event, e.g.:
<a href="https://www.google.com/" onclick="return Handler(this, event);">Google</a>
And this for JS:
function Handler(self, e) {
e.preventDefault();
var href = $(self).attr("href");
window.open(href);
return false;
}
The benefit to this method is that you can load in new links (e.g. via AJAX) whenever you want without having to worry about binding every time.
Under Settings => Media, there's an option for 'Full URL-path for files'. If you set this to the default media directory path '/wp-content/uploads' instead of blank, it will insert relative paths e.g. '/wp-content/uploads/2020/06/document.pdf'.
I'm not sure if it makes all links relative, e.g. to posts, but at least it handles media, which probably is what most people are worried about.
I had the same error for the MediaStream. The solution is set a stream to the srcObject.
From the docs:
Important: If you still have code that relies on createObjectURL() to attach streams to media elements, you need to update your code to simply set srcObject to the MediaStream directly.
I also don't under stand what the "-" means after the 200 140 section of the log
That value corresponds to the referer as described by Joachim. If you see a dash though, that means that there was no referer value to begin with (eg. the user went straight to a specific destination, like if he/she typed a URL in their browser)
You could also give the netbeans UML modeller a try. I have used it to generate javacode that I used in my eclipse projects. You can even import eclipse projects in netbeans and keep the eclipse settings synced with the netbeans project settings.
I tried several UML modellers for eclipse and wasn't satisfied with them. They were either unstable, complicated or just plain ugly. ;-)
The show command may be what you want. Try
git show -s --format=%ci <commit>
Other formats for the date string are available as well. Check the manual page for details.
Unwrap and downcast the objects to the right type, safely, with if let
, before doing the iteration with a simple for in
loop.
if let currentUser = currentUser,
let photos = currentUser.photos as? [ModelAttachment]
{
for object in photos {
let url = object.url
}
}
There's also guard let else
instead of if let
if you prefer having the result available in scope:
guard let currentUser = currentUser,
let photos = currentUser.photos as? [ModelAttachment] else
{
// break or return
}
// now 'photos' is available outside the guard
for object in photos {
let url = object.url
}
I'd seriously recommend installing MacVim via MacPorts (sudo port install MacVim
).
When installed, MacPorts automatically updates your profile to include /opt/local/bin in your path, and so when mvim is installed as /opt/local/bin/mvim during the install of MacVim you'll find it ready to use straight away.
When you install the MacVim port the MacVim.app bundle is installed in /Applications/MacPorts for you too.
A good thing about going the MacPorts route is that you'll also be able to install git too (sudo port install git-core
) and many many other ports. Highly recommended.
Answer for the question that is redirected here: "How to create a circular ImageView in Android?"
public static Bitmap getRoundBitmap(Bitmap bitmap) {
int min = Math.min(bitmap.getWidth(), bitmap.getHeight());
Bitmap bitmapRounded = Bitmap.createBitmap(min, min, bitmap.getConfig());
Canvas canvas = new Canvas(bitmapRounded);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
canvas.drawRoundRect((new RectF(0.0f, 0.0f, min, min)), min/2, min/2, paint);
return bitmapRounded;
}
A handy way can be the use of extension of type Double
extension Double {
var roundTo2f: Double {return Double(round(100 *self)/100) }
var roundTo3f: Double {return Double(round(1000*self)/1000) }
}
Usage:
let regularPie: Double = 3.14159
var smallerPie: Double = regularPie.roundTo3f // results 3.142
var smallestPie: Double = regularPie.roundTo2f // results 3.14
An int
is equivalent to uint32_t
and char
to uint8_t
.
I'll show how I resolved client-server communication, sending the actual time (4 bytes, formatted in Unix epoch) in a 1-bit array, and then re-built it in the other side. (Note: the protocol was to send 1024 bytes)
Client side
uint8_t message[1024];
uint32_t t = time(NULL);
uint8_t watch[4] = { t & 255, (t >> 8) & 255, (t >> 16) & 255, (t >>
24) & 255 };
message[0] = watch[0];
message[1] = watch[1];
message[2] = watch[2];
message[3] = watch[3];
send(socket, message, 1024, 0);
Server side
uint8_t res[1024];
uint32_t date;
recv(socket, res, 1024, 0);
date = res[0] + (res[1] << 8) + (res[2] << 16) + (res[3] << 24);
printf("Received message from client %d sent at %d\n", socket, date);
Hope it helps.
You can install maven from m2eclipse - http://download.eclipse.org/technology/m2e/releases
I find that there's simpler solution compared to the accepted answer.
Read the files using the HTML5 FileReader API with.readAsArrayBuffer
- Create a Blob with the file data and get its url with
window.URL.createObjectURL(blob)
- Create new Image element and set it's src to the file blob url
- Send the image to the canvas. The canvas size is set to desired output size
- Get the scaled-down data back from canvas
viacanvas.toDataURL("image/jpeg",0.7)
(set your own output format and quality)- Attach new hidden inputs to the original form
and transfer the dataURI images basically as normal textOn backend, read the dataURI, decode from Base64, andsave it
As per your question:
Is there a way to compress an image (mostly jpeg, png and gif) directly browser-side, before uploading it
My solution:
Create a blob with the file directly with URL.createObjectURL(inputFileElement.files[0])
.
Same as accepted answer.
Same as accepted answer. Worth mentioning that, canvas size is necessary and use img.width
and img.height
to set canvas.width
and canvas.height
. Not img.clientWidth
.
Get the scale-down image by canvas.toBlob(callbackfunction(blob){}, 'image/jpeg', 0.5)
. Setting 'image/jpg'
has no effect. image/png
is also supported. Make a new File
object inside the callbackfunction
body with let compressedImageBlob = new File([blob])
.
Add new hidden inputs or send via javascript . Server doesn't have to decode anything.
Check https://javascript.info/binary for all information. I came up the solution after reading this chapter.
Code:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload" multiple>
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
This code looks far less scary than the other answers..
One has to put everything inside img.onload
. Otherwise canvas
will not be able to get the image's width and height correctly as the time canvas
is assigned.
function upload(){
var f = fileToUpload.files[0];
var fileName = f.name.split('.')[0];
var img = new Image();
img.src = URL.createObjectURL(f);
img.onload = function(){
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
canvas.toBlob(function(blob){
console.info(blob.size);
var f2 = new File([blob], fileName + ".jpeg");
var xhr = new XMLHttpRequest();
var form = new FormData();
form.append("fileToUpload", f2);
xhr.open("POST", "upload.php");
xhr.send(form);
}, 'image/jpeg', 0.5);
}
}
3.4MB
.png
file compression test with image/jpeg
argument set.
|0.9| 777KB |
|0.8| 383KB |
|0.7| 301KB |
|0.6| 251KB |
|0.5| 219kB |
A generic function that remove any class starting with begin
:
function removeClassStartingWith(node, begin) {
node.removeClass (function (index, className) {
return (className.match ( new RegExp("\\b"+begin+"\\S+", "g") ) || []).join(' ');
});
}
http://jsfiddle.net/xa9xS/2900/
var begin = 'color-';_x000D_
_x000D_
function removeClassStartingWith(node, begin) {_x000D_
node.removeClass (function (index, className) {_x000D_
return (className.match ( new RegExp("\\b"+begin+"\\S+", "g") ) || []).join(' ');_x000D_
});_x000D_
}_x000D_
_x000D_
removeClassStartingWith($('#hello'), 'color-');_x000D_
_x000D_
console.log($("#hello")[0].className);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="hello" class="color-red color-brown foo bar"></div>
_x000D_
;WITH Split_Names (Name, xmlname)
AS
(
SELECT
Name,
CONVERT(XML,'<Names><name>'
+ REPLACE(Name,' ', '</name><name>') + '</name></Names>') AS xmlname
FROM somenames
)
SELECT
xmlname.value('/Names[1]/name[1]','varchar(100)') AS first_name,
xmlname.value('/Names[1]/name[2]','varchar(100)') AS last_name
FROM Split_Names
and also check the link below for reference
http://jahaines.blogspot.in/2009/06/converting-delimited-string-of-values.html
You don't need a for loop in your code.
Here is how you can re implement your method
Edit:
Here is hint for you to proceed, Following code snippet gives int
values for char
s
System.out.println("a="+(int)'a');
System.out.println("z="+(int)'z');
System.out.println("A="+(int)'A');
System.out.println("Z="+(int)'Z');
Output
a=97
z=122
A=65
Z=90
Here is how you can check if a number x
exists between two numbers say a
and b
// x greater than or equal to a and x less than or equal to b
if ( x >= a && x <= b )
During comparisons char
s can be treated as numbers
If you can combine these hints, you should be able to find what you want ;)
Here is a solution with shell parameter expansion that replaces multiple contiguous occurrences with a single _
:
$ var=AxxBCyyyDEFzzLMN
$ echo "${var//+([xyz])/_}"
A_BC_DEF_LMN
Notice that the +(pattern)
pattern requires extended pattern matching, turned on with
shopt -s extglob
Alternatively, with the -s
("squeeze") option of tr
:
$ tr -s xyz _ <<< "$var"
A_BC_DEF_LMN
I have a sample
import * as types from '../../helpers/ActionTypes';
var initialState = {
changedValues: {}
};
const quickEdit = (state = initialState, action) => {
switch (action.type) {
case types.PRODUCT_QUICKEDIT:
{
const item = action.item;
const changedValues = {
...state.changedValues,
[item.id]: item,
};
return {
...state,
loading: true,
changedValues: changedValues,
};
}
default:
{
return state;
}
}
};
export default quickEdit;
You should subscribe as a SensorEventListener
, and get the accelerometer
data.
Once you have it, you should monitor for sudden change in direction (sign) of acceleration on a certain axis. It would be a good indication for the 'shake'
movement of device.
Based on the answer by Eduard Florinescu, but with newer code and the missing imports added:
$ cat work-auth.py
#!/usr/bin/python3
# Setup:
# sudo apt-get install chromium-chromedriver
# sudo -H python3 -m pip install selenium
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('/usr/bin/chromedriver',options=chrome_options)
chrome_options.add_argument("user-data-dir=chrome-data")
driver.get('https://www.somedomainthatrequireslogin.com')
time.sleep(30) # Time to enter credentials
driver.quit()
$ cat work.py
#!/usr/bin/python3
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('/usr/bin/chromedriver',options=chrome_options)
driver.get('https://www.somedomainthatrequireslogin.com') # Already authenticated
time.sleep(10)
driver.quit()
update: a podfile.lock
is necessary and should not be ignored by version control, it keeps track of the versions of libraries installed at a certain pod install. (It's similar to gemfile.lock and composer.lock for rails and php dependency management, respectively). To learn more please read the docs. Credit goes to cbowns.
In my case, what I did was that I was doing some house cleaning for my project (ie branching out the integration tests as a git submodule.. removing duplicate files etc).. and pushed the final result to a git remote repo.. all the clients who cloned my repo suffered from the above error. Inspired by Hlung's comment above, I realized that there were some dangling pod scripts that were attempting to run against some non-existent files. So I went to my target build phase, and deleted all the remaining phases that had anything to do with cocoa pods (and Hlung's comment he suggests deleting Copy Pods Manifest.lock
and copy pod resources
.. mine were named different maybe b/c I'm using Xcode 5.. the point being is to delete those dangling build phases)..
To make the images flexible, simply add
max-width:100%
andheight:auto
. Imagemax-width:100%
andheight:auto
works in IE7, but not in IE8 (yes, another weird IE bug). To fix this, you need to addwidth:auto\9
for IE8.source: http://webdesignerwall.com/tutorials/responsive-design-with-css3-media-queries
for example :
img {
max-width: 100%;
height: auto;
width: auto\9; /* ie8 */
}
and then any images you add simply using the img tag will be flexible
JSFiddle example here. No JavaScript required. Works in latest versions of Chrome, Firefox and IE (which is all I've tested).
It works on firefox, if you change onClick() to click() in javascript part.
$("img.foo").click(function()_x000D_
{_x000D_
// Get the src of the image_x000D_
var src = $(this).attr("src");_x000D_
_x000D_
// Send Ajax request to backend.php, with src set as "img" in the POST data_x000D_
$.post("/backend.php", {"img": src});_x000D_
});
_x000D_
Combining two answers I came out with a solution, that might not look that pretty,
but It works!
It creates a thumbnail with a specific size that might be clicked to brings you to the max resolutions image.
[<img src="image.png" width="250"/>](image.png)
i think there should be entry of your your_module.ko in /lib/modules/uname -r
/modules.dep and in /lib/modules/uname -r
/modules.dep.bin for "modprobe your_module" command to work
Everyone else has posted "going backwards" answer, so I'll give the alternative: create a list of items you want to remove, then remove them at the end:
List<string> removals = new List<string>();
foreach (string s in listBox1.Items)
{
MessageBox.Show(s);
//do stuff with (s);
removals.Add(s);
}
foreach (string s in removals)
{
listBox1.Items.Remove(s);
}
Sometimes the "work backwards" method is better, sometimes the above is better - particularly if you're dealing with a type which has a RemoveAll(collection)
method. Worth knowing both though.
As mentioned by other here:
Interfaces are not necessary in Python. This is because Python has proper multiple inheritance, and also ducktyping, which means that the places where you must have interfaces in Java, you don't have to have them in Python.
That said, there are still several uses for interfaces. Some of them are covered by Pythons Abstract Base Classes, introduced in Python 2.6. They are useful, if you want to make base classes that cannot be instantiated, but provide a specific interface or part of an implementation.
Another usage is if you somehow want to specify that an object implements a specific interface, and you can use ABC's for that too by subclassing from them. Another way is zope.interface, a module that is a part of the Zope Component Architecture, a really awesomely cool component framework. Here you don't subclass from the interfaces, but instead mark classes (or even instances) as implementing an interface. This can also be used to look up components from a component registry. Supercool!
In certain cases, it might be necessary to restrict the display of a webpage to a document mode supported by an earlier version of Internet Explorer. You can do this by serving the page with an x-ua-compatible header. For more info, see Specifying legacy document modes.
- https://msdn.microsoft.com/library/cc288325
Thus this tag is used to future proof the webpage, such that the older / compatible engine is used to render it the same way as intended by the creator.
Make sure that you have checked it to work properly with the IE version you specify.
There is a way to capture tabs in a TextInput
. It's hacky, but better than nothing.
Define an onChangeText
handler that compares the new input value with the old, checking for a \t
. If one is found, advance the field as shown by @boredgames
Assuming the variable username
contains the value for the username and setUsername
dispatches an action to change it in the store (component state, redux store, etc), do something like this:
function tabGuard (newValue, oldValue, callback, nextCallback) {
if (newValue.indexOf('\t') >= 0 && oldValue.indexOf('\t') === -1) {
callback(oldValue)
nextCallback()
} else {
callback(newValue)
}
}
class LoginScene {
focusNextField = (nextField) => {
this.refs[nextField].focus()
}
focusOnPassword = () => {
this.focusNextField('password')
}
handleUsernameChange = (newValue) => {
const { username } = this.props // or from wherever
const { setUsername } = this.props.actions // or from wherever
tabGuard(newValue, username, setUsername, this.focusOnPassword)
}
render () {
const { username } = this.props
return (
<TextInput ref='username'
placeholder='Username'
autoCapitalize='none'
autoCorrect={false}
autoFocus
keyboardType='email-address'
onChangeText={handleUsernameChange}
blurOnSubmit={false}
onSubmitEditing={focusOnPassword}
value={username} />
)
}
}
Yes, it's possible to To capture div as PDFs in JS. You can can check the solution provided by https://grabz.it. They have nice and clean JavaScript API which will allow you to capture the content of a single HTML element such as a div or a span.
So, yo use it you will need and app+key and the free SDK. The usage of it is as following:
Let's say you have a HTML:
<div id="features">
<h4>Acme Camera</h4>
<label>Price</label>$399<br />
<label>Rating</label>4.5 out of 5
</div>
<p>Cras ut velit sed purus porttitor aliquam. Nulla tristique magna ac libero tempor, ac vestibulum felisvulput ate. Nam ut velit eget
risus porttitor tristique at ac diam. Sed nisi risus, rutrum a metus suscipit, euismod tristique nulla. Etiam venenatis rutrum risus at
blandit. In hac habitasse platea dictumst. Suspendisse potenti. Phasellus eget vehicula felis.</p>
To capture what is under the features id you will need to:
//add the sdk
<script type="text/javascript" src="grabzit.min.js"></script>
<script type="text/javascript">
//login with your key and secret.
GrabzIt("KEY", "SECRET").ConvertURL("http://www.example.com/my-page.html",
{"target": "#features", "format": "pdf"}).Create();
</script>
You need to replace the http://www.example.com/my-page.html
with your target url and #feature
per your CSS selector.
That's all. Now, when the page is loaded an image screenshot will now be created in the same location as the script tag, which will contain all of the contents of the features div and nothing else.
The are other configuration and customization you can do to the div-screenshot mechanism, please check them out here
Use this Way in this circle image is also working + you have preloader also for network image:
new ClipRRect(
borderRadius: new BorderRadius.circular(30.0),
child: FadeInImage.assetNetwork(
placeholder:'asset/loader.gif',
image: 'Your Image Path',
),
)
Use a function style conversion (found in section labeled "Integer and Floating-Point Conversion" from "The Swift Programming Language."[iTunes link])
1> Int(3.4)
$R1: Int = 3
All solutions based on array_keys don't work for mixed arrays. Solution is simple:
echo array_search($needle,array_keys($haystack), true);
From php.net: If the third parameter strict is set to TRUE then the array_search() function will search for identical elements in the haystack. This means it will also perform a strict type comparison of the needle in the haystack, and objects must be the same instance.
I prefer option 4, but it makes intuitive sense to me because I do far too much work in Grails, Groovy, and JavaFX. "Magic" connections between the view and the controller are common in all. It is important to name the method well:
In the view,add the onClick method to the button or other widget:
android:clickable="true"
android:onClick="onButtonClickCancel"
Then in the class, handle the method:
public void onButtonClickCancel(View view) {
Toast.makeText(this, "Cancel pressed", Toast.LENGTH_LONG).show();
}
Again, name the method clearly, something you should do anyway, and the maintenance becomes second-nature.
One big advantage is that you can write unit tests now for the method. Option 1 can do this, but 2 and 3 are more difficult.
You can browse Android SDK samples from your smartphone using "Code Search": https://market.android.com/details?id=sqwady.codesearch
Please follow this to by ajax call to webservice of java var param = { feildName: feildValue }; JSON.stringify({data : param})
$.ajax({
dataType : 'json',
type : 'POST',
contentType : 'application/json',
url : '<%=request.getContextPath()%>/rest/priceGroups',
data : JSON.stringify({data : param}),
success : function(res) {
if(res.success == true){
$('#alertMessage').html('Successfully price group created.').addClass('alert alert-success fade in');
$('#alertMessage').removeClass('alert-danger alert-info');
initPriceGroupsList();
priceGroupId = 0;
resetForm();
}else{
$('#alertMessage').html(res.message).addClass('alert alert-danger fade in');
}
$('#alertMessage').alert();
window.setTimeout(function() {
$('#alertMessage').removeClass('in');
document.getElementById('message').style.display = 'none';
}, 5000);
}
});
On my Fedora 23 machine I had to run the following:
sudo dnf install mysql-devel
This should work:
$("#table-filters>ul>li.active").removeClass("active");
//Find all `li`s with class `active`, children of `ul`s, children of `table-filters`
The easiest way is probably to use xvfb-run:
DISPLAY=:1 xvfb-run java -jar selenium-server-standalone-2.0b3.jar
xvfb-run does the whole X authority dance for you, give it a try!
(np.where(np.isnan(A)))[0].shape[0]
will be greater than 0
if A
contains at least one element of nan
, A
could be an n x m
matrix.
Example:
import numpy as np
A = np.array([1,2,4,np.nan])
if (np.where(np.isnan(A)))[0].shape[0]:
print "A contains nan"
else:
print "A does not contain nan"
This work out for me :
in javascript :
Axios({
method: 'post',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
url: 'https://localhost:44346/Order/Order/GiveOrder',
data: order
}).then(function (response) {
console.log(response.data);
});
and in the backend (.net core) : in startup:
#region Allow-Orgin
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
});
#endregion
and in controller before action
[EnableCors("AllowOrigin")]
You can use the inbuilt CONVERT
function
select CONVERT(varchar(3), Date, 100) as Month from MyTable.
This will display first 3 characters of month (JAN,FEB etc..)
This should do:
samp2 <- samp[,-1]
rownames(samp2) <- samp[,1]
So in short, no there is no alternative to reassigning.
Edit: Correcting myself, one can also do it in place: assign rowname attributes, then remove column:
R> df<-data.frame(a=letters[1:10], b=1:10, c=LETTERS[1:10])
R> rownames(df) <- df[,1]
R> df[,1] <- NULL
R> df
b c
a 1 A
b 2 B
c 3 C
d 4 D
e 5 E
f 6 F
g 7 G
h 8 H
i 9 I
j 10 J
R>
select count(*)
from table_emp
where DATEPART(YEAR, ARR_DATE) = '2012' AND DATEPART(MONTH, ARR_DATE) = '01'
Tried all the above, the last piece missing was to enable USB Debugging within Developer Options which was hidden on my 4.4 Galaxy Note 10.1.
See item 5.2 from this link.
I use this to avoid Console.WriteLine(...)
:
public static void Cout(this string str, params object[] args) {
Console.WriteLine(str, args);
}
and then you can use the following:
"line 1".Cout();
"This {0} is an {1}".Cout("sentence", "example");
it's concise and kindof funky.
I've found an answer to this problem :)
SET @update_id := 0;
UPDATE some_table SET column_name = 'value', id = (SELECT @update_id := id)
WHERE some_other_column = 'blah' LIMIT 1;
SELECT @update_id;
EDIT by aefxx
This technique can be further expanded to retrieve the ID of every row affected by an update statement:
SET @uids := null;
UPDATE footable
SET foo = 'bar'
WHERE fooid > 5
AND ( SELECT @uids := CONCAT_WS(',', fooid, @uids) );
SELECT @uids;
This will return a string with all the IDs concatenated by a comma.
require(ggplot2)
require(nlme)
set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)
mp <- within(mp,
{
wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
wow <- rnorm(N)*wav+rnorm(N)*wav^3
})
m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))
Get fitted values (the same as m01$fitted
)
fit <- predict(m01)
Normally we could use something like predict(...,se.fit=TRUE)
to get the confidence intervals on the prediction, but gls
doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :
V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))
Put together a "prediction frame":
predframe <- with(mp,data.frame(year,wav,
wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))
Now plot with geom_ribbon
(p1 <- ggplot(mp, aes(year, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It's easier to see that we got the right answer if we plot against wav
rather than year
:
(p2 <- ggplot(mp, aes(wav, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly()
fits -- see ?makepredictcall
.
Both these work for me. Maybe post a complete example?
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class PaneBackgroundTest extends Application {
@Override
public void start(Stage primaryStage) {
BorderPane root = new BorderPane();
VBox vbox = new VBox();
root.setCenter(vbox);
ToggleButton toggle = new ToggleButton("Toggle color");
HBox controls = new HBox(5, toggle);
controls.setAlignment(Pos.CENTER);
root.setBottom(controls);
// vbox.styleProperty().bind(Bindings.when(toggle.selectedProperty())
// .then("-fx-background-color: cornflowerblue;")
// .otherwise("-fx-background-color: white;"));
vbox.backgroundProperty().bind(Bindings.when(toggle.selectedProperty())
.then(new Background(new BackgroundFill(Color.CORNFLOWERBLUE, CornerRadii.EMPTY, Insets.EMPTY)))
.otherwise(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY))));
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
check fnAddData: https://legacy.datatables.net/ref
$(document).ready(function () {
var table = $('#example').dataTable();
var url = '/RESTApplicationTest/webresources/entity.person';
$.get(url, function (data) {
for (var i = 0; i < data.length; i++) {
table.fnAddData([data[i].idPerson, data[i].firstname, data[i].lastname, data[i].email, data[i].phone])
}
});
});
Perhaps a function along these lines is what you're after:
def add_unique_to_dict_list(dict_list, key, value):
for d in dict_list:
if key in d:
return d[key]
dict_list.append({ key: value })
return value
encodeURIComponent/decodeURIComponent() is almost always the pair you want to use, for concatenating together and splitting apart text strings in URI parts.
encodeURI in less common, and misleadingly named: it should really be called fixBrokenURI. It takes something that's nearly a URI, but has invalid characters such as spaces in it, and turns it into a real URI. It has a valid use in fixing up invalid URIs from user input, and it can also be used to turn an IRI (URI with bare Unicode characters in) into a plain URI (using %-escaped UTF-8 to encode the non-ASCII).
decodeURI decodes the same characters as decodeURIComponent except for a few special ones. It is provided to be an inverse of encodeURI, but you still can't count on it to return the same as you originally put in — see eg. decodeURI(encodeURI('%20 '));
.
Where encodeURI should really be named fixBrokenURI(), decodeURI() could equally be called potentiallyBreakMyPreviouslyWorkingURI(). I can think of no valid use for it anywhere; avoid.
This behavior is documented in the java.util.Date -class documentation:
Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.
It is also marked as deprecated. Use java.util.Calendar instead.
If you want to remove more characters for example "a", "A", "b", "B", "c", "C" from string you can do it this way:
someString = someString.replacingOccurrences(of: "[abc]", with: "", options: [.regularExpression, .caseInsensitive])
The approach I have taken is to just throw exceptions from the api controller actions and have an exception filter registered that processes the exception and sets an appropriate response on the action execution context.
The filter exposes a fluent interface that provides a means of registering handlers for specific types of exceptions prior to registering the filter with global configuration.
The use of this filter enables centralized exception handling instead of spreading it across the controller actions. There are however cases where I will catch exceptions within the controller action and return a specific response if it does not make sense to centralize the handling of that particular exception.
Example registration of filter:
GlobalConfiguration.Configuration.Filters.Add(
new UnhandledExceptionFilterAttribute()
.Register<KeyNotFoundException>(HttpStatusCode.NotFound)
.Register<SecurityException>(HttpStatusCode.Forbidden)
.Register<SqlException>(
(exception, request) =>
{
var sqlException = exception as SqlException;
if (sqlException.Number > 50000)
{
var response = request.CreateResponse(HttpStatusCode.BadRequest);
response.ReasonPhrase = sqlException.Message.Replace(Environment.NewLine, String.Empty);
return response;
}
else
{
return request.CreateResponse(HttpStatusCode.InternalServerError);
}
}
)
);
UnhandledExceptionFilterAttribute class:
using System;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http.Filters;
namespace Sample
{
/// <summary>
/// Represents the an attribute that provides a filter for unhandled exceptions.
/// </summary>
public class UnhandledExceptionFilterAttribute : ExceptionFilterAttribute
{
#region UnhandledExceptionFilterAttribute()
/// <summary>
/// Initializes a new instance of the <see cref="UnhandledExceptionFilterAttribute"/> class.
/// </summary>
public UnhandledExceptionFilterAttribute() : base()
{
}
#endregion
#region DefaultHandler
/// <summary>
/// Gets a delegate method that returns an <see cref="HttpResponseMessage"/>
/// that describes the supplied exception.
/// </summary>
/// <value>
/// A <see cref="Func{Exception, HttpRequestMessage, HttpResponseMessage}"/> delegate method that returns
/// an <see cref="HttpResponseMessage"/> that describes the supplied exception.
/// </value>
private static Func<Exception, HttpRequestMessage, HttpResponseMessage> DefaultHandler = (exception, request) =>
{
if(exception == null)
{
return null;
}
var response = request.CreateResponse<string>(
HttpStatusCode.InternalServerError, GetContentOf(exception)
);
response.ReasonPhrase = exception.Message.Replace(Environment.NewLine, String.Empty);
return response;
};
#endregion
#region GetContentOf
/// <summary>
/// Gets a delegate method that extracts information from the specified exception.
/// </summary>
/// <value>
/// A <see cref="Func{Exception, String}"/> delegate method that extracts information
/// from the specified exception.
/// </value>
private static Func<Exception, string> GetContentOf = (exception) =>
{
if (exception == null)
{
return String.Empty;
}
var result = new StringBuilder();
result.AppendLine(exception.Message);
result.AppendLine();
Exception innerException = exception.InnerException;
while (innerException != null)
{
result.AppendLine(innerException.Message);
result.AppendLine();
innerException = innerException.InnerException;
}
#if DEBUG
result.AppendLine(exception.StackTrace);
#endif
return result.ToString();
};
#endregion
#region Handlers
/// <summary>
/// Gets the exception handlers registered with this filter.
/// </summary>
/// <value>
/// A <see cref="ConcurrentDictionary{Type, Tuple}"/> collection that contains
/// the exception handlers registered with this filter.
/// </value>
protected ConcurrentDictionary<Type, Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>>> Handlers
{
get
{
return _filterHandlers;
}
}
private readonly ConcurrentDictionary<Type, Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>>> _filterHandlers = new ConcurrentDictionary<Type, Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>>>();
#endregion
#region OnException(HttpActionExecutedContext actionExecutedContext)
/// <summary>
/// Raises the exception event.
/// </summary>
/// <param name="actionExecutedContext">The context for the action.</param>
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
if(actionExecutedContext == null || actionExecutedContext.Exception == null)
{
return;
}
var type = actionExecutedContext.Exception.GetType();
Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>> registration = null;
if (this.Handlers.TryGetValue(type, out registration))
{
var statusCode = registration.Item1;
var handler = registration.Item2;
var response = handler(
actionExecutedContext.Exception.GetBaseException(),
actionExecutedContext.Request
);
// Use registered status code if available
if (statusCode.HasValue)
{
response.StatusCode = statusCode.Value;
}
actionExecutedContext.Response = response;
}
else
{
// If no exception handler registered for the exception type, fallback to default handler
actionExecutedContext.Response = DefaultHandler(
actionExecutedContext.Exception.GetBaseException(), actionExecutedContext.Request
);
}
}
#endregion
#region Register<TException>(HttpStatusCode statusCode)
/// <summary>
/// Registers an exception handler that returns the specified status code for exceptions of type <typeparamref name="TException"/>.
/// </summary>
/// <typeparam name="TException">The type of exception to register a handler for.</typeparam>
/// <param name="statusCode">The HTTP status code to return for exceptions of type <typeparamref name="TException"/>.</param>
/// <returns>
/// This <see cref="UnhandledExceptionFilterAttribute"/> after the exception handler has been added.
/// </returns>
public UnhandledExceptionFilterAttribute Register<TException>(HttpStatusCode statusCode)
where TException : Exception
{
var type = typeof(TException);
var item = new Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>>(
statusCode, DefaultHandler
);
if (!this.Handlers.TryAdd(type, item))
{
Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>> oldItem = null;
if (this.Handlers.TryRemove(type, out oldItem))
{
this.Handlers.TryAdd(type, item);
}
}
return this;
}
#endregion
#region Register<TException>(Func<Exception, HttpRequestMessage, HttpResponseMessage> handler)
/// <summary>
/// Registers the specified exception <paramref name="handler"/> for exceptions of type <typeparamref name="TException"/>.
/// </summary>
/// <typeparam name="TException">The type of exception to register the <paramref name="handler"/> for.</typeparam>
/// <param name="handler">The exception handler responsible for exceptions of type <typeparamref name="TException"/>.</param>
/// <returns>
/// This <see cref="UnhandledExceptionFilterAttribute"/> after the exception <paramref name="handler"/>
/// has been added.
/// </returns>
/// <exception cref="ArgumentNullException">The <paramref name="handler"/> is <see langword="null"/>.</exception>
public UnhandledExceptionFilterAttribute Register<TException>(Func<Exception, HttpRequestMessage, HttpResponseMessage> handler)
where TException : Exception
{
if(handler == null)
{
throw new ArgumentNullException("handler");
}
var type = typeof(TException);
var item = new Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>>(
null, handler
);
if (!this.Handlers.TryAdd(type, item))
{
Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>> oldItem = null;
if (this.Handlers.TryRemove(type, out oldItem))
{
this.Handlers.TryAdd(type, item);
}
}
return this;
}
#endregion
#region Unregister<TException>()
/// <summary>
/// Unregisters the exception handler for exceptions of type <typeparamref name="TException"/>.
/// </summary>
/// <typeparam name="TException">The type of exception to unregister handlers for.</typeparam>
/// <returns>
/// This <see cref="UnhandledExceptionFilterAttribute"/> after the exception handler
/// for exceptions of type <typeparamref name="TException"/> has been removed.
/// </returns>
public UnhandledExceptionFilterAttribute Unregister<TException>()
where TException : Exception
{
Tuple<HttpStatusCode?, Func<Exception, HttpRequestMessage, HttpResponseMessage>> item = null;
this.Handlers.TryRemove(typeof(TException), out item);
return this;
}
#endregion
}
}
Source code can also be found here.
(more of a functional note)
There are cases when you have to use GROUP BY, for example if you wanted to get the number of employees per employer:
SELECT u.employer, COUNT(u.id) AS "total employees" FROM users u GROUP BY u.employer
In such a scenario DISTINCT u.employer
doesn't work right. Perhaps there is a way, but I just do not know it. (If someone knows how to make such a query with DISTINCT please add a note!)
This worked for me:
min-height: 14px;
height: 14px;
Use localStorage for that. It's persistent over sessions.
Writing :
localStorage['myKey'] = 'somestring'; // only strings
Reading :
var myVar = localStorage['myKey'] || 'defaultValue';
If you need to store complex structures, you might serialize them in JSON. For example :
Reading :
var stored = localStorage['myKey'];
if (stored) myVar = JSON.parse(stored);
else myVar = {a:'test', b: [1, 2, 3]};
Writing :
localStorage['myKey'] = JSON.stringify(myVar);
Note that you may use more than one key. They'll all be retrieved by all pages on the same domain.
Unless you want to be compatible with IE7, you have no reason to use the obsolete and small cookies.
Unfortunately, the best method to approach this is to use Internet Explorer as it's a browser that is guaranteed to be on Windows based machines. This will also bring compatibility of other users which might have alternative browsers such as Firefox, Chrome, Opera..etc,
start "iexplore.exe" http://www.website.com
I think I got there in the end.
The task is like this:
- name: Populate genders
set_fact:
genders: "{{ genders|default({}) | combine( {item.item.name: item.stdout} ) }}"
with_items: "{{ people.results }}"
It loops through each of the dicts (item
) in the people.results
array, each time creating a new dict like {Bob: "male"}
, and combine()
s that new dict in the genders
array, which ends up like:
{
"Bob": "male",
"Thelma": "female"
}
It assumes the keys (the name
in this case) will be unique.
I then realised I actually wanted a list of dictionaries, as it seems much easier to loop through using with_items
:
- name: Populate genders
set_fact:
genders: "{{ genders|default([]) + [ {'name': item.item.name, 'gender': item.stdout} ] }}"
with_items: "{{ people.results }}"
This keeps combining the existing list with a list containing a single dict. We end up with a genders
array like this:
[
{'name': 'Bob', 'gender': 'male'},
{'name': 'Thelma', 'gender': 'female'}
]
To compare Strings for equality, don't use ==. The == operator checks to see if two objects are exactly the same object:
In Java there are many string comparisons.
String s = "something", t = "maybe something else";
if (s == t) // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT
if (s > t) // ILLEGAL
if (s.compareTo(t) > 0) // also CORRECT>
Your class MyClass
creates a new MyClassToBeTested
, instead of using your mock. My article on the Mockito wiki describes two ways of dealing with this.
Would you be happy with your Python command running another program to get the info?
If so, I'd suggest you have a look at PsList and all its options. For example, The following would tell you about any running iTunes process
PsList itunes
If you can work out how to interpret the results, this should hopefully get you going.
Edit:
When I'm not running iTunes, I get the following:
pslist v1.29 - Sysinternals PsList
Copyright (C) 2000-2009 Mark Russinovich
Sysinternals
Process information for CLARESPC:
Name Pid Pri Thd Hnd Priv CPU Time Elapsed Time
iTunesHelper 3784 8 10 229 3164 0:00:00.046 3:41:05.053
With itunes running, I get this one extra line:
iTunes 928 8 24 813 106168 0:00:08.734 0:02:08.672
However, the following command prints out info only about the iTunes program itself, i.e. with the -e
argument:
pslist -e itunes
Use git clean
Get help on this running
git clean -h
If you want to see what would happen first, make sure to pass the -n switch for a dry run:
git clean -xn
To remove gitingnored garbage
git clean -xdf
Careful: You may be ignoring local config files like database.yml which would also be removed. Use at your own risk.
Then
git add .
git commit -m ".gitignore is now working"
git push
expand "Java Resources" and then 'Libraries' (in eclipse project). make sure that "Apache Tomcat" present.
if not follow- right click on project -> "Build Path" -> "Java Build Path" -> "Add Library" -> select "Server Runtime" -> next -> select "Apache Tomcat -> click finish
Yes, cd; and cd - would work. The reason It can see is that, directory is being deleted from any other terminal or any other program and recreate it. So i-node entry is modified so program can not access old i-node entry.
It means you don't have privileges to create the trigger with root@localhost user..
try removing definer from the trigger command:
CREATE DEFINER = root
@localhost
FUNCTION fnc_calcWalkedDistance
I don't think maven supports this. If you're on Unix, and don't want to leave your current directory, you could use a small shell script, a shell function, or just a sub-shell:
user@host ~/project$ (cd ~/some/location; mvn install)
[ ... mvn build ... ]
user@host ~/project$
As a bash function (which you could add to your ~/.bashrc):
function mvn-there() {
DIR="$1"
shift
(cd $DIR; mvn "$@")
}
user@host ~/project$ mvn-there ~/some/location install)
[ ... mvn build ... ]
user@host ~/project$
I realize this doesn't answer the specific question, but may provide you with what you're after. I'm not familiar with the Windows shell, though you should be able to reach a similar solution there as well.
Regards
3D case
Modifying Mohsen's answer for 3D array:
[M,I] = max (A(:));
[ind1, ind2, ind3] = ind2sub(size(A),I)
Greetings! I know this is an older post, but I found it through Google when searching for "javascript add large block of html as variable". I thought I'd post an alternate solution.
First, I'd recommend using single-quotes around the variable itself ... makes it easier to preserve double-quotes in the actual HTML code.
You can use a backslash to separate lines if you want to maintain a sense of formatting to the code:
var code = '<div class="my-class"> \
<h1>The Header</h1> \
<p>The paragraph of text</p> \
<div class="my-quote"> \
<p>The quote I\'d like to put in a div</p> \
</div> \
</div>';
Note: You'll obviously need to escape any single-quotes inside the code (e.g. inside the last 'p' tag)
Anyway, I hope that helps someone else that may be looking for the same answer I was ... Cheers!
Starting from Java 1.7 you can use try-with-resources like this:
private Integer findRandomOpenPortOnAllLocalInterfaces() throws IOException {
try (
ServerSocket socket = new ServerSocket(0);
) {
return socket.getLocalPort();
}
}
If you need to find an open port on a specific interface check ServerSocket documentation for alternative constructors.
Warning: Any code using the port number returned by this method is subject to a race condition - a different process / thread may bind to the same port immediately after we close the ServerSocket instance.
Here's a solution that supports finding the difference even if the end time is less than the start time (over midnight interval) such as 23:55:00-00:25:00
(a half an hour duration):
#!/usr/bin/env python
from datetime import datetime, time as datetime_time, timedelta
def time_diff(start, end):
if isinstance(start, datetime_time): # convert to datetime
assert isinstance(end, datetime_time)
start, end = [datetime.combine(datetime.min, t) for t in [start, end]]
if start <= end: # e.g., 10:33:26-11:15:49
return end - start
else: # end < start e.g., 23:55:00-00:25:00
end += timedelta(1) # +day
assert end > start
return end - start
for time_range in ['10:33:26-11:15:49', '23:55:00-00:25:00']:
s, e = [datetime.strptime(t, '%H:%M:%S') for t in time_range.split('-')]
print(time_diff(s, e))
assert time_diff(s, e) == time_diff(s.time(), e.time())
0:42:23
0:30:00
time_diff()
returns a timedelta object that you can pass (as a part of the sequence) to a mean()
function directly e.g.:
#!/usr/bin/env python
from datetime import timedelta
def mean(data, start=timedelta(0)):
"""Find arithmetic average."""
return sum(data, start) / len(data)
data = [timedelta(minutes=42, seconds=23), # 0:42:23
timedelta(minutes=30)] # 0:30:00
print(repr(mean(data)))
# -> datetime.timedelta(0, 2171, 500000) # days, seconds, microseconds
The mean()
result is also timedelta()
object that you can convert to seconds (td.total_seconds()
method (since Python 2.7)), hours (td / timedelta(hours=1)
(Python 3)), etc.
Without Error Handeling
//Load background texture
new THREE.TextureLoader();
loader.load('https://images.pexels.com/photos/1205301/pexels-photo-1205301.jpeg' , function(texture)
{
scene.background = texture;
});
With Error Handling
// Function called when download progresses
var onProgress = function (xhr) {
console.log((xhr.loaded / xhr.total * 100) + '% loaded');
};
// Function called when download errors
var onError = function (error) {
console.log('An error happened'+error);
};
//Function called when load completes.
var onLoad = function (texture) {
var objGeometry = new THREE.BoxGeometry(30, 30, 30);
var objMaterial = new THREE.MeshPhongMaterial({
map: texture,
shading: THREE.FlatShading
});
var boxMesh = new THREE.Mesh(objGeometry, objMaterial);
scene.add(boxMesh);
var render = function () {
requestAnimationFrame(render);
boxMesh.rotation.x += 0.010;
boxMesh.rotation.y += 0.010;
sphereMesh.rotation.y += 0.1;
renderer.render(scene, camera);
};
render();
}
//LOAD TEXTURE and on completion apply it on box
var loader = new THREE.TextureLoader();
loader.load('https://upload.wikimedia.org/wikipedia/commons/thumb/9/97/The_Earth_seen_from_Apollo_17.jpg/1920px-The_Earth_seen_from_Apollo_17.jpg',
onLoad,
onProgress,
onError);
Result:
I've decided to post since I don't like any of these answers -- things can always be more simple and this is by far the most concise way I've found.
1. Build your Xib in Interface Builder as you like it
2. In your UIViewController or UITableViewController subclass
@implementation ViewController
static NSString *cellIdentifier = @"MyCellIdentier";
- (void) viewDidLoad {
...
[self.tableView registerNib:[UINib nibWithNibName:@"MyTableViewCellSubclass" bundle:nil] forCellReuseIdentifier:cellIdentifier];
}
- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyTableViewCellSubclass *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
...
return cell;
}
3. In your MyTableViewCellSubclass
- (id) initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
...
}
return self;
}
Ruby has a few methods for changing the case of strings. To convert to lowercase, use downcase
:
"hello James!".downcase #=> "hello james!"
Similarly, upcase
capitalizes every letter and capitalize
capitalizes the first letter of the string but lowercases the rest:
"hello James!".upcase #=> "HELLO JAMES!"
"hello James!".capitalize #=> "Hello james!"
"hello James!".titleize #=> "Hello James!"
If you want to modify a string in place, you can add an exclamation point to any of those methods:
string = "hello James!"
string.downcase!
string #=> "hello james!"
Refer to the documentation for String for more information.
Try this:
grep "string to search for" FileNameToSearch | cut -d ":" -f 4 | sort -n | uniq -c
Sample:
grep "SMTP connect from unknown" maillog | cut -d ":" -f 4 | sort -n | uniq -c
6 SMTP connect from unknown [188.190.118.90]
54 SMTP connect from unknown [62.193.131.114]
3 SMTP connect from unknown [91.222.51.253]
You can simply use../your_script_name.py
For example suppose the path to your python script is trading system/trading strategies/ts1.py
. To refer to volume.csv
located in trading system/data/
. You simply need to refer to it as ../data/volume.csv
This is the simplest way to loop through a form accessing only the form elements. Inside the each function you can check and build whatever you want. When building objects note that you will want to declare it outside of the each function.
EDIT JSFIDDLE
The below will work
$('form[name=formName]').find('input, textarea, select').each(function() {
alert($(this).attr('name'));
});
import hashlib
user = input("Enter ")
h = hashlib.md5(user.encode())
h2 = h.hexdigest()
with open("encrypted.txt","w") as e:
print(h2,file=e)
with open("encrypted.txt","r") as e:
p = e.readline().strip()
print(p)
Your task declaration is incorrectly combining the Copy
task type and project.copy
method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy
isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File
API) will do. Assuming Project1
is the project directory:
task renABCToXYZ { doLast { file("ABC").renameTo(file("XYZ")) } }
Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast
task action) to the task that produces ABC
.
My Jenkins version: 1.5.39
Execute steps:
Step 1. Go to folder /Library/Application Support/Jenkins
Step 2. Run Uninstall.command jenkins-runner.sh
file.
Step 3. Check result.
It work for me.
It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.
Let's say you have something like this in your code:
$str = "test";
echo($str{0});
since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:
$str = "test";
echo($str[0]);
Fixing the code in the question will look something like this:
public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
$records = $this->listRecords($zoneID, $type, $name);
if (isset($records->result[0]->id)) {
return $records->result[0]->id;
}
return false;
}
expr match "$LIST" '$SOURCE'
don't work because of this function search $SOURCE from begin of the string and return the position just after pattern $SOURCE if found else 0. So you must write another code:
expr match "$LIST" '.*'"$SOURCE" or expr "$LIST" : '.*'"$SOURCE"
The expression $SOURCE must be double quoted so as a parser may set substitution. Single quoted not substitute and the code above will search textual string $SOURCE from the beginning of the $LIST. If you need the beginning of the string subtract the length $SOURCE e.g ${#SOURCE}. You may write also
expr "$LIST" : ".*\($SOURCE\)"
This function just extract $SOURCE from $LIST and return it. You'll get empty string else. But they problem with double double quote. I don't know how it resolve without using additional variable. It's light solution. So you may write in C. There is ready function strstr. Don't use expr index, So is very attractive. But index search not substring and only first char.
This error can also show up if there are parts in your string that json.loads()
does not recognize. An in this example string, an error will be raised at character 27 (char 27)
.
string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""
My solution to this would be to use the string.replace()
to convert these items to a string:
import json
string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""
string = string.replace("False", '"False"')
dict_list = json.loads(string)
There are some differences in calling conventions in C++ and Java. In C++ there are technically speaking only two conventions: pass-by-value and pass-by-reference, with some literature including a third pass-by-pointer convention (that is actually pass-by-value of a pointer type). On top of that, you can add const-ness to the type of the argument, enhancing the semantics.
Pass by reference
Passing by reference means that the function will conceptually receive your object instance and not a copy of it. The reference is conceptually an alias to the object that was used in the calling context, and cannot be null. All operations performed inside the function apply to the object outside the function. This convention is not available in Java or C.
Pass by value (and pass-by-pointer)
The compiler will generate a copy of the object in the calling context and use that copy inside the function. All operations performed inside the function are done to the copy, not the external element. This is the convention for primitive types in Java.
An special version of it is passing a pointer (address-of the object) into a function. The function receives the pointer, and any and all operations applied to the pointer itself are applied to the copy (pointer), on the other hand, operations applied to the dereferenced pointer will apply to the object instance at that memory location, so the function can have side effects. The effect of using pass-by-value of a pointer to the object will allow the internal function to modify external values, as with pass-by-reference and will also allow for optional values (pass a null pointer).
This is the convention used in C when a function needs to modify an external variable, and the convention used in Java with reference types: the reference is copied, but the referred object is the same: changes to the reference/pointer are not visible outside the function, but changes to the pointed memory are.
Adding const to the equation
In C++ you can assign constant-ness to objects when defining variables, pointers and references at different levels. You can declare a variable to be constant, you can declare a reference to a constant instance, and you can define all pointers to constant objects, constant pointers to mutable objects and constant pointers to constant elements. Conversely in Java you can only define one level of constant-ness (final keyword): that of the variable (instance for primitive types, reference for reference types), but you cannot define a reference to an immutable element (unless the class itself is immutable).
This is extensively used in C++ calling conventions. When the objects are small you can pass the object by value. The compiler will generate a copy, but that copy is not an expensive operation. For any other type, if the function will not change the object, you can pass a reference to a constant instance (usually called constant reference) of the type. This will not copy the object, but pass it into the function. But at the same time the compiler will guarantee that the object is not changed inside the function.
Rules of thumb
This are some basic rules to follow:
There are other small deviations from these rules, the first of which is handling ownership of an object. When an object is dynamically allocated with new, it must be deallocated with delete (or the [] versions thereof). The object or function that is responsible for the destruction of the object is considered the owner of the resource. When a dynamically allocated object is created in a piece of code, but the ownership is transfered to a different element it is usually done with pass-by-pointer semantics, or if possible with smart pointers.
Side note
It is important to insist in the importance of the difference between C++ and Java references. In C++ references are conceptually the instance of the object, not an accessor to it. The simplest example is implementing a swap function:
// C++
class Type; // defined somewhere before, with the appropriate operations
void swap( Type & a, Type & b ) {
Type tmp = a;
a = b;
b = tmp;
}
int main() {
Type a, b;
Type old_a = a, old_b = b;
swap( a, b );
assert( a == old_b );
assert( b == old_a );
}
The swap function above changes both its arguments through the use of references. The closest code in Java:
public class C {
// ...
public static void swap( C a, C b ) {
C tmp = a;
a = b;
b = tmp;
}
public static void main( String args[] ) {
C a = new C();
C b = new C();
C old_a = a;
C old_b = b;
swap( a, b );
// a and b remain unchanged a==old_a, and b==old_b
}
}
The Java version of the code will modify the copies of the references internally, but will not modify the actual objects externally. Java references are C pointers without pointer arithmetic that get passed by value into functions.
I have found that within the socket.handshake.headers there is a forwarded for address which doesn't appear on my local machine. And I was able to get the remote address using:
socket.handshake.headers['x-forwarded-for']
This is in the server side and not client side.
I think this should do the trick (untested):
Page.Response.Redirect(Page.Request.Url.ToString(), true);
You should try this syntax - assuming you want to have @OrderID
as a parameter for your stored procedure:
CREATE PROCEDURE dbo.YourStoredProcNameHere
@OrderID INT
AS
BEGIN
DECLARE @OrderItemID AS INT
DECLARE @AppointmentID AS INT
DECLARE @PurchaseOrderID AS INT
DECLARE @PurchaseOrderItemID AS INT
DECLARE @SalesOrderID AS INT
DECLARE @SalesOrderItemID AS INT
SELECT @OrderItemID = OrderItemID
FROM [OrderItem]
WHERE OrderID = @OrderID
SELECT @AppointmentID = AppoinmentID
FROM [Appointment]
WHERE OrderID = @OrderID
SELECT @PurchaseOrderID = PurchaseOrderID
FROM [PurchaseOrder]
WHERE OrderID = @OrderID
END
OF course, that only works if you're returning exactly one value (not multiple values!)
If you use android studio, this might be useful for you.
I had a similar problem and i solved it by changing the skd path from the default C:\Program Files (x86)\Android\android-studio\sdk to C:\Program Files (x86)\Android\android-sdk .
It seems the problem came from the compiler version (gradle sets it automatically to the highest one available in the sdk folder) which doesn't support this theme, and since android studio had only the api 7 in its sdk folder, it gave me this error.
For more information on how to change Android sdk path in Android Studio: Android Studio - How to Change Android SDK Path
Set the DIV's z-index to one larger than the other DIVs. You'll also need to make sure the DIV has a position
other than static
set on it, too.
CSS:
#someDiv {
z-index:9;
}
Read more here: http://coding.smashingmagazine.com/2009/09/15/the-z-index-css-property-a-comprehensive-look/
Note: Don’t confuse RUN with CMD. RUN actually runs a command and commits the result; CMD does not execute anything at build time, but specifies the intended command for the image.
from docker file reference
You can use COALESCE
in conjunction with NULLIF
for a short, efficient solution:
COALESCE( NULLIF(yourField,'') , '0' )
The NULLIF
function will return null if yourField
is equal to the second value (''
in the example), making the COALESCE
function fully working on all cases:
QUERY | RESULT
---------------------------------------------------------------------------------
SELECT COALESCE(NULLIF(null ,''),'0') | '0'
SELECT COALESCE(NULLIF('' ,''),'0') | '0'
SELECT COALESCE(NULLIF('foo' ,''),'0') | 'foo'
Remember that casing is a locale specific operation. Depending on scenario you may want to take that in to account. For example, if you are comparing names of two people you may want to consider locale but if you are comparing machine generated values such as UUID then you might not. This why I use following function in my utils library (note that type checking is not included for performance reason).
function compareStrings (string1, string2, ignoreCase, useLocale) {
if (ignoreCase) {
if (useLocale) {
string1 = string1.toLocaleLowerCase();
string2 = string2.toLocaleLowerCase();
}
else {
string1 = string1.toLowerCase();
string2 = string2.toLowerCase();
}
}
return string1 === string2;
}
The parent div (I assume the outermost div) is display: block
and will fill up all available area of its container (in this case, the body) that it can. Use a different display type -- inline-block
is probably what you are going for:
<?php
// Assuming the above tags are at www.example.com
$tags = get_meta_tags('http://www.example.com/');
// Notice how the keys are all lowercase now, and
// how . was replaced by _ in the key.
echo $tags['author']; // name
echo $tags['keywords']; // php documentation
echo $tags['description']; // a php manual
echo $tags['geo_position']; // 49.33;-86.59
?>
A simpler answer is to manually upload the README.MD file from your computer to GitHub. Worked very well for me.
There is a bug reported for Pillow here, which indicates that libjpeg
and zlib
are now required as of Pillow 3.0.0.
The installation instructions for Pillow on Linux give advice of how to install these packages. Note that not all of the following packages may be missing on your machine (comments suggest that only libjpeg8-dev
is actually missing).
The latest releases of Pillow are available on PyPi as wheels — the new standard packaging mechanism for Python. These prebuilt packages include all neccessary binary dependencies to allow Pillow to run and should be used if you want to install Pillow using PyPi
To use wheels, you need to have a version of pip>=1.4
. If you are using an earlier version (pip --version
) upgrade pip using the following:
pip install --upgrade pip
Once pip
is upgraded, pip install
will use platform-specific wheel files by default if they are available. Use the following command to upgrade Pillow to the latest version available on PyPi:
pip install --upgrade pillow
sudo apt-get install libtiff4-dev libjpeg8-dev zlib1g-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.5-dev tk8.5-dev python-tk
sudo apt-get install libtiff5-dev libjpeg8-dev zlib1g-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev python-tk
sudo apt install libjpeg8-dev zlib1g-dev
The Fedora 20 equivalent of libjpeg8-dev
is libjpeg-devel
.
sudo yum install libtiff-devel libjpeg-devel libzip-devel freetype-devel lcms2-devel libwebp-devel tcl-devel tk-devel
On Mac OS X with Homebrew this can be fixed using:
brew install libjpeg zlib
You may also need to force-link zlib using the following:
brew link zlib --force
Update April 2019: In Mojave the above will not work and you need to run the following as taken from this bug report on Pillow
sudo installer -pkg /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg -target /
Update July 2016: There is no longer a formula for zlib
available in the main repository (Homebrew will prompt you to install lzlib
which is a different library and will not solve this problem).
There is a formula available in the dupes repository. You can either tap this repository, and install as normal:
brew tap homebrew/dupes
brew install zlib
Or you can install zlib
via xcode
instead, as follows:
xcode-select --install
Thanks to phoenix, Panos Angelopoulou, nelsonvarela, benjaminz and Kal in the comments
After these are installed the pip installation of Pillow should work normally.
When a module is loaded from a file in Python, __file__
is set to its path. You can then use that with other functions to find the directory that the file is located in.
Taking your examples one at a time:
A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.
B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.
C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.
You can see the various values returned from these here:
import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))
and make sure you run it from different locations (such as ./text.py
, ~/python/text.py
and so forth) to see what difference that makes.
I just want to address some confusion first. __file__
is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.
http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.
In this case __file__
is an attribute of a module (a module object). In Python a .py
file is a module. So import amodule
will have an attribute of __file__
which means different things under difference circumstances.
Taken from the docs:
__file__
is the pathname of the file from which the module was loaded, if it was loaded from a file. The__file__
attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.
In your case the module is accessing it's own __file__
attribute in the global namespace.
To see this in action try:
# file: test.py
print globals()
print __file__
And run:
python test.py
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py
try this easy
_x000D_
.btn-circle span {_x000D_
top: 0;_x000D_
_x000D_
position: absolute;_x000D_
font-size: 18px;_x000D_
text-align: center;_x000D_
text-decoration: none;_x000D_
-webkit-animation:spin 4s linear infinite;_x000D_
-moz-animation:spin 4s linear infinite;_x000D_
animation:spin 4s linear infinite;_x000D_
}_x000D_
_x000D_
.btn-circle span :hover {_x000D_
color :silver;_x000D_
}_x000D_
_x000D_
_x000D_
/* rotate 360 key for refresh btn */_x000D_
@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }_x000D_
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }_x000D_
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }
_x000D_
<button type="button" class="btn btn-success btn-circle" ><span class="glyphicon">↻</span></button>
_x000D_
This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....
To cover the identities listed:
IIS_IUSRS:
This is analogous to the old IIS6 IIS_WPG
group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.
IUSR:
This account is analogous to the old IUSR_<MACHINE_NAME>
local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).
For more information about IIS_IUSRS
and IUSR
see:
DefaultAppPool:
If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name>
will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool
created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>
. You also won't see these pool accounts in your computers User Manager. See the following for more information:
ASP.NET v4.0:
-
This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool
above.
NETWORK SERVICE:
-
The NETWORK SERVICE
account is a built-in identity introduced on Windows 2003. NETWORK SERVICE
is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).
In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE
). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" />
setting in web.config
file locally (if that setting is locked then it would need to be done by an admin in the machine.config
file).
Setting <identity impersonate="true">
is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).
In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR
or a specific custom anonymous account.
LOCAL SERVICE:
The LOCAL SERVICE
account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:
LOCAL SYSTEM:
You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.
In Practice:
In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity
. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity
:
In the website you should then configure the Authentication feature:
Right click and edit the Anonymous Authentication entry:
Ensure that "Application pool identity" is selected:
When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0
pool permissions then you can either do this via Explorer:
Click the "Check Names" button:
Or you can do this using the ICACLS.EXE
utility:
icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)
...or...if you site's application pool is called BobsCatPicBlog
then:
icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)
I hope this helps clear things up.
Update:
I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:
The difference between the 'Local System' account and the 'Network Service' account?
I'd like to add another solution since I didn't see it here. My problem was that heroku was linking to the wrong url (since I kept playing around with url names). Editing the remote url solved my problem:
git remote set-url heroku <heroku-url-here>
TLDR;
Before we start, remember that all disadvantages of something are a continuation of its advantages. There only a right tool for a job, no panacea. TCP/UDP coexist for decades, and for a reason.
TCP
It was designed to be extremely reliable and it does its job very well. It's so complex because it accomplishes a hard task: providing a reliable transport over the unreliable IP protocol.
Since all TCP's complex logic is encapsulated into the network stack, you are free from doing lots of laborious, error-prone low-level stuff in the application layer.
When you send data over TCP, you write a stream of bytes to the socket at the sender side where it gets broken into packets, passed down the stack and sent over the wire. On the receiver side packets get reassembled again into a continous stream of bytes.
Maintaining this nice abstraction has a cost in terms of complexity and performance. If the 1st packet from the byte stream is lost, the receiver will delay processing of subsequent packets even those have already arrived (the so-called "head of line blocking").
In addition, in order to be reliable, TCP implements this:
All this is exacerbated in slow unreliable wireless networks because TCP was designed for wired networks where delays are predictable and packet loss is not so common. In addition, like many people already mentioned, for some things TCP just doesn't work at all (DHCP). However, where relevant, TCP still does its work exceptionally well.
Using a mail analogy a TCP session is similar to telling a story to your secretary who breaks it into mails and sends over a crappy mail service to a publisher. On the other side another secretary assembles mails into a single piece of text. Some mails get lost, some get corrupted, so a very complex procedure is required for reliable delivery and your 10-page story can take a long time to reach your publisher.
UDP
UDP, on the other hand, is message-oriented, so a receiver writes a message (packet) to the socket and then it gets transmitted to a receiver as-is, without any splitting/assembling in the transport layer.
Compared to TCP, its specification is very straightforward. Essentially, all it does for you is adding a checksum to the packet so a receiver can detect its corruption. Everything else must be implemented by you, a software developer. Now read the voluminous TCP spec and try thinking of re-implementing even a small subset of it.
Some people went this way and got very decent results, to the point that HTTP/3 uses QUIC - a protocol based on UDP. However, this is more of an exception. Common applications of UDP are audio/video streaming and conferencing applications like Skype, Zoom or Google Hangout where loosing packets is not so important compared to a delay introduced by TCP.
CMake 3.13 on Ubuntu 16.04
This approach is more flexible because it doesn't constraint MY_VARIABLE to a type:
$ cat CMakeLists.txt
message("MY_VARIABLE=${MY_VARIABLE}")
if( MY_VARIABLE )
message("MY_VARIABLE evaluates to True")
endif()
$ mkdir build && cd build
$ cmake ..
MY_VARIABLE=
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
$ cmake .. -DMY_VARIABLE=True
MY_VARIABLE=True
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
$ cmake .. -DMY_VARIABLE=False
MY_VARIABLE=False
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
$ cmake .. -DMY_VARIABLE=1
MY_VARIABLE=1
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
$ cmake .. -DMY_VARIABLE=0
MY_VARIABLE=0
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
Here's an update as of Nov 2014. I find that setting method='curl'
did the trick for me (while method='auto'
, does not).
For example:
# does not work
download.file(url='https://s3.amazonaws.com/tripdata/201307-citibike-tripdata.zip',
destfile='localfile.zip')
# does not work. this appears to be the default anyway
download.file(url='https://s3.amazonaws.com/tripdata/201307-citibike-tripdata.zip',
destfile='localfile.zip', method='auto')
# works!
download.file(url='https://s3.amazonaws.com/tripdata/201307-citibike-tripdata.zip',
destfile='localfile.zip', method='curl')
sub domain is part of the domain, it's like subletting a room of an apartment. A records has to be setup on the dns for the domain e.g
mydomain.com has IP 123.456.789.999 and hosted with Godaddy. Now to get the sub domain
anothersite.mydomain.com
of which the site is actually on another server then
login to Godaddy and add an A record dnsimple anothersite.mydomain.com and point the IP to the other server 98.22.11.11
And that's it.
After isntalling jdk please restart your system this works for me
I have used this to some of my projects before and was able to solved most of my COLLATION problems. (especially on JOINS XD) Hope some of you find it useful.
To use, just export results to delimited text (probably new line '\n')
-- EACH TABLE
SELECT CONCAT('ALTER TABLE ', TABLE_NAME,'
CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;') AS 'USE DATABASE_NAME
;'
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DATABASE_NAME'
AND TABLE_TYPE LIKE 'BASE TABLE'
-- EACH COLUMN
SELECT CONCAT('ALTER TABLE ', TABLE_NAME,'
MODIFY COLUMN ', COLUMN_NAME,'
', DATA_TYPE, IF(CHARACTER_MAXIMUM_LENGTH IS NULL OR DATA_TYPE LIKE 'longtext', '', CONCAT('(',CHARACTER_MAXIMUM_LENGTH,')')),' COLLATE utf8mb4_unicode_ci;') AS 'USE DATABASE_NAME
;'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'DATABASE_NAME' AND (SELECT INFORMATION_SCHEMA.TABLES.TABLE_TYPE FROM INFORMATION_SCHEMA.TABLES WHERE INFORMATION_SCHEMA.TABLES.TABLE_SCHEMA = INFORMATION_SCHEMA.COLUMNS.TABLE_SCHEMA AND INFORMATION_SCHEMA.TABLES.TABLE_NAME = INFORMATION_SCHEMA.COLUMNS.TABLE_NAME LIMIT 1) LIKE 'BASE TABLE' AND DATA_TYPE IN ('char','varchar') /* include other types if necessary */
$(".list-toggle").click(function() {
$(this).attr('colspan') ?
$(this).removeAttr('colspan') : $(this).attr('colspan', 6);
});
If you're using bootstrap 3 date time picker, try this:
$('.selector').datetimepicker({ maxDate: $.now() });
Using Xcode 7.3, I spent way too much time trying to figure this out -- none of the answers here or elsewhere did the trick -- and ultimately stumbled into a ridiculously easy solution.
Hope this helps someone.
This answer concerns developers for Windows. You want to pick an XML parsing module that does NOT depend on node-expat. Node-expat requires node-gyp and node-gyp requires you to install Visual Studio on your machine. If your machine is a Windows Server, you definitely don't want to install Visual Studio on it.
So, which XML parsing module to pick?
Save yourself a lot of trouble and use either xml2js or xmldoc. They depend on sax.js which is a pure Javascript solution that doesn't require node-gyp.
Both libxmljs and xml-stream require node-gyp. Don't pick these unless you already have Visual Studio on your machine installed or you don't mind going down that road.
Update 2015-10-24: it seems somebody found a solution to use node-gyp on Windows without installing VS: https://github.com/nodejs/node-gyp/issues/629#issuecomment-138276692
I had a similar problem when deploying one of my portlets. The portlet has been developed for Liferay 6.2 on Windows. My runtime environment is Tomcat 7 running on JRE 1.6 (JRockit 1.6). I have recently migrated to Eclipse 2019-3. I checked my Java Build Path (Project->Properties, Libraries tab). I noticed that the Apache Tomcat that is specified in the list of JARs and class folders on the build path was unbound. I selected that item. I clicked on the Edit button. Server Libary dialog was opened. I selected the correct Apache Tomcat. After applying the change, I redeployed the portlet and the problem was resolved.
Sometimes you may need to delete the problematic portlet from the [Tomcat]/webapps
directory before deploying the corrected portlet. Also, sometimes I have experienced that deployment of a portlet takes more than usual, and redeploying it resolves the issue.
To change the integrated terminal on Windows, you just need to change the terminal.integrated.shell.windows
line:
"terminal.integrated.shell.windows": "C:\\Bin\\Cmder\\Cmder.exe"
setting to the User Settings document on the right if it's not already there. This is so you aren't editing the Default Setting directly, but instead adding to it.You can then access it with keys Ctrl+backtick by default.
While your problem might be network-based, I've personally sped up my local git status
calls tenfold (7+ seconds down to 700 ms) by doing two modifications. This is on a 700 MB repository with 21,000 files and excessive numbers of large binary files.
One is enabling parallel index preloads. From a command prompt:
git config core.preloadindex true
This changed time git status
from 7 seconds to 2.5 seconds.
Update!
The following is no longer necessary. A patch has fixed this as of mysysgit 1.9.4
https://github.com/msysgit/git/commit/64d63240762df22e92b287b145d75a0d68a66988
However, you must enable the fix by typing
git config core.fscache true
I also disabled the UAC and the "luafv" driver (reboot required). This disables a driver in Windows Vista, 7 and 8 that redirects programs trying to write to system locations and instead redirects those accesses to a user directory.
To see a discussion on how this affects Git performance, read here: https://code.google.com/p/msysgit/issues/detail?id=320
To disable this driver, in regedit, change the "start" key at HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/luafv
to 4 to disable the driver. Then, put UAC to its lowest setting, "never notify".
If the disabling of this driver makes you wary (it should), an alternative is running on a drive (or partition) different than your system partition. Apparently the driver only runs on file access on the system partition. I have a second hard drive and see identical results when run with this registry modification on my C drive as I do without it on the D drive.
This change takes time git status
from 2.5 seconds down to 0.7 seconds.
You also might want to follow https://github.com/msysgit/git/pull/94 and https://github.com/git/git/commit/d637d1b9a8fb765a8542e69bd2e04b3e229f663b to check out what additional work is underway for speed issues in Windows.
If you are using a UNIX system, you could do
git log|grep "Author"|wc -l
interesting, datepicker default date is current date as I found,
but you can set date by
$("#yourinput").datepicker( "setDate" , "7/11/2011" );
don't forget to check you system date :)
Then NumPy sum
function takes an optional axis argument that specifies along which axis you would like the sum performed:
>>> a = numpy.arange(12).reshape(4,3)
>>> a.sum(0)
array([18, 22, 26])
Or, equivalently:
>>> numpy.sum(a, 0)
array([18, 22, 26])
PHP VERSION >= 5.3.0
function test($test_param, $my_function) {
return $my_function($test_param);
}
test("param", function($param) {
echo $param;
}); //will echo "param"
$obj = new stdClass();
$obj->test = function ($test_param, $my_function) {
return $my_function($test_param);
};
$test = $obj->test;
$test("param", function($param) {
echo $param;
});
class obj{
public function test($test_param, $my_function) {
return $my_function($test_param);
}
}
$obj = new obj();
$obj->test("param", function($param) {
echo $param;
});
class obj {
public static function test($test_param, $my_function) {
return $my_function($test_param);
}
}
obj::test("param", function($param) {
echo $param;
});
In case that you want to display in your <div>
some kind of popUp message on screen center - then you don't need to read size of <div>
but you can use flex
.box {
width: 50px;
height: 20px;
background: red;
}
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
width: 100vw;
position: fixed; /* remove this in case there is no content under div (and remember to set body margins to 0)*/
}
_x000D_
<div class="container">
<div class="box">My div</div>
</div>
_x000D_
To create a "drop down menu" you can use OptionMenu
in tkinter
Example of a basic OptionMenu
:
from Tkinter import *
master = Tk()
variable = StringVar(master)
variable.set("one") # default value
w = OptionMenu(master, variable, "one", "two", "three")
w.pack()
mainloop()
More information (including the script above) can be found here.
Creating an OptionMenu
of the months from a list would be as simple as:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
mainloop()
In order to retrieve the value the user has selected you can simply use a .get()
on the variable that we assigned to the widget, in the below case this is variable
:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
def ok():
print ("value is:" + variable.get())
button = Button(master, text="OK", command=ok)
button.pack()
mainloop()
I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.
What you are doing is correct, the problem is somewhere else, e.g. the cookie is being set again somehow on refresh.
You can use this syntax if some grads are attached with your variables.
y=torch.Tensor.cpu(x).detach().numpy()[:,:,:,-1]
The Linux Kernel does not automatically change the IO Scheduler at run-time. By this I mean, the Linux kernel, as of today, is not able to automatically choose an "optimal" scheduler depending on the type of secondary storage devise. During start-up, or during run-time, it is possible to change the IO scheduler manually.
The default scheduler is chosen at start-up based on the contents in the file located at /linux-2.6 /block/Kconfig.iosched. However, it is possible to change the IO scheduler during run-time by echo
ing a valid scheduler name into the file located at /sys/block/[DEV]/queue/scheduler. For example, echo deadline > /sys/block/hda/queue/scheduler
Use the INTERVAL
type to it. E.g:
--yesterday
SELECT NOW() - INTERVAL '1 DAY';
--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;
Then you can do the following on your query:
SELECT
org_id,
count(accounts) AS COUNT,
((date_at) - INTERVAL '1 DAY') AS dateat
FROM
sourcetable
WHERE
date_at <= now() - INTERVAL '130 DAYS'
GROUP BY
org_id,
dateat;
You can append multiple operands. E.g.: how to get last day of current month?
SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';
You can also create an interval using make_interval
function, useful when you need to create it at runtime (not using literals):
SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);
Try the following:
javac file1.java file2.java
I wrote this method for me. I use some part of Bruno Ratnieks's code. Maybe it is useful to someone.
public static string getQueryFromCommand(SqlCommand cmd)
{
StringBuilder CommandTxt = new StringBuilder();
CommandTxt.Append("DECLARE ");
List<string> paramlst = new List<string>();
foreach (SqlParameter parms in cmd.Parameters)
{
paramlst.Add(parms.ParameterName);
CommandTxt.Append(parms.ParameterName + " AS ");
CommandTxt.Append(parms.SqlDbType.ToString());
CommandTxt.Append(",");
}
if (CommandTxt.ToString().Substring(CommandTxt.Length-1, 1) == ",")
CommandTxt.Remove(CommandTxt.Length-1, 1);
CommandTxt.AppendLine();
int rownr = 0;
foreach (SqlParameter parms in cmd.Parameters)
{
string val = String.Empty;
if (parms.DbType.Equals(DbType.String) || parms.DbType.Equals(DbType.DateTime))
val = "'" + Convert.ToString(parms.Value).Replace(@"\", @"\\").Replace("'", @"\'") + "'";
if (parms.DbType.Equals(DbType.Int16) || parms.DbType.Equals(DbType.Int32) || parms.DbType.Equals(DbType.Int64) || parms.DbType.Equals(DbType.Decimal) || parms.DbType.Equals(DbType.Double))
val = Convert.ToString(parms.Value);
CommandTxt.AppendLine();
CommandTxt.Append("SET " + paramlst[rownr].ToString() + " = " + val.ToString());
rownr += 1;
}
CommandTxt.AppendLine();
CommandTxt.AppendLine();
CommandTxt.Append(cmd.CommandText);
return CommandTxt.ToString();
}
using jQuery it's easy...
$('YOUR CLASS SELECTOR').click(function(){
$(this).toggle();
});
url=$(echo "$1" | sed -e 's/%/%25/g' -e 's/ /%20/g' -e 's/!/%21/g' -e 's/"/%22/g' -e 's/#/%23/g' -e 's/\$/%24/g' -e 's/\&/%26/g' -e 's/'\''/%27/g' -e 's/(/%28/g' -e 's/)/%29/g' -e 's/\*/%2a/g' -e 's/+/%2b/g' -e 's/,/%2c/g' -e 's/-/%2d/g' -e 's/\./%2e/g' -e 's/\//%2f/g' -e 's/:/%3a/g' -e 's/;/%3b/g' -e 's//%3e/g' -e 's/?/%3f/g' -e 's/@/%40/g' -e 's/\[/%5b/g' -e 's/\\/%5c/g' -e 's/\]/%5d/g' -e 's/\^/%5e/g' -e 's/_/%5f/g' -e 's/`/%60/g' -e 's/{/%7b/g' -e 's/|/%7c/g' -e 's/}/%7d/g' -e 's/~/%7e/g')
this will encode the string inside of $1 and output it in $url. although you don't have to put it in a var if you want. BTW didn't include the sed for tab thought it would turn it into spaces
In XML values in text() nodes.
If we write this
<numbers>1,2,3</numbers>
in element "numbers
" will be one text() node with value "1,2,3".
Native way to get many text() nodes in element is insert nodes of other types in text.
Other available types is element or comment() node.
Split with element node:
<numbers>3<_/>2<_/>1</numbers>
Split with comment() node:
<numbers>3<!---->2<!---->1</numbers>
We can select this values by this XPath
//numbers/text()
Select value by index
//numbers/text()[3]
Will return text() node with value "1"
I have tried this and it is working fine for me:
sqlcmd -S servername -E -s~ -W -k1 -Q "sql query here" > "\\file_path\file_name.csv"
If you version of xargs supports the -d flag then this should work
ls | xargs -d, -L 1 echo
-d is the delimiter flag
If you do not have -d, then you can try the following
ls | xargs -I {} echo {}, | xargs echo
The first xargs allows you to specify your delimiter which is a comma in this example.
Swift 4.1
Create a "Character Set" based on the option you want (urlQueryAllowed). Then remove the additional characters you do not want (+&). Then pass that character set to "addingPercentEncoding".
var address = "American Tourister, Abids Road, Bogulkunta, Hyderabad, Andhra Pradesh, India"
var queryCharSet = NSCharacterSet.urlQueryAllowed
queryCharSet.remove(charactersIn: "+&")
let escapedAddress = address.addingPercentEncoding(withAllowedCharacters: queryCharSet)!
let urlpath = String(format: "http://maps.googleapis.com/maps/api/geocode/json?address=\(escapedAddress)")
Update: I figured this out. On my ScrollView, I needed to override the onInterceptTouchEvent method to only intercept the touch event if the Y motion is > the X motion. It seems like the default behavior of a ScrollView is to intercept the touch event whenever there is ANY Y motion. So with the fix, the ScrollView will only intercept the event if the user is deliberately scrolling in the Y direction and in that case pass off the ACTION_CANCEL to the children.
Here is the code for my Scroll View class that contains the HorizontalScrollView:
public class CustomScrollView extends ScrollView {
private GestureDetector mGestureDetector;
public CustomScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
mGestureDetector = new GestureDetector(context, new YScrollDetector());
setFadingEdgeLength(0);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return super.onInterceptTouchEvent(ev) && mGestureDetector.onTouchEvent(ev);
}
// Return false if we're scrolling in the x direction
class YScrollDetector extends SimpleOnGestureListener {
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return Math.abs(distanceY) > Math.abs(distanceX);
}
}
}
Have you tried this?
git log --pretty=oneline --abbrev-commit
The problem is probably that you are missing an empty line after the first line. The command above usually works for me, but I just tested on a commit without empty second line. I got the same result as you: the whole message on one line.
Empty second line is a standard in git commit messages. The behaviour you see was probably implemented on purpose.
The first line of a commit message is meant to be a short description. If you cannot make it in a single line you can use several, but git considers everything before the first empty line to be the "short description". oneline
prints the whole short description, so all your 3 rows.
Because it's not actually a dictionary; it's another mapping type that looks like a dictionary. Use type()
to verify. Pass it to dict()
to get a real dictionary from it.
Another option:
UPDATE `table` SET the_col = current_timestamp
Looks odd, but works as expected. If I had to guess, I'd wager this is slightly faster than calling now()
.