In the interests of completeness there are a couple of other solutions which (in my opinion) are more orthodox than solutions relying on the SqlDependency (and SqlTableDependency) classes. SqlDependency was originally designed to make refreshing distributed webserver caches easier, and so was built to a different set of requirements than if it were designed as an event producer.
There are broadly four options, some of which have not been covered here already:
Change tracking
Change tracking is a lightweight notification mechanism in SQL server. Basically, a database-wide version number is incremented with every change to any data. The version number is then written to the change tracking tables with a bit mask including the names of the columns which were changed. Note, the actual change is not persisted. The notification only contains the information that a particular data entity has changed. Further, because the change table versioning is cumulative, change notifications on individual items are not preserved and are overwritten by newer notifications. This means that if an entity changes twice, change tracking will only know about the most recent change.
In order to capture these changes in c#, polling must be used. The change tracking tables can be polled and each change inspected to see if is of interest. If it is of interest, it is necessary to then go directly to the data to retrieve the current state.
Change Data Capture
Source: https://technet.microsoft.com/en-us/library/bb522489(v=sql.105).aspx
Change data capture (CDC) is more powerful but most costly than change tracking. Change data capture will track and notify changes based on monitoring the database log. Because of this CDC has access to the actual data which has been changed, and keeps a record of all individual changes.
Similarly to change tracking, in order to capture these changes in c#, polling must be used. However, in the case of CDC, the polled information will contain the change details, so it's not strictly necessary to go back to the data itself.
Triggers to queues
Source: https://code.msdn.microsoft.com/Service-Broker-Message-e81c4316
This technique depends on triggers on the tables from which notifications are required. Each change will fire a trigger, and the trigger will write this information to a service broker queue. The queue can then be connected to via C# using the Service Broker Message Processor (sample in the link above).
Unlike change tracking or CDC, triggers to queues do not rely on polling and thereby provides realtime eventing.
CLR
This is a technique I have seen used, but I would not recommend it. Any solution which relies on the CLR to communicate externally is a hack at best. The CLR was designed to make writing complex data processing code easier by leveraging C#. It was not designed to wire in external dependencies like messaging libraries. Furthermore, CLR bound operations can break in clustered environments in unpredictable ways.
This said, it is fairly straightforward to set up, as all you need to do is register the messaging assembly with CLR and then you can call away using triggers or SQL jobs.
In summary...
It has always been a source of amazement to me that Microsoft has steadfastly refused to address this problem space. Eventing from database to code should be a built-in feature of the database product. Considering that Oracle Advanced Queuing combined with the ODP.net MessageAvailable event provided reliable database eventing to C# more than 10 years ago, this is woeful from MS.
The upshot of this is that none of the solutions listed to this question are very nice. They all have technical drawbacks and have a significant setup cost. Microsoft if you're listening, please sort out this sorry state of affairs.
Here's my version that is able to escape '{', and clean up those unassigned place holders.
function getStringFormatPlaceHolderRegEx(placeHolderIndex) {
return new RegExp('({)?\\{' + placeHolderIndex + '\\}(?!})', 'gm')
}
function cleanStringFormatResult(txt) {
if (txt == null) return "";
return txt.replace(getStringFormatPlaceHolderRegEx("\\d+"), "");
}
String.prototype.format = function () {
var txt = this.toString();
for (var i = 0; i < arguments.length; i++) {
var exp = getStringFormatPlaceHolderRegEx(i);
txt = txt.replace(exp, (arguments[i] == null ? "" : arguments[i]));
}
return cleanStringFormatResult(txt);
}
String.format = function () {
var s = arguments[0];
if (s == null) return "";
for (var i = 0; i < arguments.length - 1; i++) {
var reg = getStringFormatPlaceHolderRegEx(i);
s = s.replace(reg, (arguments[i + 1] == null ? "" : arguments[i + 1]));
}
return cleanStringFormatResult(s);
}
It sounds like you can pick and choose. If you pick float, you may lose 11 digits of precision. If that's acceptable, go for it -- apparently the Linq designers thought this to be a good tradeoff.
However, if your application needs those extra digits, use decimal. Decimal (implemented correctly) is way more accurate than a float anyway -- no messy translation from base 10 to base 2 and back.
"Casting" is different than conversion. In this case, window.location.hash
will auto-convert a number to a string. But to avoid a TypeScript compile error, you can do the string conversion yourself:
window.location.hash = ""+page_number;
window.location.hash = String(page_number);
These conversions are ideal if you don't want an error to be thrown when page_number
is null
or undefined
. Whereas page_number.toString()
and page_number.toLocaleString()
will throw when page_number
is null
or undefined
.
When you only need to cast, not convert, this is how to cast to a string in TypeScript:
window.location.hash = <string>page_number;
// or
window.location.hash = page_number as string;
The <string>
or as string
cast annotations tell the TypeScript compiler to treat page_number
as a string at compile time; it doesn't convert at run time.
However, the compiler will complain that you can't assign a number to a string. You would have to first cast to <any>
, then to <string>
:
window.location.hash = <string><any>page_number;
// or
window.location.hash = page_number as any as string;
So it's easier to just convert, which handles the type at run time and compile time:
window.location.hash = String(page_number);
(Thanks to @RuslanPolutsygan for catching the string-number casting issue.)
As mentioned in this tutorial, it's as simple as:
To install
brew install gradle
To upgrade
brew upgrade gradle
(using Homebrew of course)
Also see (finally) updated docs.
Cheers :)!
I don't know exactly what you are doing, but float("inf")
gives you a float Infinity, which is greater than any other number.
You need to do encode
on tmp[0]
, not on tmp
.
tmp
is not a string. It contains a (Unicode) string.
Try running type(tmp)
and print dir(tmp)
to see it for yourself.
Use [label sizeToFit];
to adjust the text in UILabel
The type int
is a primitive and it cannot be null
, if you want to return null
, mark the signature as
public Integer pollDecrementHigherKey(int x) {
x = 10;
if (condition) {
return x; // This is auto-boxing, x will be automatically converted to Integer
} else if (condition2) {
return null; // Integer inherits from Object, so it's valid to return null
} else {
return new Integer(x); // Create an Integer from the int and then return
}
return 5; // Also will be autoboxed and converted into Integer
}
There are some syntax errors on your HTML
.
First, the URL of the image needs to point to an address on the public Internet. The users viewing your page won't have your hard drive, so pointing to a file on your local hard drive cannot work. Replace C:\Pics
with the actual URL of the image, not a path on development machine filesystem. If you want to be absolutely sure, use a different computer and paste the img tag src attribute value to the address bar of the browser. If it works there, then you're good. Do not that the path can be relative and still valid, but then it needs to be relative to the public URL of the web page it's embedded in.
Second, the <title>
tag. You need to add this tag if you need a title on the browser, and you can't format it.
The third error, if about the <th>
tag, you have to add this header inside a <tr>
tag, because <th>
needs a row (create by <tr>
).
Another thing is, you don't need all colspan you did.
I tried to do a valid html as you need. Take a look:
<!DOCTYPE html>
<html>
<head>
<title>CAR APPLICATION</title>
</head>
<body>
<center>
<h1>CAR APPLICATION</h1>
</center>
<table border="5" bordercolor="red" align="center">
<tr>
<th colspan="3">SONAKSHI RAINA 10B ROLL No:-32</th>
</tr>
<tr>
<th>Name</th>
<th>Origin</th>
<th>Photo</th>
</tr>
<tr>
<td>Bugatti Veyron Super Sport</td>
<td>Molsheim, Alsace, France</td>
<!-- considering it is on the same folder that .html file -->
<td><img src="H.gif" alt="" border=3 height=100 width=100></img></td>
</tr>
<tr>
<td>SSC Ultimate Aero TT TopSpeed</td>
<td>United States</td>
<td border=3 height=100 width=100>Photo1</td>
</tr>
<tr>
<td>Koenigsegg CCX</td>
<td>Ängelholm, Sweden</td>
<td border=4 height=100 width=300>Photo1</td>
</tr>
<tr>
<td>Saleen S7</td>
<td>Irvine, California, United States</td>
<td border=3 height=100 width=100>Photo1</td>
</tr>
<tr>
<td> McLaren F1</td>
<td>Surrey, England</td>
<td border=3 height=100 width=100>Photo1</td>
</tr>
<tr>
<td>Ferrari Enzo</td>
<td>Maranello, Italy</td>
<td border=3 height=100 width=100>Photo1</td>
</tr>
<tr>
<td> Pagani Zonda F Clubsport</td>
<td>Modena, Italy</td>
<td border=3 height=100 width=100>Photo1</td>
</tr>
</table>
</body>
<html>
If all you want is to see the date like so "YYYY-MM-DD" without all the other clutter e.g. "Thu May 21 12:08:18 EDT 2015" then just use java.sql.Date
. This example gets the current date:
new java.sql.Date(System.currentTimeMillis());
Also java.sql.Date
is a subclass of java.util.Date
.
You can now use the Decodable protocol to Decode a .plist into a custom struct. I will go over a basic example, for more complicated .plist structures I recommend reading up on Decodable/Encodable (a good resource is here: https://benscheirman.com/2017/06/swift-json/).
First setup your struct into the format of your .plist file. For this example I will consider a .plist with a root level Dictionary and 3 entries: 1 String with key "name", 1 Int with key "age", and 1 Boolean with key "single". Here is the struct:
struct Config: Decodable {
private enum CodingKeys: String, CodingKey {
case name, age, single
}
let name: String
let age: Int
let single: Bool
}
Simple enough. Now the cool part. Using the PropertyListDecoder class we can easily parse the .plist file into an instantiation of this struct:
func parseConfig() -> Config {
let url = Bundle.main.url(forResource: "Config", withExtension: "plist")!
let data = try! Data(contentsOf: url)
let decoder = PropertyListDecoder()
return try! decoder.decode(Config.self, from: data)
}
Not much more code to worry about, and its all in Swift. Better yet we now have an instantiation of the Config struct that we can easily use:
let config = parseConfig()
print(config.name)
print(config.age)
print(config.single)
This Prints the value for the "name", "age", and "single" keys in the .plist.
Yes it is, there have to be boolean expresion after IF. Here you have a direct link. I hope it helps. GL!
While it's a bit more verbose, you can accomplish what everyone else was recommending underscore/lodash for 2 years ago, by using Array.prototype.reduce.
var subset = ['color', 'height'].reduce(function(o, k) { o[k] = elmo[k]; return o; }, {});
This approach solves it from the other side: rather than take an object and pass property names to it to extract, take an array of property names and reduce them into a new object.
While it's more verbose in the simplest case, a callback here is pretty handy, since you can easily meet some common requirements, e.g. change the 'color' property to 'colour' on the new object, flatten arrays, etc. -- any of the things you need to do when receiving an object from one service/library and building a new object needed somewhere else. While underscore/lodash are excellent, well-implemented libs, this is my preferred approach for less vendor-reliance, and a simpler, more consistent approach when my subset-building logic gets more complex.
edit: es7 version of the same:
const subset = ['color', 'height'].reduce((a, e) => (a[e] = elmo[e], a), {});
edit: A nice example for currying, too! Have a 'pick' function return another function.
const pick = (...props) => o => props.reduce((a, e) => ({ ...a, [e]: o[e] }), {});
The above is pretty close to the other method, except it lets you build a 'picker' on the fly. e.g.
pick('color', 'height')(elmo);
What's especially neat about this approach, is you can easily pass in the chosen 'picks' into anything that takes a function, e.g. Array#map
:
[elmo, grover, bigBird].map(pick('color', 'height'));
// [
// { color: 'red', height: 'short' },
// { color: 'blue', height: 'medium' },
// { color: 'yellow', height: 'tall' },
// ]
I needed the rotateAroundWorldAxis
function but the above code doesn't work with the newest release (r52). It looks like getRotationFromMatrix()
was replaced by setEulerFromRotationMatrix()
function rotateAroundWorldAxis( object, axis, radians ) {
var rotationMatrix = new THREE.Matrix4();
rotationMatrix.makeRotationAxis( axis.normalize(), radians );
rotationMatrix.multiplySelf( object.matrix ); // pre-multiply
object.matrix = rotationMatrix;
object.rotation.setEulerFromRotationMatrix( object.matrix );
}
Just to improve Wael's answer and put it on a single line:
dt.Columns.Add("Better", typeof(Boolean)).SetOrdinal(0);
UPDATE: Note that this works when you don't need to do anything else with the DataColumn. Add() returns the column in question, SetOrdinal() returns nothing.
On Excel 2010 try this:
Because LINQ
can do everything...:
string test = "key1=value1&key2=value2&key3=value3";
var count = test.Where(x => x == '&').Count();
Or if you like, you can use the Count
overload that takes a predicate :
var count = test.Count(x => x == '&');
Your ngClick
is correct; you just need the right service. $location
is what you're looking for. Check out the docs for the full details, but the solution to your specific question is this:
$location.path( '/new-page.html' );
The $location
service will add the hash (#) if it's appropriate based on your current settings and ensure no page reload occurs.
You could also do something more flexible with a directive if you so chose:
.directive( 'goClick', function ( $location ) {
return function ( scope, element, attrs ) {
var path;
attrs.$observe( 'goClick', function (val) {
path = val;
});
element.bind( 'click', function () {
scope.$apply( function () {
$location.path( path );
});
});
};
});
And then you could use it on anything:
<button go-click="/go/to/this">Click!</button>
There are many ways to improve this directive; it's merely to show what could be done. Here's a Plunker demonstrating it in action: http://plnkr.co/edit/870E3psx7NhsvJ4mNcd2?p=preview.
If you use pandas, you can append your dataframes to an existing CSV file this way:
df.to_csv('log.csv', mode='a', index=False, header=False)
With mode='a' we ensure that we append, rather than overwrite, and with header=False we ensure that we append only the values of df rows, rather than header + values.
How about something like:
SELECT mt.*
FROM MyTable mt INNER JOIN
(
SELECT id, MIN(record_date) AS MinDate
FROM MyTable
GROUP BY id
) t ON mt.id = t.id AND mt.record_date = t.MinDate
This gets the minimum date per ID, and then gets the values based on those values. The only time you would have duplicates is if there are duplicate minimum record_dates for the same ID.
This approach also works with same hierarchy of Controller files:
$printReport = new PrintReportController;
$prinReport->getPrintReport();
You can disable FK and CHECK constraints only in SQL 2005+. See ALTER TABLE
ALTER TABLE foo NOCHECK CONSTRAINT ALL
or
ALTER TABLE foo NOCHECK CONSTRAINT CK_foo_column
Primary keys and unique constraints can not be disabled, but this should be OK if I've understood you correctly.
To execute SomeClass.main(String [] args) from a deployed war file do:
Step 1: Write class SomeClass.java that has a main method method i.e. (public static void main(String[] args) {...})
Step 2: Deploy your WAR
Step 3: cd /usr/local/yourprojectsname/tomcat/webapps/projectName/WEB-INF
Step 4: java -cp "lib/jar1.jar:lib/jar2.jar: ... :lib/jarn.jar" com.mypackage.SomeClass arg1 arg2 ... arg3
Note1: (to see if the class SomeOtherClass.class is in /usr/tomcat/webapps/projectName/WEB-INF/lib)
run --> cd /usr/tomcat/webapps/projectName/WEB-INF/lib && find . -name '*.jar' | while read jarfile; do if jar tf "$jarfile" | grep SomeOtherClass.class; then echo "$jarfile"; fi; done
Note2: Write to standard out so you can see if your main actually works via print statements to the console. This is called a back door.
Note3: The comment above by Bozhidar Bozhanov seems correct
My solution was the following:
document.getElementById("agent_details").scrollIntoView();
SQL Server requires subqueries that you SELECT FROM
or JOIN
to have an alias.
Add an alias to your subquery (in this case x
):
select COUNT(*) from
(
select m.Company_id
from Monitor as m
inner join Monitor_Request as mr on mr.Company_ID=m.Company_id
group by m.Company_id
having COUNT(m.Monitor_id)>=5) x
Also you can try to use
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
if you are dealing with jackson with version below 2+ (1.9.5) i tested it, you can easily use this annotation above the class. Not for specified for the attributes, just for class decleration.
In addition to kieran's answer, apparently, modern browsers have an Object.keys
function. In this case, you could do this:
Object.keys(jsonArray).length;
More details in this answer on How to list the properties of a javascript object
Based on the other answers to this question, I've implemented a new approach using bcrypt.
If I understand correctly, the argument to use bcrypt
over SHA512
is that bcrypt
is designed to be slow. bcrypt
also has an option to adjust how slow you want it to be when generating the hashed password for the first time:
# The '12' is the number that dictates the 'slowness'
bcrypt.hashpw(password, bcrypt.gensalt( 12 ))
Slow is desirable because if a malicious party gets their hands on the table containing hashed passwords, then it is much more difficult to brute force them.
def get_hashed_password(plain_text_password):
# Hash a password for the first time
# (Using bcrypt, the salt is saved into the hash itself)
return bcrypt.hashpw(plain_text_password, bcrypt.gensalt())
def check_password(plain_text_password, hashed_password):
# Check hashed password. Using bcrypt, the salt is saved into the hash itself
return bcrypt.checkpw(plain_text_password, hashed_password)
I was able to install the library pretty easily in a linux system using:
pip install py-bcrypt
However, I had more trouble installing it on my windows systems. It appears to need a patch. See this Stack Overflow question: py-bcrypt installing on win 7 64bit python
spin12.setLayoutParams(new LinearLayout.LayoutParams(200, 120));
spin12
is your spinner and 200,120 is width
and height
for your spinner
.
ORA-06512 is part of the error stack. It gives us the line number where the exception occurred, but not the cause of the exception. That is usually indicated in the rest of the stack (which you have still not posted).
In a comment you said
"still, the error comes when pNum is not between 12 and 14; when pNum is between 12 and 14 it does not fail"
Well, your code does this:
IF ((pNum < 12) OR (pNum > 14)) THEN
RAISE vSOME_EX;
That is, it raises an exception when pNum is not between 12 and 14. So does the rest of the error stack include this line?
ORA-06510: PL/SQL: unhandled user-defined exception
If so, all you need to do is add an exception block to handle the error. Perhaps:
PROCEDURE PX(pNum INT,pIdM INT,pCv VARCHAR2,pSup FLOAT)
AS
vSOME_EX EXCEPTION;
BEGIN
IF ((pNum < 12) OR (pNum > 14)) THEN
RAISE vSOME_EX;
ELSE
EXECUTE IMMEDIATE 'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('||pCv||', '||pSup||', '||pIdM||')';
END IF;
exception
when vsome_ex then
raise_application_error(-20000
, 'This is not a valid table: M'||pNum||'GR');
END PX;
The documentation covers handling PL/SQL exceptions in depth.
StringBuilder replace method can be used to replace the last character.
StringBuilder.replace(startPosition, endPosition, newString)
StringBuilder builder = new StringBuilder(fieldName);
builder.replace(builder.length()-1, builder.length(), "");
builder.toString();
Command:
netstat -aon | findstr 4723
Output:
TCP 0.0.0.0:4723 0.0.0.0:0 LISTENING 10396
Now cut the process ID, "10396", using the for
command in Windows.
Command:
for /f "tokens=5" %a in ('netstat -aon ^| findstr 4723') do @echo %~nxa
Output:
10396
If you want to cut the 4th number of the value means "LISTENING" then command in Windows.
Command:
for /f "tokens=4" %a in ('netstat -aon ^| findstr 4723') do @echo %~nxa
Output:
LISTENING
1.1 you can do this with this site: http://inloop.github.io/svg2android/ but it does not support all the features of SVG like some gradients.
1.2 you can convert via android studio but it might use some features that only supports API 24 and higher that cuase crashe your app in older devices.
and add vectorDrawables.useSupportLibrary = true
in gradle file and use like this:
<android.support.v7.widget.AppCompatImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:srcCompat="@drawable/ic_item1" />
add this code in application class:
public void onCreate() {
SVGLoader.load(this)
}
and use the SVG like this :
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_android_red"/>
It's just happen because of abnormal termination of mysql service. delete or take backup of /var/lib/mysql/mysql.sock file and restart mysql.
Please let me know if in case any issue..
The data series names are defined by the column headers. Add the names to the column headers that you would like to use as titles for each of your data series, select all of the data (including the headers), then re-generate your graph. The names in the headers should then appear as the names in the legend for each series.
An alternative to the answer from sergey_mo is to create multiple ssh keys on the jenkins server.
(Though as the first commenter to sergey_mo's answer said, this may end up being more painful than managing a single key-pair.)
Great answer above. Another way is to use the great yaml jq wrapper tool, yq at https://github.com/kislyuk/yq
Save your JSON example to a file, say ex.json and then
yq -y '.' ex.json
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
DickFeynman's answer is a workable solution for any circumstance in which JQuery is not a good fit, or isn't otherwise necessary. As ComFreek notes, this requires setting the CORS headers on the server-side. If it's your service, and you have a handle on the bigger question of security, then that's entirely feasible.
Here's a listing of a Flask service, setting the CORS headers, grabbing data from a database, responding with JSON, and working happily with DickFeynman's approach on the client-side:
#!/usr/bin/env python
from __future__ import unicode_literals
from flask import Flask, Response, jsonify, redirect, request, url_for
from your_model import *
import os
try:
import simplejson as json;
except ImportError:
import json
try:
from flask.ext.cors import *
except:
from flask_cors import *
app = Flask(__name__)
@app.before_request
def before_request():
try:
# Provided by an object in your_model
app.session = SessionManager.connect()
except:
print "Database connection failed."
@app.teardown_request
def shutdown_session(exception=None):
app.session.close()
# A route with a CORS header, to enable your javascript client to access
# JSON created from a database query.
@app.route('/whatever-data/', methods=['GET', 'OPTIONS'])
@cross_origin(headers=['Content-Type'])
def json_data():
whatever_list = []
results_json = None
try:
# Use SQL Alchemy to select all Whatevers, WHERE size > 0.
whatevers = app.session.query(Whatever).filter(Whatever.size > 0).all()
if whatevers and len(whatevers) > 0:
for whatever in whatevers:
# Each whatever is able to return a serialized version of itself.
# Refer to your_model.
whatever_list.append(whatever.serialize())
# Convert a list to JSON.
results_json = json.dumps(whatever_list)
except SQLAlchemyError as e:
print 'Error {0}'.format(e)
exit(0)
if len(whatevers) < 1 or not results_json:
exit(0)
else:
# Because we used json.dumps(), rather than jsonify(),
# we need to create a Flask Response object, here.
return Response(response=str(results_json), mimetype='application/json')
if __name__ == '__main__':
#@NOTE Not suitable for production. As configured,
# your Flask service is in debug mode and publicly accessible.
app.run(debug=True, host='0.0.0.0', port=5001) # http://localhost:5001/
your_model contains the serialization method for your whatever, as well as the database connection manager (which could stand a little refactoring, but suffices to centralize the creation of database sessions, in bigger systems or Model/View/Control architectures). This happens to use postgreSQL, but could just as easily use any server side data store:
#!/usr/bin/env python
# Filename: your_model.py
import time
import psycopg2
import psycopg2.pool
import psycopg2.extras
from psycopg2.extensions import adapt, register_adapter, AsIs
from sqlalchemy import update
from sqlalchemy.orm import *
from sqlalchemy.exc import *
from sqlalchemy.dialects import postgresql
from sqlalchemy import Table, Column, Integer, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
class SessionManager(object):
@staticmethod
def connect():
engine = create_engine('postgresql://id:passwd@localhost/mydatabase',
echo = True)
Session = sessionmaker(bind = engine,
autoflush = True,
expire_on_commit = False,
autocommit = False)
session = Session()
return session
@staticmethod
def declareBase():
engine = create_engine('postgresql://id:passwd@localhost/mydatabase', echo=True)
whatever_metadata = MetaData(engine, schema ='public')
Base = declarative_base(metadata=whatever_metadata)
return Base
Base = SessionManager.declareBase()
class Whatever(Base):
"""Create, supply information about, and manage the state of one or more whatever.
"""
__tablename__ = 'whatever'
id = Column(Integer, primary_key=True)
whatever_digest = Column(VARCHAR, unique=True)
best_name = Column(VARCHAR, nullable = True)
whatever_timestamp = Column(BigInteger, default = time.time())
whatever_raw = Column(Numeric(precision = 1000, scale = 0), default = 0.0)
whatever_label = Column(postgresql.VARCHAR, nullable = True)
size = Column(BigInteger, default = 0)
def __init__(self,
whatever_digest = '',
best_name = '',
whatever_timestamp = 0,
whatever_raw = 0,
whatever_label = '',
size = 0):
self.whatever_digest = whatever_digest
self.best_name = best_name
self.whatever_timestamp = whatever_timestamp
self.whatever_raw = whatever_raw
self.whatever_label = whatever_label
# Serialize one way or another, just handle appropriately in the client.
def serialize(self):
return {
'best_name' :self.best_name,
'whatever_label':self.whatever_label,
'size' :self.size,
}
In retrospect, I might have serialized the whatever objects as lists, rather than a Python dict, which might have simplified their processing in the Flask service, and I might have separated concerns better in the Flask implementation (The database call probably shouldn't be built-in the the route handler), but you can improve on this, once you have a working solution in your own development environment.
Also, I'm not suggesting people avoid JQuery. But, if JQuery's not in the picture, for one reason or another, this approach seems like a reasonable alternative.
It works, in any case.
Here's my implementation of DickFeynman's approach, in the the client:
<script type="text/javascript">
var addr = "dev.yourserver.yourorg.tld"
var port = "5001"
function Get(whateverUrl){
var Httpreq = new XMLHttpRequest(); // a new request
Httpreq.open("GET",whateverUrl,false);
Httpreq.send(null);
return Httpreq.responseText;
}
var whatever_list_obj = JSON.parse(Get("http://" + addr + ":" + port + "/whatever-data/"));
whatever_qty = whatever_list_obj.length;
for (var i = 0; i < whatever_qty; i++) {
console.log(whatever_list_obj[i].best_name);
}
</script>
I'm not going to list my console output, but I'm looking at a long list of whatever.best_name strings.
More to the point: The whatever_list_obj is available for use in my javascript namespace, for whatever I care to do with it, ...which might include generating graphics with D3.js, mapping with OpenLayers or CesiumJS, or calculating some intermediate values which have no particular need to live in my DOM.
Try this query.. It uses the Analytic function SUM:
SELECT * FROM
(
SELECT SUM(1) OVER(PARTITION BY ctn_no) cnt, A.*
FROM table1 a
WHERE s_ind ='Y'
)
WHERE cnt > 2
Am not sure why you are identifying a record as a duplicate if the ctn_no repeats more than 2 times. FOr me it repeats more than once it is a duplicate. In this case change the las part of the query to WHERE cnt > 1
You can view these with Process Explorer from sysinternals. Use the "Find -> Find Handle or DLL..." option and enter the pattern "\Device\NamedPipe\". It will show you which processes have which pipes open.
I also faced similar issue.
My source path had one directory with 'space' (D:/source 2012). I resolved this by removing the space (D:/source2012).
I was also facing the same issue where I was receiving the Transaction_Date as YYYYMMDD in bigint format. So I converted it into Datetime format using below query and saved it in new column with datetime format. I hope this will help you as well.
SELECT
convert( Datetime, STUFF(STUFF(Transaction_Date, 5, 0, '-'), 8, 0, '-'), 120) As [Transaction_Date_New]
FROM mydb
I tried re-creating this, and .someclass.notip
was being generated for me but .someclass:not(.notip)
was not, for as long as I did not have the @mixin tip()
defined. Once I had that, it all worked.
http://sassmeister.com/gist/9775949
$dropdown-width: 100px;
$comp-tip: true;
@mixin tip($pos:right) {
}
@mixin dropdown-pos($pos:right) {
&:not(.notip) {
@if $comp-tip == true{
@if $pos == right {
top:$dropdown-width * -0.6;
background-color: #f00;
@include tip($pos:$pos);
}
}
}
&.notip {
@if $pos == right {
top: 0;
left:$dropdown-width * 0.8;
background-color: #00f;
}
}
}
.someclass { @include dropdown-pos(); }
EDIT: http://sassmeister.com/ is a good place to debug your SASS because it gives you error messages. Undefined mixin 'tip'.
it what I get when I remove @mixin tip($pos:right) { }
I tried the example that you have provided and the only difference is that you have True and False values switched as @bdparrish
had pointed out. Here is a working example of making an SSRS Texbox visible or hidden based on the number of rows present in a dataset. This example uses SSRS 2008 R2
.
Step-by-step process: SSRS 2008 R2
In this example, the report has a dataset named Items
and has textbox to show row counts. It also has another textbox which will be visible only if the dataset Items has rows.
Right-click on the textbox that should be visible/hidden based on an expression and select Text Box Properties...
. Refer screenshot #1.
On the Text Box Properties
dialog, click on Visibility
from the left section. Refer screenshot #2.
Select Show or hide based on an epxression
.
Click on the expression button fx
.
Enter the expression =IIf(CountRows("Items") = 0 , True, False)
. Note that this expression is to hide the Textbox (Hidden).
Click OK twice to close the dialogs.
Screenshot #3 shows data in the SQL Server table dbo.Items
, which is the source for the report data set Items
. The table contains 3 rows. Screenshot #4 shows the sample report execution against the data.
Screenshot #5 shows data in the SQL Server table dbo.Items
, which is the source for the report data set Items
. The table contains no data. Screenshot #6 shows the sample report execution against the data.
Hope that helps.
Screenshot #1:
Screenshot #2:
Screenshot #3:
Screenshot #4:
Screenshot #5:
Screenshot #6:
Using &
is fine for short commands, but that single line can get very long very quick. When that happens, switch to multi-line syntax.
FOR /r %%X IN (*.txt) DO (
ECHO %%X
DEL %%X
)
Placement of (
and )
matters. The round brackets after DO
must be placed on the same line, otherwise the batch file will be incorrect.
See if /?|find /V ""
for details.
You can use the "Except" extension method (see http://msdn.microsoft.com/en-us/library/bb337804.aspx)
In your code
var difference = people.Except(exclusions);
If you use command line interface for inserting sql file to database.
Be sure your table charset utf8mb4
and column collation utf8mb4_unicode_ci
or utf8mb4_bin
mysql -u root -p123456 my_database < profiles.sql
ERROR 1366 (HY000) at line 1679: Incorrect string value: '\xF0\x9F\x98\x87\xF0\x9F...' for column 'note' at row 328
we can solve the problem with this parameter
--default-character-set=name
(Set the default character set)
mysql -u root -p123456 --default-character-set=utf8mb4 my_database < profiles.sql
First of all do not use list
as a variable name- that is a builtin function.
I'm not super clear of what you're asking (a little more context would help), but maybe this is helpful-
my_list = []
my_list.append(np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1))
my_list.append(np.genfromtxt('temp2.txt', usecols=3, dtype=[('floatname','float')], skip_header=1))
That will create a list (a type of mutable array in python) called my_list
with the output of the np.getfromtext()
method in the first 2 indexes.
The first can be referenced with my_list[0]
and the second with my_list[1]
I had a similar solution like @maximilianus. The difference was that my .repositories files were called _remote.repositores and I had to delete them to make it work.
For eg in my case I deleted
After doing so my errors disappeared.
JFrame
is the window; it can have one or more JPanel
instances inside it. JPanel
is not the window.
You need a Swing tutorial:
In a truly optimized implementation, the method for choosing pivot should depend on the array size - for a large array, it pays off to spend more time choosing a good pivot. Without doing a full analysis, I would guess "middle of O(log(n)) elements" is a good start, and this has the added bonus of not requiring any extra memory: Using tail-call on the larger partition and in-place partitioning, we use the same O(log(n)) extra memory at almost every stage of the algorithm.
Yes, require is a Node.JS function and doesn't work in client side scripting without certain requirements. If you're getting this error while writing electronJS code, try the following:
In your BrowserWindow declaration, add the following webPreferences field:
i.e, instead of plain mainWindow = new BrowserWindow()
, write
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true
}
});
The output looks correct to me:
Invalid JavaScript code: sun.org.mozilla.javascript.internal.EvaluatorException: missing } after property list (<Unknown source>) in <Unknown source>; at line number 1
I think Invalid Javascript code: ..
is the start of the exception message.
Normally the stacktrace isn't returned with the message:
try {
throw new RuntimeException("hu?\ntrace-line1\ntrace-line2");
} catch (Exception e) {
System.out.println(e.getMessage()); // prints "hu?"
}
So maybe the code you are calling catches an exception and rethrows a ScriptException
. In this case maybe e.getCause().getMessage()
can help you.
If you're not interested in the details that git diff
outputs you can just run git cherry
which will output a list of commits your remote tracking branch has ahead of your local branch.
For example:
git fetch origin
git cherry master origin/master
Will output something like :
+ 2642039b1a4c4d4345a0d02f79ccc3690e19d9b1
+ a4870f9fbde61d2d657e97b72b61f46d1fd265a9
Indicates that there are two commits in my remote tracking branch that haven't been merged into my local branch.
This also works the other way :
git cherry origin/master master
Will show you a list of local commits that you haven't pushed to your remote repository yet.
try
{
..
..
..
}
catch(Exception ex)
{
..
..
..
}
the Exception ex means all the exceptions.
Try this expression:
typeof(variable) != "undefined" && variable !== null
This will be true if the variable is defined and not null, which is the equivalent of how PHP's isset works.
You can use it like this:
if(typeof(variable) != "undefined" && variable !== null) {
bla();
}
You need only to write:
GRANT DBA TO NewDBA;
Because this already makes the user a DB Administrator
brew cask commands were disabled on 2020-12-21 with the release of Homebrew 2.7.0.
Use the below commands to install JDK
brew install --cask adoptopenjdk/openjdk/adoptopenjdk8
Here is the code that worked for me!
Assuming that you have a valid session going,
//Get the current users id
$uid = $facebook->getUser();
//create the url
$profile_pic = "http://graph.facebook.com/".$uid."/picture";
//echo the image out
echo "<img src=\"" . $profile_pic . "\" />";
Thanx goes to Raine, you da man!
margin: 0 auto
then the element should be centered, but the width is left as-is--whatever it is calculated to be, disregarding any margin settings.<INPUT>
tag to display:block
, then it should be centered with margin: 0 auto
. See Visual formatting model details - calculating widths and margins from the CSS 2.1 specs for more details. Relavent bits include:
In a block formatting context, each box's left outer edge touches the left edge of the containing block.
and
When the total width of the inline boxes on a line is less than the width of the line box containing them, their horizontal distribution within the line box is determined by the 'text-align' property.
finally
If 'width' is set to 'auto', any other 'auto' values become '0' and 'width' follows from the resulting equality.
If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element with respect to the edges of the containing block.
Just ran into this problem myself. OSx Lion hides scrollbars while not in use to make it seem more "slick", but at the same time the issue you addressed comes up: people sometimes cannot see whether a div has a scroll feature or not.
The fix: In your css include -
::-webkit-scrollbar {
-webkit-appearance: none;
width: 7px;
}
::-webkit-scrollbar-thumb {
border-radius: 4px;
background-color: rgba(0, 0, 0, .5);
box-shadow: 0 0 1px rgba(255, 255, 255, .5);
}
/* always show scrollbars */_x000D_
_x000D_
::-webkit-scrollbar {_x000D_
-webkit-appearance: none;_x000D_
width: 7px;_x000D_
}_x000D_
_x000D_
::-webkit-scrollbar-thumb {_x000D_
border-radius: 4px;_x000D_
background-color: rgba(0, 0, 0, .5);_x000D_
box-shadow: 0 0 1px rgba(255, 255, 255, .5);_x000D_
}_x000D_
_x000D_
_x000D_
/* css for demo */_x000D_
_x000D_
#container {_x000D_
height: 4em;_x000D_
/* shorter than the child */_x000D_
overflow-y: scroll;_x000D_
/* clip height to 4em and scroll to show the rest */_x000D_
}_x000D_
_x000D_
#child {_x000D_
height: 12em;_x000D_
/* taller than the parent to force scrolling */_x000D_
}_x000D_
_x000D_
_x000D_
/* === ignore stuff below, it's just to help with the visual. === */_x000D_
_x000D_
#container {_x000D_
background-color: #ffc;_x000D_
}_x000D_
_x000D_
#child {_x000D_
margin: 30px;_x000D_
background-color: #eee;_x000D_
text-align: center;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="child">Example</div>_x000D_
</div>
_x000D_
customize the apperance as needed. Source
AlarmManager
in combination with IntentService
I think the best pattern for using AlarmManager
is its collaboration with an IntentService
. The IntentService
is triggered by the AlarmManager
and it handles the required actions through the receiving intent. This structure has not performance impact like using BroadcastReceiver
. I have developed a sample code for this idea in kotlin which is available here:
MyAlarmManager.kt
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
object MyAlarmManager {
private var pendingIntent: PendingIntent? = null
fun setAlarm(context: Context, alarmTime: Long, message: String) {
val alarmManager: AlarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context, MyIntentService::class.java)
intent.action = MyIntentService.ACTION_SEND_TEST_MESSAGE
intent.putExtra(MyIntentService.EXTRA_MESSAGE, message)
pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent)
}
fun cancelAlarm(context: Context) {
pendingIntent?.let {
val alarmManager: AlarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.cancel(it)
}
}
}
MyIntentService.kt
import android.app.IntentService
import android.content.Intent
class MyIntentService : IntentService("MyIntentService") {
override fun onHandleIntent(intent: Intent?) {
intent?.apply {
when (intent.action) {
ACTION_SEND_TEST_MESSAGE -> {
val message = getStringExtra(EXTRA_MESSAGE)
println(message)
}
}
}
}
companion object {
const val ACTION_SEND_TEST_MESSAGE = "ACTION_SEND_TEST_MESSAGE"
const val EXTRA_MESSAGE = "EXTRA_MESSAGE"
}
}
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.aminography.alarm">
<application
... >
<service
android:name="path.to.MyIntentService"
android:enabled="true"
android:stopWithTask="false" />
</application>
</manifest>
Usage:
val calendar = Calendar.getInstance()
calendar.add(Calendar.SECOND, 10)
MyAlarmManager.setAlarm(applicationContext, calendar.timeInMillis, "Test Message!")
If you want to to cancel the scheduled alarm, try this:
MyAlarmManager.cancelAlarm(applicationContext)
No, it's not the script, it's the fact that your script is not executed by Python at all. If your script is stored in a file named script.py
, you have to execute it as python script.py
, otherwise the default shell will execute it and it will bail out at the from
keyword. (Incidentally, from
is the name of a command line utility which prints names of those who have sent mail to the given username, so that's why it tries to access the mailboxes).
Another possibility is to add the following line to the top of the script:
#!/usr/bin/env python
This will instruct your shell to execute the script via python
instead of trying to interpret it on its own.
Why don't try to use bootstrap's solutions. They are perfect if you don't want to meddle with tables and floats.
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/> <!--- This line is just linking the bootstrap thingie in the file. The real thing starts below -->_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col-sm-4">_x000D_
One of three columns_x000D_
</div>_x000D_
<div class="col-sm-4">_x000D_
One of three columns_x000D_
</div>_x000D_
<div class="col-sm-4">_x000D_
One of three columns_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
No meddling with complex CSS, and the best thing is that you can edit the width of the columns by changing the number. You can find more examples at https://getbootstrap.com/docs/4.0/layout/grid/
For those who use ASP.NET Identity 2.1 and have changed the primary key from the default string
to either int
or Guid
, if you're still getting
EntityType 'xxxxUserLogin' has no key defined. Define the key for this EntityType.
EntityType 'xxxxUserRole' has no key defined. Define the key for this EntityType.
you probably just forgot to specify the new key type on IdentityDbContext
:
public class AppIdentityDbContext : IdentityDbContext<
AppUser, AppRole, int, AppUserLogin, AppUserRole, AppUserClaim>
{
public AppIdentityDbContext()
: base("MY_CONNECTION_STRING")
{
}
......
}
If you just have
public class AppIdentityDbContext : IdentityDbContext
{
......
}
or even
public class AppIdentityDbContext : IdentityDbContext<AppUser>
{
......
}
you will get that 'no key defined' error when you are trying to add migrations or update the database.
Because I always struggle to remember, a quick summary of what each of these do:
>>> pd.Timestamp.now() # naive local time
Timestamp('2019-10-07 10:30:19.428748')
>>> pd.Timestamp.utcnow() # tz aware UTC
Timestamp('2019-10-07 08:30:19.428748+0000', tz='UTC')
>>> pd.Timestamp.now(tz='Europe/Brussels') # tz aware local time
Timestamp('2019-10-07 10:30:19.428748+0200', tz='Europe/Brussels')
>>> pd.Timestamp.now(tz='Europe/Brussels').tz_localize(None) # naive local time
Timestamp('2019-10-07 10:30:19.428748')
>>> pd.Timestamp.now(tz='Europe/Brussels').tz_convert(None) # naive UTC
Timestamp('2019-10-07 08:30:19.428748')
>>> pd.Timestamp.utcnow().tz_localize(None) # naive UTC
Timestamp('2019-10-07 08:30:19.428748')
>>> pd.Timestamp.utcnow().tz_convert(None) # naive UTC
Timestamp('2019-10-07 08:30:19.428748')
You can wrap the text with a non-existing processing-instruction, e.g.:
<detail>
<?ignore
<band height="20">
<staticText>
<reportElement x="180" y="0" width="200" height="20"/>
<text><![CDATA[Hello World!]]></text>
</staticText>
</band>
?>
</detail>
Nested processing instructions are not allowed and '?>' ends the processing instruction (see http://www.w3.org/TR/REC-xml/#sec-pi)
I would use a hashtable with in key takes the element of the array (here string) and in value an Integer.
then go through the list doing something like this :
for(String s:array){
if(hash.containsKey(s)){
Integer i = hash.get(s);
i++;
}else{
hash.put(s, new Interger(1));
}
You can use Object.prototype.toString
to easily check if an object is an Error
, which will work for different frames as well.
function isError(obj){
return Object.prototype.toString.call(obj) === "[object Error]";
}
function isError(obj){
return Object.prototype.toString.call(obj) === "[object Error]";
}
console.log("Error:", isError(new Error));
console.log("RangeError:", isError(new RangeError));
console.log("SyntaxError:", isError(new SyntaxError));
console.log("Object:", isError({}));
console.log("Array:", isError([]));
_x000D_
This behavior is guaranteed by the ECMAScript Language Specification.
When the toString method is called, the following steps are taken:
- If the this value is undefined, return "[object Undefined]".
- If the this value is null, return "[object Null]".
- Let O be the result of calling ToObject passing the this value as the argument.
- Let class be the value of the [[Class]] internal property of O.
- Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".
Properties of Error Instances:
Error instances inherit properties from the Error prototype object and their
[[Class]]
internal property value is "Error". Error instances have no special properties.
if (!(/^[-+]?\d*\.?\d*$/.test(document.getElementById('txtRemittanceNumber').value))){
alert('Please enter only numbers into amount textbox.')
}
else
{
alert('Right Number');
}
I hope this code may help you.
in this code if condition will return true if there is any legal decimal number of any number of decimal places. and alert will come up with the message "Right Number" other wise it will show a alert popup with message "Please enter only numbers into amount textbox.".
Thanks... :)
Above wait statement is a nice example of Explicit wait.
As Explicit waits are intelligent waits that are confined to a particular web element(as mentioned in above x-path).
By Using explicit waits you are basically telling WebDriver at the max it is to wait for X units(whatever you have given as timeoutInSeconds) of time before it gives up.
git branch --set-upstream-to=origin/master<branch_name>
For me on windows it was Ctrl+¡
, indent line. It adds a tab at the beggining of each line.
Here it is, You have to follow write a few methods here. #Swift 5
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as? UITableViewHeaderFooterView
header?.textLabel?.font = UIFont.init(name: "Montserrat-Regular", size: 14)
header?.textLabel?.textColor = .greyishBrown
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 26
}
Have a good luck
You can do something like this:
function getSorted(itemsArray , sortingArr ) {
var result = [];
for(var i=0; i<arr.length; i++) {
result[i] = arr[sortArr[i]];
}
return result;
}
Note: this assumes the arrays you pass in are equivalent in size, you'd need to add some additional checks if this may not be the case.
refer link
See ?boxplot
for all the help you need.
outline: if ‘outline’ is not true, the outliers are not drawn (as
points whereas S+ uses lines).
boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)
And for extending the range of the whiskers and suppressing the outliers inside this range:
range: this determines how far the plot whiskers extend out from the
box. If ‘range’ is positive, the whiskers extend to the most
extreme data point which is no more than ‘range’ times the
interquartile range from the box. A value of zero causes the
whiskers to extend to the data extremes.
# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)
You can try this website http://www.decompileandroid.com Just upload the .apk file and rest of it will be done by this site.
If you are using Maven, add the below config in your pom.xml:
<build>
<testResources>
<testResource>
<directory>src/main/webapp</directory>
</testResource>
</testResources>
</build>
With this config, you will be able to access xml files in WEB-INF folder. From Maven POM Reference: The testResources element block contains testResource elements. Their definitions are similar to resource elements, but are naturally used during test phases.
// you need to have a list of data that you want the spinner to display
List<String> spinnerArray = new ArrayList<String>();
spinnerArray.add("item1");
spinnerArray.add("item2");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, spinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner sItems = (Spinner) findViewById(R.id.spinner1);
sItems.setAdapter(adapter);
also to find out what is selected you could do something like this
String selected = sItems.getSelectedItem().toString();
if (selected.equals("what ever the option was")) {
}
[1] First Design your tableview cell in StoryBoard.
[2] Put below table view delegate method
//MARK: - Tableview Delegate Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return <“Your Array”>
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
var totalHeight : CGFloat = <cell name>.<label name>.frame.origin.y
totalHeight += UpdateRowHeight(<cell name>.<label name>, textToAdd: <your array>[indexPath.row])
return totalHeight
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell : <cell name>! = tableView.dequeueReusableCellWithIdentifier(“<cell identifire>”, forIndexPath: indexPath) as! CCell_VideoCall
if(cell == nil)
{
cell = NSBundle.mainBundle().loadNibNamed("<cell identifire>", owner: self, options: nil)[0] as! <cell name>;
}
<cell name>.<label name>.text = <your array>[indexPath.row] as? String
return cell as <cell name>
}
//MARK: - Custom Methods
func UpdateRowHeight ( ViewToAdd : UILabel , textToAdd : AnyObject ) -> CGFloat{
var actualHeight : CGFloat = ViewToAdd.frame.size.height
if let strName : String? = (textToAdd as? String)
where !strName!.isEmpty
{
actualHeight = heightForView1(strName!, font: ViewToAdd.font, width: ViewToAdd.frame.size.width, DesignTimeHeight: actualHeight )
}
return actualHeight
}
Reflection is your friend, as has been pointed out. But you need to use the correct method;
Assembly.GetEntryAssembly() //gives you the entrypoint assembly for the process.
Assembly.GetCallingAssembly() // gives you the assembly from which the current method was called.
Assembly.GetExecutingAssembly() // gives you the assembly in which the currently executing code is defined
Assembly.GetAssembly( Type t ) // gives you the assembly in which the specified type is defined.
You may try adding an additional argument of type HttpServletRequest
to the getUrlValue()
method:
@RequestMapping(value ="/",produces = "application/json")
public String getURLValue(HttpServletRequest request){
String test = request.getRequestURI();
return test;
}
date("Y-m-d H:i:s"); // This should do it.
Logical operators for boolean indexing in Pandas
It's important to realize that you cannot use any of the Python logical operators (and
, or
or not
) on pandas.Series
or pandas.DataFrame
s (similarly you cannot use them on numpy.array
s with more than one element). The reason why you cannot use those is because they implicitly call bool
on their operands which throws an Exception because these data structures decided that the boolean of an array is ambiguous:
>>> import numpy as np
>>> import pandas as pd
>>> arr = np.array([1,2,3])
>>> s = pd.Series([1,2,3])
>>> df = pd.DataFrame([1,2,3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> bool(s)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> bool(df)
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
I did cover this more extensively in my answer to the "Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()" Q+A.
However NumPy provides element-wise operating equivalents to these operators as functions that can be used on numpy.array
, pandas.Series
, pandas.DataFrame
, or any other (conforming) numpy.array
subclass:
and
has np.logical_and
or
has np.logical_or
not
has np.logical_not
numpy.logical_xor
which has no Python equivalent but is a logical "exclusive or" operation So, essentially, one should use (assuming df1
and df2
are pandas DataFrames):
np.logical_and(df1, df2)
np.logical_or(df1, df2)
np.logical_not(df1)
np.logical_xor(df1, df2)
However in case you have boolean NumPy array, pandas Series, or pandas DataFrames you could also use the element-wise bitwise functions (for booleans they are - or at least should be - indistinguishable from the logical functions):
np.bitwise_and
or the &
operatornp.bitwise_or
or the |
operatornp.invert
(or the alias np.bitwise_not
) or the ~
operatornp.bitwise_xor
or the ^
operatorTypically the operators are used. However when combined with comparison operators one has to remember to wrap the comparison in parenthesis because the bitwise operators have a higher precedence than the comparison operators:
(df1 < 10) | (df2 > 10) # instead of the wrong df1 < 10 | df2 > 10
This may be irritating because the Python logical operators have a lower precendence than the comparison operators so you normally write a < 10 and b > 10
(where a
and b
are for example simple integers) and don't need the parenthesis.
It is really important to stress that bit and logical operations are only equivalent for boolean NumPy arrays (and boolean Series & DataFrames). If these don't contain booleans then the operations will give different results. I'll include examples using NumPy arrays but the results will be similar for the pandas data structures:
>>> import numpy as np
>>> a1 = np.array([0, 0, 1, 1])
>>> a2 = np.array([0, 1, 0, 1])
>>> np.logical_and(a1, a2)
array([False, False, False, True])
>>> np.bitwise_and(a1, a2)
array([0, 0, 0, 1], dtype=int32)
And since NumPy (and similarly pandas) does different things for boolean (Boolean or “mask” index arrays) and integer (Index arrays) indices the results of indexing will be also be different:
>>> a3 = np.array([1, 2, 3, 4])
>>> a3[np.logical_and(a1, a2)]
array([4])
>>> a3[np.bitwise_and(a1, a2)]
array([1, 1, 1, 2])
Logical operator | NumPy logical function | NumPy bitwise function | Bitwise operator
-------------------------------------------------------------------------------------
and | np.logical_and | np.bitwise_and | &
-------------------------------------------------------------------------------------
or | np.logical_or | np.bitwise_or | |
-------------------------------------------------------------------------------------
| np.logical_xor | np.bitwise_xor | ^
-------------------------------------------------------------------------------------
not | np.logical_not | np.invert | ~
Where the logical operator does not work for NumPy arrays, pandas Series, and pandas DataFrames. The others work on these data structures (and plain Python objects) and work element-wise.
However be careful with the bitwise invert on plain Python bool
s because the bool will be interpreted as integers in this context (for example ~False
returns -1
and ~True
returns -2
).
My issue was inside of my app.gradle. I ran into this issue when I moved
apply plugin: "com.android.application"
from the top line to below a line with
apply from:
I switched the plugin back to the top and violá
My exact error was
Could not find method android() for arguments [dotenv_wke4apph61tdae6bfodqe7sj$_run_closure1@5d9d91a5] on project ':app' of type org.gradle.api.Project.
The top of my app.gradle now looks like this
project.ext.envConfigFiles = [
debug: ".env",
release: ".env",
anothercustombuild: ".env",
]
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"
apply plugin: "com.android.application"
When you start tomcat independently and type http://localhost:8080/
, tomcat show its default page (tomcat has its default page at TOMCAT_ROOT_DIRECTORY\webapps\ROOT\index.jsp
).
When you start tomcat from eclipse, eclipse doesn't have any default page for url http://localhost:8080/
so it show error message. This doesn't mean that tomcat7 is not running.when you put your project specific url like http://localhost:8080/PROJECT_NAME_YOU_HAVE_CREATE_USING_ECLIPSE
will display the default page of your web project.
This Link helped me alot http://www.codescratcher.com/wpf/remove-default-mouse-over-effect-on-wpf-buttons/
Define a style in UserControl.Resources or Window.Resources
<Window.Resources>
<Style x:Key="MyButton" TargetType="Button">
<Setter Property="OverridesDefaultStyle" Value="True" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Name="border" BorderThickness="0" BorderBrush="Black" Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Opacity" Value="0.8" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
Then add the style to your button this way Style="{StaticResource MyButton}"
<Button Name="btnSecond" Width="350" Height="120" Margin="15" Style="{StaticResource MyButton}">
<Button.Background>
<ImageBrush ImageSource="/Remove_Default_Button_Effect;component/Images/WithStyle.jpg"></ImageBrush>
</Button.Background>
</Button>
I solved a similar issue applying some padding to the LinearLayout like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/app_background"
android:padding="35dip">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/black">
</RelativeLayout>
</LinearLayout>
This probably won't give you an exact percentage but can be easily graduated and avoid extra unnecessary layout elements.
A bean is a Java class with method names that follow the Java Bean guidelines (also called design patterns) for properties, methods, and events . Thus, any public method of the bean class that is not part of a property definition is a bean method. Minimally, a Java class even with either a property as the sole member (of course, accompanying public getter and setter required), a public method as the sole member or just one public event listener registration method is a Java bean. Furthermore, the property can either be read-only property (has a getter method but no setter) or write-only property (has a setter method only). The Java bean needs to be a public class to be visible to any beanbox tool or container. The container must be able to instantiate it; thus, it must have a public constructor too. The JavaBeans specification doesn’t require a bean to have a public zero-args constructor, explicit or default, for a container to instantiate it. If you could provide a file (with extension .ser) containing a serialized instance, a beanbox tool could use that file to instantiate a prototype bean. Otherwise, the bean must have a public zero-args constructor, either explicit or default.
Once the bean is instantiated, the Java Bean API ( java.beans.*) can introspect it and call methods on it. If no class implementing the interface BeanInfo or extending a BeanInfo implementation , SimpleBeanInfo class, is available, the introspection involves using reflection (implicit introspection) to study the methods supported by a target bean and then apply simple design patterns(the guidelines) to deduce from those methods what properties, events, and public methods are supported. If a class implementing the interface BeanInfo (for a bean Foo, it must be named FooBeanInfo) is available, the API bypasses implicit introspection and uses public methods (getPropertyDescriptor(), getMethodDescriptors(), getEventSetDescriptors() ) of this class to get the information. If a class extending SimpleBeanInfo is available, depending on which of the SimpleBeanInfo public methods (getPropertyDescriptor(), getMethodDescriptors(), getEventSetDescriptors() ) are overridden, it will use those overridden methods(s) to get information; for a method that is not overridden, it’ll default to the corresponding implicit introspection. A bean needs to be instantiated anyway even if no implicit introspection is carried on it. Thus, the requirement of a public zeri-args constructor. But, of course, the Serializable or Externalizable interface isn’t necessary for it to be recognized. However the Java Bean specification says, ‘We’d also like it to be “trivial” for the common case of a tiny Bean that simply wants to have its internal state saved and doesn’t want to think about it.’ So, all beans must implement Serializable or Externalizable interface. Overall, JavaBeans specification isn’t hard and fast about what constitutes a bean. "Writing JavaBeans components is surprisingly easy. You don't need a special tool and you don't have to implement any interfaces. Writing beans is simply a matter of following certain coding conventions. All you have to do is make your class look like a bean — tools that use beans will be able to recognize and use your bean." Trivially, even the following class is a Java Bean,
public class Trivial implements java.io.Serializable {}
Say, a bean constructor has some parameters. Suppose some are simple types. The container might not know what values to assign to them; even if it does, the resulting instance might not be reusable. It may make sense only if the user can configure (specify values) by say annotations or xml configuration files as in Spring beans. And suppose some parameters are class or interface types. Again, the container might not know what values to assign to it. It may make sense only if the user can configure (specify specific objects) by say annotations or xml configuration files. However, even in Spring (via xml configuration files), assigning specific objects (with string names) to constructor arguments ( attribute or element of constructor arguments)is not typesafe;it is basically like resource injection. Making references to other Spring beans(called collaborators; via element in a constructor argument element) is basically dependency injection and thus typesafe. Obviously, a dependency(collaborator bean) might have a constructor with injected parameters; those injected dependency(ies) might have a constructor with parameters and so on. In this scenario, ultimately, you would need some bean classes (e.g, MyBean.class) that the container can instantiate by simply calling new MyBean() before it can construct the other collaborating beans via dependency injection on constructors—thus, the requirement for the beans to have public zero-args constructor. Suppose, if a container doesn’t support dependency injection and/or doesn’t allow assigning simple-type values to constructor via some annotations or xml config files as in Spring, bean constructors shouldn’t have parameters. Even a Spring beans application would need some beans to have public zero-args constructor (e.g., in a scenario where your Spring application has no bean with just simple types as constructor arguments).
JSF managed beans run in a web container. They can be configured either with @ManagedBean annotation or with an application configuration resource file managed-bean.xml. However, it supports injection via resource injection (not typesafe) only; not fit for injection on constructors. The JSF spec requires that managed beans must have a public zero-argument constructors . Further it says, “As of version 2.3 of this specification, use of the managed bean facility as specified in this section is strongly discouraged. A better and more cohesively integrated solution for solving the same problem is to use Contexts and Dependency Injection (CDI), as specified in JSR-365." In other words, CDI managed beans to be used, which offers typesafe dependency injection on constructors akin to Spring beans. The CDI specification adopts the Managed Beans specification, which applies to all containers of the JEE platform, not just web tier. Thus, the web container needs to implement CDI specification.
Here is an extract from the Managed Bean specification “ Managed Beans are container-managed objects with minimal requirements, otherwise known under the acronym “POJOs” (Plain Old Java Objects)…they can be seen as a Java EE platform-enhanced version of the JavaBeans component model found on the Java SE platform…. It won’t be missed by the reader that Managed Beans have a precursor in the homonymous facility found in the JavaServer Faces (JSF) technology…Managed Beans as defined in this specification represent a generalization of those found in JSF; in particular, Managed Beans can be used anywhere in a Java EE application, not just in web modules. For example, in the basic component model, Managed Beans must provide a no-argument constructor, but a specification that builds on Managed Beans, such as CDI (JSR-299), can relax that requirement and allow Managed Beans to provide constructors with more complex signatures, as long as they follow some well-defined rules...A Managed Bean must not be: a final class, an abstract class, a non-static inner class. A Managed Bean may not be serializable unlike a regular JavaBean component.” Thus, the specification for Managed Beans, otherwise known as POJOs or POJO beans, allows extension as in CDI.
The CDI specification re-defines managed beans as: When running in Java EE, A top-level Java class is a managed bean if it meets requirements:
• It is not an inner class. • It is a non-abstract class, or is annotated @Decorator. • It does not implement javax.enterprise.inject.spi.Extension. • It is not annotated @Vetoed or in a package annotated @Vetoed. • It has an appropriate constructor, either: the class has a constructor with no parameters, or the class declares a constructor annotated @Inject.
All Java classes that meet these conditions are managed beans and thus no special declaration is required to define a managed bean. Or
if it is defined to be a managed bean by any other Java EE specification and if
• It is not annotated with an EJB component-defining annotation or declared as an EJB bean class in ejb-jar.xml.
Unlike Spring beans it doesn’t support constructors with simple-types, which might be possible if it supported configuration with xml config files like in Spring or any annotations.
EJBs run in an EJB container. Its specification says: “A session bean component is a Managed Bean." “The class must have a public constructor that takes no arguments,” it says for both session bean and message-driven bean. Further, it says, “The session bean class is not required to implement the SessionBean interface or the Serializable interface.” For the same reason as JSF beans, that EJB3 dependency injection is basically resource injection, JSF beans do not support constructors with arguments, that is, via dependency injection. However, if the EJB container implements CDI, “ Optionally: The class may have an additional constructor annotated with the Inject annotation, “ it says for both session bean and message-driven bean because, “An EJB packaged into a CDI bean archive and not annotated with javax.enterprise.inject.Vetoed annotation, is considered a CDI-enabled bean.”
The question is quite old so I feel like I need to give a more up to date response to this question.
Based on MonoDevelop, the best IDE for building C# applications on the Mac, for pretty much any platform is http://xamarin.com/
Using HttpClient (Http's replacement) in Angular 4.3+, the entire mapping/casting process is made simpler/eliminated.
Using your CountryData class, you would define a service method like this:
getCountries() {
return this.httpClient.get<CountryData[]>('http://theUrl.com/all');
}
Then when you need it, define an array like this:
countries:CountryData[] = [];
and subscribe to it like this:
this.countryService.getCountries().subscribe(countries => this.countries = countries);
A complete setup answer is posted here also.
I second the top voted answer, but feel like adding little more details here if anyone finds it useful.
short version:
IIS runs any website you configure in a process named w3wp.exe. IIS Application pool is feature in IIS which allows each website or a part of it to run under a corresponding w3wp.exe process. So you can run 100 websites all in a single w3wp.exe or 100 different w3wp.exe. E.g. run 3 websites in same application pool(same w3wp.exe) to save memory usage. ,run 2 different websites in two different application pools so that each can run under separate user account(called application pool identity). run a website in one application pool and a subsite 'website/app' under a different application pool.
Longer version:
Every website or a part of the website,you can run under an application pool.You can control some basic settings of the website using an application pool.
Before using reset think about using revert so you can always go back.
https://www.pixelstech.net/article/1549115148-git-reset-vs-git-revert
On request
Source: https://www.pixelstech.net/article/1549115148-git-reset-vs-git-revert
git reset vs git revert sonic0002 2019-02-02 08:26:39
When maintaining code using version control systems such as git, it is unavoidable that we need to rollback some wrong commits either due to bugs or temp code revert. In this case, rookie developers would be very nervous because they may get lost on what they should do to rollback their changes without affecting others, but to veteran developers, this is their routine work and they can show you different ways of doing that. In this post, we will introduce two major ones used frequently by developers.
What are their differences and corresponding use cases? We will discuss them in detail below. git reset Assuming we have below few commits.
Commit A and B are working commits, but commit C and D are bad commits. Now we want to rollback to commit B and drop commit C and D. Currently HEAD is pointing to commit D 5lk4er, we just need to point HEAD to commit B a0fvf8 to achieve what we want. It's easy to use git reset command.
git reset --hard a0fvf8
After executing above command, the HEAD will point to commit B.
But now the remote origin still has HEAD point to commit D, if we directly use git push to push the changes, it will not update the remote repo, we need to add a -f option to force pushing the changes.
git push -f
The drawback of this method is that all the commits after HEAD will be gone once the reset is done. In case one day we found that some of the commits ate good ones and want to keep them, it is too late. Because of this, many companies forbid to use this method to rollback changes.
git revert The use of git revert is to create a new commit which reverts a previous commit. The HEAD will point to the new reverting commit. For the example of git reset above, what we need to do is just reverting commit D and then reverting commit C.
git revert 5lk4er
git revert 76sdeb
Now it creates two new commit D' and C',
In above example, we have only two commits to revert, so we can revert one by one. But what if there are lots of commits to revert? We can revert a range indeed.
git revert OLDER_COMMIT^..NEWER_COMMIT
This method would not have the disadvantage of git reset, it would point HEAD to newly created reverting commit and it is ok to directly push the changes to remote without using the -f option. Now let's take a look at a more difficult example. Assuming we have three commits but the bad commit is the second commit.
It's not a good idea to use git reset to rollback the commit B since we need to keep commit C as it is a good commit. Now we can revert commit C and B and then use cherry-pick to commit C again.
From above explanation, we can find out that the biggest difference between git reset and git revert is that git reset will reset the state of the branch to a previous state by dropping all the changes post the desired commit while git revert will reset to a previous state by creating new reverting commits and keep the original commits. It's recommended to use git revert instead of git reset in enterprise environment. Reference: https://kknews.cc/news/4najez2.html
I know this might seem to be extremely late.. however it may help someone out there
I wanted to get the AM PM part of the date, so I used what Andy advised:
dateTime.ToString("tt");
I used that part to construct a Path to save my files.. I built my assumptions that I will get either AM or PM and nothing else !!
however when I used a PC that its culture is not English ..( in my case ARABIC) .. my application failed becase the format "tt" returned something new not AM nor PM (? or ?)..
So the fix to this was to ignore the culture by adding the second argument as follow:
dateTime.ToString("tt", CultureInfo.InvariantCulture);
.. of course u have to add : using System.Globalization; on top of ur file I hope that will help someone :)
It turns out this is actually possible, but not using the genuine Docker CE or EE version.
You can either use Red Hat's fork of docker with the '--add-registry' flag or you can build docker from source yourself with registry/config.go modified to use your own hard-coded default registry namespace/index.
The shorthand for $(document).ready(handler)
is $(handler)
(where handler
is a function). See here.
The code in your question has nothing to do with .ready()
. Rather, it is an immediately-invoked function expression (IIFE) with the jQuery object as its argument. Its purpose is to restrict the scope of at least the $
variable to its own block so it doesn't cause conflicts. You typically see the pattern used by jQuery plugins to ensure that $ == jQuery
.
I needed to do something like this really fast really simple, from searching for ideas i finally built this template. The idea is receive the weighted values in a form of a json from the api, which here is simulated by the dict.
Then translate it into a list in which each value repeats proportionally to it's weight, and just use random.choice to select a value from the list.
I tried it running with 10, 100 and 1000 iterations. The distribution seems pretty solid.
def weighted_choice(weighted_dict):
"""Input example: dict(apples=60, oranges=30, pineapples=10)"""
weight_list = []
for key in weighted_dict.keys():
weight_list += [key] * weighted_dict[key]
return random.choice(weight_list)
Just in case this helps anybody else out there, I stumbled on an obscure case for this error triggering last night. Specifically, I was using the require_once method and specifying only a filename and no path, since the file being required was present in the same directory.
I started to get the 'Failed opening required file' error at one point. After tearing my hair out for a while, I finally noticed a PHP Warning message immediately above the fatal error output, indicating 'failed to open stream: Permission denied', but more importantly, informing me of the path to the file it was trying to open. I then twigged to the fact I had created a copy of the file (with ownership not accessible to Apache) elsewhere that happened to also be in the PHP 'include' search path, and ahead of the folder where I wanted it to be picked up. D'oh!
public static JSONArray RemoveJSONArray( JSONArray jarray,int pos) {
JSONArray Njarray=new JSONArray();
try{
for(int i=0;i<jarray.length();i++){
if(i!=pos)
Njarray.put(jarray.get(i));
}
}catch (Exception e){e.printStackTrace();}
return Njarray;
}
You may use the ==
operator to compare unicode objects for equality.
>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>>
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>>
But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode
object to a str
object, like so:
>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False
See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.
Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.
I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."
You can create these easily using the floating ability of CSS, for example. I have created a small example on Jsfiddle over here, all the related css and html is also provided there.
.foo {_x000D_
float: left;_x000D_
width: 20px;_x000D_
height: 20px;_x000D_
margin: 5px;_x000D_
border: 1px solid rgba(0, 0, 0, .2);_x000D_
}_x000D_
_x000D_
.blue {_x000D_
background: #13b4ff;_x000D_
}_x000D_
_x000D_
.purple {_x000D_
background: #ab3fdd;_x000D_
}_x000D_
_x000D_
.wine {_x000D_
background: #ae163e;_x000D_
}
_x000D_
<div class="foo blue"></div>_x000D_
<div class="foo purple"></div>_x000D_
<div class="foo wine"></div>
_x000D_
can use this to redirect
echo '<meta http-equiv="refresh" content="1; URL=index.php" />';
the content=1 can be change to different value to increase the delay before redirection
Try this:
$("div[class]").filter(function() {
var classNames = this.className.split(/\s+/);
for (var i=0; i<classNames.length; ++i) {
if (classNames[i].substr(0, 6) === "apple-") {
return true;
}
}
return false;
})
Sample here:
<Style TargetType="Window" x:Key="DialogWindow">
<Setter Property="AllowsTransparency" Value="True"/>
<Setter Property="WindowStyle" Value="None"/>
<Setter Property="ResizeMode" Value="CanResizeWithGrip"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Window}">
<Border BorderBrush="Black" BorderThickness="3" CornerRadius="10" Height="{TemplateBinding Height}"
Width="{TemplateBinding Width}" Background="Gray">
<DockPanel>
<Grid DockPanel.Dock="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition Width="50"/>
</Grid.ColumnDefinitions>
<Label Height="35" Grid.ColumnSpan="2"
x:Name="PART_WindowHeader"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"/>
<Button Width="15" Height="15" Content="x" Grid.Column="1" x:Name="PART_CloseButton"/>
</Grid>
<Border HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
Background="LightBlue" CornerRadius="0,0,10,10"
Grid.ColumnSpan="2"
Grid.RowSpan="2">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="20"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="20"></RowDefinition>
</Grid.RowDefinitions>
<ResizeGrip Width="10" Height="10" Grid.Column="1" VerticalAlignment="Bottom" Grid.Row="1"/>
</Grid>
</Border>
</DockPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
If it helps anyone, I was having an issue where I wanted to treat an object as another type with a similar interface. I attempted the following:
Didn't pass linting
const x = new Obj(a as b);
The linter was complaining that a
was missing properties that existed on b
. In other words, a
had some properties and methods of b
, but not all. To work around this, I followed VS Code's suggestion:
Passed linting and testing
const x = new Obj(a as unknown as b);
Note that if your code attempts to call one of the properties that exists on type b
that is not implemented on type a
, you should realize a runtime fault.
You can update a Hive partition by, for example:
ALTER TABLE logs PARTITION(year = 2012, month = 12, day = 18)
SET LOCATION 'hdfs://user/darcy/logs/2012/12/18';
This command does not move the old data, nor does it delete the old data. It simply sets the partition to the new location.
To drop a partition, you can do
ALTER TABLE logs DROP IF EXISTS PARTITION(year = 2012, month = 12, day = 18);
Hope it helps!
Add classpath com.google.gms:google-services:3.0.0
dependencies at project level build.gradle
Refer the sample block from project level build.gradle
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
classpath 'com.google.gms:google-services:3.0.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
The latest google api docs document how to write to a spreadsheet with python but it's a little difficult to navigate to. Here is a link to an example of how to append.
The following code is my first successful attempt at appending to a google spreadsheet.
import httplib2
import os
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'mail_to_g_app.json')
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def add_todo():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
'version=v4')
service = discovery.build('sheets', 'v4', http=http,
discoveryServiceUrl=discoveryUrl)
spreadsheetId = 'PUT YOUR SPREADSHEET ID HERE'
rangeName = 'A1:A'
# https://developers.google.com/sheets/guides/values#appending_values
values = {'values':[['Hello Saturn',],]}
result = service.spreadsheets().values().append(
spreadsheetId=spreadsheetId, range=rangeName,
valueInputOption='RAW',
body=values).execute()
if __name__ == '__main__':
add_todo()
const printHtml = async (html) => {
const printable = window.open('', '_blank', 'fullscreen=no');
printable.document.open();
printable.document.write(`<html><body onload="window.print()">${html}</body></html>`);
await printable.print();
printable.close();
};
Here's my ES2016 solution.
In case of someone else is doing it in Python and it is not working, try to set it before do the imports of pycuda and tensorflow.
I.e.:
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
...
import pycuda.autoinit
import tensorflow as tf
...
As saw here.
I had to change my values/styles.xml to
<!-- Base application theme. -->
<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
Before that change, it was without 'Base'.
(IntelliJ IDEA 2017.2.4)
If you're trying to use MatDialog
inside a service - let's call it 'PopupService'
and that service is defined in a module with:
@Injectable({ providedIn: 'root' })
then it may not work. I am using lazy loading, but not sure if that's relevant or not.
You have to:
PopupService
directly to the component that opens your dialog - using [ provide: PopupService ]
. This allows it to use (with DI) the MatDialog
instance in the component. I think the component calling open
needs to be in the same module as the dialog component in this instance.matDialog
when you call your service.Excuse my jumbled answer, the point being it's the providedIn: 'root'
that is breaking things because MatDialog needs to piggy-back off a component.
To expound on darioo's answer with a concrete example. Tomcat 7 installed using homebrew on OS X, using Eclipse:
What? No Tomcat version is listed even though you have it installed via homebrew??
Hope that helps someone who is just getting started out a little.
I've finally done it in this way.
Added a ServletContextListener that does the following:
public void contextInitialized(ServletContextEvent event) {
ServletContext context = event.getServletContext();
System.setProperty("rootPath", context.getRealPath("/"));
}
Then in the log4j.properties file:
log4j.appender.file.File=${rootPath}WEB-INF/logs/MyLog.log
By doing it in this way Log4j will write into the right folder as long as you don't use it before the "rootPath" system property has been set. This means that you cannot use it from the ServletContextListener itself but you should be able to use it from anywhere else in the app.
It should work on every web container and OS as it's not dependent on a container specific system property and it's not affected by OS specific path issues. Tested with Tomcat and Orion web containers and on Windows and Linux and it works fine so far.
What do you think?
Usually, git creates a hidden directory in project's root directory (.git/)
When you're working on a CMS, its possible you install modules/plugins carrying .git/ directory with git's metadata for the specific module/plugin
Quickest solution is to find all .git directories and keep only your root git metadata directory. If you do so, git will not consider those modules as project submodules.
Kirk's answer is right on. As a rule, you're not going to have any luck with type inference when your method signature has fewer types of parameters than it has generic type parameters.
In your particular case, it seems you could possibly move the T
type parameter to the class level and then get type inference on your Get
method:
class ServiceGate<T>
{
public IAccess<S, T> Get<S>(S sig) where S : ISignatur<T>
{
throw new NotImplementedException();
}
}
Then the code you posted with the CS0411 error could be rewritten as:
static void Main()
{
// Notice: a bit more cumbersome to write here...
ServiceGate<SomeType> service = new ServiceGate<SomeType>();
// ...but at least you get type inference here.
IAccess<Signatur, SomeType> access = service.Get(new Signatur());
}
So after running brew install mcrypt php
, I had to install php-mcrypt via pecl:
pecl install mcrypt-1.0.1
At the time of writing, mcrypt does not have a stable pecl release, 1.0.1 being the current release for php 7.2 and 7.3, and brew install php
will install php 7.2.
One statement can be written as such:
someValues.forEach(x => console.log(x));
or multiple statements can be enclosed in {}
like this:
someValues.forEach(x => { let a = 2 + x; console.log(a); });
For an updated answer see this SO question:
calling web service using VBA code in excel 2010
Both threads should be merged though.
try with this
$ cat /tmp/topfs.txt
/dev/sda2 xfs 32G 10G 22G 32% /
awk print last column
$ cat /tmp/topfs.txt | awk '{print $NF}'
awk print before last column
$ cat /tmp/topfs.txt | awk '{print $(NF-1)}'
32%
awk - print last two columns
$ cat /tmp/topfs.txt | awk '{print $(NF-1), $NF}'
32% /
Shift-Right Click on the folder and select TortoiseSVN -> Merge All
Mark gravell suggested this if you have .NET Core 3, System.Runtime.Intrinsics.X86.Popcnt.PopCount
public bool IsPowerOfTwo(uint i)
{
return Popcnt.PopCount(i) == 1
}
Single instruction, faster than (x != 0) && ((x & (x - 1)) == 0)
but less portable.
You can set the format in aspx, just add the property "DateFormatString" in your BoundField.
DataFormatString="{0:dd/MM/yyyy hh:mm:ss}"
Check the sql log in the LOG directory of your instance - see if anything is going on there. You'll need to stop the service to open the log - or restart and you can read the old one - named with .1 on the end.
With the error you're getting, you need to enable TCP/IP or Named pipes for named connections. Shared memory connection should work, but you seem to not be using that. Are you trying to connect through SSMS?
In my log I see entries like this...
Server local connection provider is ready to accept connection on [\\.\pipe\mssql$sqlexpress\sql\query ]
As the comments said, .\SQLEXPRESS should work. Also worstationName\SQLEXPRESS will work.
There is no simple and elegant solution to the Redirect
problem in ASP.Net WebForms. You can choose between the Dirty solution and the Tedious solution
Dirty: Response.Redirect(url)
sends a redirect to the browser, and then throws a ThreadAbortedException
to terminate the current thread. So no code is executed past the Redirect()-call. Downsides: It is bad practice and have performance implications to kill threads like this. Also, ThreadAbortedExceptions
will show up in exception logging.
Tedious: The recommended way is to call Response.Redirect(url, false)
and then Context.ApplicationInstance.CompleteRequest()
However, code execution will continue and the rest of the event handlers in the page lifecycle will still be executed. (E.g. if you perform the redirect in Page_Load, not only will the rest of the handler be executed, Page_PreRender and so on will also still be called - the rendered page will just not be sent to the browser. You can avoid the extra processing by e.g. setting a flag on the page, and then let subsequent event handlers check this flag before before doing any processing.
(The documentation to CompleteRequest
states that it "Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution". This can easily be misunderstood. It does bypass further HTTP filters and modules, but it doesn't bypass further events in the current page lifecycle.)
The deeper problem is that WebForms lacks a level of abstraction. When you are in a event handler, you are already in the process of building a page to output. Redirecting in an event handler is ugly because you are terminating a partially generated page in order to generate a different page. MVC does not have this problem since the control flow is separate from rendering views, so you can do a clean redirect by simply returning a RedirectAction
in the controller, without generating a view.
[edit] The lovely chosen jQuery plugin has been bought to my attention, looks like a great alternative to me.
Or if you just want to use jQuery autocomplete, I've extended the combobox example to support defaults and remove the tooltips to give what I think is more expected behaviour. Try it out.
(function ($) {
$.widget("ui.combobox", {
_create: function () {
var input,
that = this,
wasOpen = false,
select = this.element.hide(),
selected = select.children(":selected"),
defaultValue = selected.text() || "",
wrapper = this.wrapper = $("<span>")
.addClass("ui-combobox")
.insertAfter(select);
function removeIfInvalid(element) {
var value = $(element).val(),
matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(value) + "$", "i"),
valid = false;
select.children("option").each(function () {
if ($(this).text().match(matcher)) {
this.selected = valid = true;
return false;
}
});
if (!valid) {
// remove invalid value, as it didn't match anything
$(element).val(defaultValue);
select.val(defaultValue);
input.data("ui-autocomplete").term = "";
}
}
input = $("<input>")
.appendTo(wrapper)
.val(defaultValue)
.attr("title", "")
.addClass("ui-state-default ui-combobox-input")
.width(select.width())
.autocomplete({
delay: 0,
minLength: 0,
autoFocus: true,
source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(select.children("option").map(function () {
var text = $(this).text();
if (this.value && (!request.term || matcher.test(text)))
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>"),
value: text,
option: this
};
}));
},
select: function (event, ui) {
ui.item.option.selected = true;
that._trigger("selected", event, {
item: ui.item.option
});
},
change: function (event, ui) {
if (!ui.item) {
removeIfInvalid(this);
}
}
})
.addClass("ui-widget ui-widget-content ui-corner-left");
input.data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li>")
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
$("<a>")
.attr("tabIndex", -1)
.appendTo(wrapper)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("ui-corner-right ui-combobox-toggle")
.mousedown(function () {
wasOpen = input.autocomplete("widget").is(":visible");
})
.click(function () {
input.focus();
// close if already visible
if (wasOpen) {
return;
}
// pass empty string as value to search for, displaying all results
input.autocomplete("search", "");
});
},
_destroy: function () {
this.wrapper.remove();
this.element.show();
}
});
})(jQuery);
Minizip does have an example programs to demonstrate its usage - the files are called minizip.c and miniunz.c.
Update: I had a few minutes so I whipped up this quick, bare bones example for you. It's very smelly C, and I wouldn't use it without major improvements. Hopefully it's enough to get you going for now.
// uzip.c - Simple example of using the minizip API.
// Do not use this code as is! It is educational only, and probably
// riddled with errors and leaks!
#include <stdio.h>
#include <string.h>
#include "unzip.h"
#define dir_delimter '/'
#define MAX_FILENAME 512
#define READ_SIZE 8192
int main( int argc, char **argv )
{
if ( argc < 2 )
{
printf( "usage:\n%s {file to unzip}\n", argv[ 0 ] );
return -1;
}
// Open the zip file
unzFile *zipfile = unzOpen( argv[ 1 ] );
if ( zipfile == NULL )
{
printf( "%s: not found\n" );
return -1;
}
// Get info about the zip file
unz_global_info global_info;
if ( unzGetGlobalInfo( zipfile, &global_info ) != UNZ_OK )
{
printf( "could not read file global info\n" );
unzClose( zipfile );
return -1;
}
// Buffer to hold data read from the zip file.
char read_buffer[ READ_SIZE ];
// Loop to extract all files
uLong i;
for ( i = 0; i < global_info.number_entry; ++i )
{
// Get info about current file.
unz_file_info file_info;
char filename[ MAX_FILENAME ];
if ( unzGetCurrentFileInfo(
zipfile,
&file_info,
filename,
MAX_FILENAME,
NULL, 0, NULL, 0 ) != UNZ_OK )
{
printf( "could not read file info\n" );
unzClose( zipfile );
return -1;
}
// Check if this entry is a directory or file.
const size_t filename_length = strlen( filename );
if ( filename[ filename_length-1 ] == dir_delimter )
{
// Entry is a directory, so create it.
printf( "dir:%s\n", filename );
mkdir( filename );
}
else
{
// Entry is a file, so extract it.
printf( "file:%s\n", filename );
if ( unzOpenCurrentFile( zipfile ) != UNZ_OK )
{
printf( "could not open file\n" );
unzClose( zipfile );
return -1;
}
// Open a file to write out the data.
FILE *out = fopen( filename, "wb" );
if ( out == NULL )
{
printf( "could not open destination file\n" );
unzCloseCurrentFile( zipfile );
unzClose( zipfile );
return -1;
}
int error = UNZ_OK;
do
{
error = unzReadCurrentFile( zipfile, read_buffer, READ_SIZE );
if ( error < 0 )
{
printf( "error %d\n", error );
unzCloseCurrentFile( zipfile );
unzClose( zipfile );
return -1;
}
// Write data to file.
if ( error > 0 )
{
fwrite( read_buffer, error, 1, out ); // You should check return of fwrite...
}
} while ( error > 0 );
fclose( out );
}
unzCloseCurrentFile( zipfile );
// Go the the next entry listed in the zip file.
if ( ( i+1 ) < global_info.number_entry )
{
if ( unzGoToNextFile( zipfile ) != UNZ_OK )
{
printf( "cound not read next file\n" );
unzClose( zipfile );
return -1;
}
}
}
unzClose( zipfile );
return 0;
}
I built and tested it with MinGW/MSYS on Windows like this:
contrib/minizip/$ gcc -I../.. -o unzip uzip.c unzip.c ioapi.c ../../libz.a
contrib/minizip/$ ./unzip.exe /j/zlib-125.zip
This question got many answers but none cover the entire process to return clean JSON with everything required to prevent the JSON response to be malformed.
/*
* returnJsonHttpResponse
* @param $success: Boolean
* @param $data: Object or Array
*/
function returnJsonHttpResponse($success, $data)
{
// remove any string that could create an invalid JSON
// such as PHP Notice, Warning, logs...
ob_clean();
// this will clean up any previously added headers, to start clean
header_remove();
// Set the content type to JSON and charset
// (charset can be set to something else)
header("Content-type: application/json; charset=utf-8");
// Set your HTTP response code, 2xx = SUCCESS,
// anything else will be error, refer to HTTP documentation
if ($success) {
http_response_code(200);
} else {
http_response_code(500);
}
// encode your PHP Object or Array into a JSON string.
// stdClass or array
echo json_encode($data);
// making sure nothing is added
exit();
}
References:
Refer to http://api.jquery.com/on/
It says
In all browsers, the load, scroll, and error events (e.g., on an
<img>
element) do not bubble. In Internet Explorer 8 and lower, the paste and reset events do not bubble. Such events are not supported for use with delegation, but they can be used when the event handler is directly attached to the element generating the event.
If you want to do something when a new input box is added then you can simply write the code after appending it.
$('#add').click(function(){
$('body').append(x);
// Your code can be here
});
And if you want the same code execute when the first input box within the document is loaded then you can write a function and call it in both places i.e. $('#add').click
and document's ready event
It is possible to do everything you want. Aaron's answer was not quite complete.
His approach is correct, up to creating the temporary table in the inner query. Then, you need to insert the results into a table in the outer query.
The following code snippet grabs the first line of a file and inserts it into the table @Lines:
declare @fieldsep char(1) = ',';
declare @recordsep char(1) = char(10);
declare @Lines table (
line varchar(8000)
);
declare @sql varchar(8000) = '
create table #tmp (
line varchar(8000)
);
bulk insert #tmp
from '''+@filename+'''
with (FirstRow = 1, FieldTerminator = '''+@fieldsep+''', RowTerminator = '''+@recordsep+''');
select * from #tmp';
insert into @Lines
exec(@sql);
select * from @lines
If you want to redirect, just use window.location
. Like so:
window.location = "http://www.redirectedsite.com"
There are few mistakes you are doing:
addRow
methodsplice
method to remove an element from an array at particular index.my-item
component, where this can be modified.You can see working code here.
addRow(){
this.rows.push({description: '', unitprice: '' , code: ''}); // what to push unto the rows array?
},
removeRow(index){
this. itemList.splice(index, 1)
}
VideoView myVideo = (VideoView) rootView.findViewById(R.id.definition_video_view);
//Set video name (no extension)
String myVideoName = "my_video";
//Set app package
String myAppPackage = "com.myapp";
//Get video URI from raw directory
Uri myVideoUri = Uri.parse("android.resource://"+myAppPackage+"/raw/"+myVideoName);
//Set the video URI
myVideo.setVideoURI(myVideoUri);
//Play the video
myVideo.start();
/* Didn't test it but this should work "out of the box" */
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//you should edit this to fit your needs
builder.setTitle("Double Edit Text");
final EditText one = new EditText(this);
from.setHint("one");//optional
final EditText two = new EditText(this);
to.setHint("two");//optional
//in my example i use TYPE_CLASS_NUMBER for input only numbers
from.setInputType(InputType.TYPE_CLASS_NUMBER);
to.setInputType(InputType.TYPE_CLASS_NUMBER);
LinearLayout lay = new LinearLayout(this);
lay.setOrientation(LinearLayout.VERTICAL);
lay.addView(one);
lay.addView(two);
builder.setView(lay);
// Set up the buttons
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//get the two inputs
int i = Integer.parseInt(one.getText().toString());
int j = Integer.parseInt(two.getText().toString());
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
builder.show();
I had the similar problem. It was a maven project with the following snippet of pom.xml.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<release>9</release>
</configuration>
</plugin>
</plugins>
</build>
I had to change the following.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<release>11</release>
</configuration>
</plugin>
</plugins>
</build>
If you have already installed JDK 11 and working with java 9 or java 10 as maven compiler, eclipse can not detect. Hence change the release to 11 or the actual installed version of JDK.
Here'a my attempt to summarize built-in capabilities windows for compression and uncompression - How can I compress (/ zip ) and uncompress (/ unzip ) files and folders with batch file without using any external tools?
with a few given solutions that should work on almost every windows machine.
As regards to the shell.application and WSH I preferred the jscript as it allows a hybrid batch/jscript file (with .bat extension) that not require temp files.I've put unzip and zip capabilities in one file plus a few more features.
You can use $addToSet with the aggregation framework to count distinct objects.
For example:
db.collectionName.aggregate([{
$group: {_id: null, uniqueValues: {$addToSet: "$fieldName"}}
}])
Once you have the source trees, e.g.
diff -ENwbur repos1/ repos2/
Even better
diff -ENwbur repos1/ repos2/ | kompare -o -
and have a crack at it in a good gui tool :)
Is NDEBUG standard?
Yes it is a standard macro with the semantic "Not Debug" for C89, C99, C++98, C++2003, C++2011, C++2014 standards. There are no _DEBUG
macros in the standards.
C++2003 standard send the reader at "page 326" at "17.4.2.1 Headers" to standard C.
That NDEBUG is similar as This is the same as the Standard C library.
In C89 (C programmers called this standard as standard C) in "4.2 DIAGNOSTICS" section it was said
http://port70.net/~nsz/c/c89/c89-draft.html
If NDEBUG is defined as a macro name at the point in the source file where is included, the assert macro is defined simply as
#define assert(ignore) ((void)0)
If look at the meaning of _DEBUG
macros in Visual Studio
https://msdn.microsoft.com/en-us/library/b0084kay.aspx
then it will be seen, that this macro is automatically defined by your ?hoice of language runtime library version.
Your target domain might refuse to send you information. This can work as a filter based on browser agent or any other header information. This is a defense against bots, crawlers or any unwanted applications.
Above screenshot taken from this live example: https://regex101.com/r/cU5lC2/1
I'll be using the phpsh interactive shell on Ubuntu 12.10 to demonstrate the PCRE regex engine through the method known as preg_match
Start phpsh, put some content into a variable, match on word.
el@apollo:~/foo$ phpsh
php> $content1 = 'badger'
php> $content2 = '1234'
php> $content3 = '$%^&'
php> echo preg_match('(\w+)', $content1);
1
php> echo preg_match('(\w+)', $content2);
1
php> echo preg_match('(\w+)', $content3);
0
The preg_match method used the PCRE engine within the PHP language to analyze variables: $content1
, $content2
and $content3
with the (\w)+
pattern.
$content1 and $content2 contain at least one word, $content3 does not.
el@apollo:~/foo$ phpsh
php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'darty gun';
php> $gun4 = 'unicorn gun';
php> echo preg_match('(dart|fart)', $gun1);
1
php> echo preg_match('(dart|fart)', $gun2);
1
php> echo preg_match('(dart|fart)', $gun3);
1
php> echo preg_match('(dart|fart)', $gun4);
0
Variables gun1
and gun2
contain the string dart
or fart
which is correct, but gun3 contains darty
and still matches, that is the problem. So onto the next example.
Word Boundaries can be force matched with \b
, see:
Regex Visual Image acquired from http://jex.im/regulex and https://github.com/JexCheng/regulex Example:
el@apollo:~/foo$ phpsh
php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'darty gun';
php> $gun4 = 'unicorn gun';
php> echo preg_match('(\bdart\b|\bfart\b)', $gun1);
1
php> echo preg_match('(\bdart\b|\bfart\b)', $gun2);
1
php> echo preg_match('(\bdart\b|\bfart\b)', $gun3);
0
php> echo preg_match('(\bdart\b|\bfart\b)', $gun4);
0
The \b
asserts that we have a word boundary, making sure " dart " is matched, but " darty " isn't.
This can be simplified by completely skipping the where object and the $users declaration. All you need is:
Code
get-content c:\scripts\users.txt | get-aduser -properties * | select displayname, office | export-csv c:\path\to\your.csv
python setup.py install
You may need administrator privileges for step 5. What you do here thus depends on your operating system. For example in Ubuntu you would say sudo python setup.py install
EDIT- thanks to kwatford (see first comment)
To bypass the need for administrator privileges during step 5 above you may be able to make use of the --user flag. In this way you can install the package only for the current user.
The docs say:
Files will be installed into subdirectories of site.USER_BASE (written as userbase hereafter). This scheme installs pure Python modules and extension modules in the same location (also known as site.USER_SITE). Here are the values for UNIX, including Mac OS X:
More details can be found here: http://docs.python.org/2.7/install/index.html
I had this issue... It was the log that was huge. Logs are here :
/var/lib/docker/containers/<container id>/<container id>-json.log
You can manage this in the run command line or in the compose file. See there : Configure logging drivers
I personally added these 3 lines to my docker-compose.yml file :
my_container:
logging:
options:
max-size: 10m
Element.children
returns only element children, while Node.childNodes
returns all node children. Note that elements are nodes, so both are available on elements.
I believe childNodes
is more reliable. For example, MDC (linked above) notes that IE only got children
right in IE 9. childNodes
provides less room for error by browser implementors.
One way to control the locale settings is to set the java system properties user.language and user.region.
The definitive solution is to allow the InfoTech protocol to work in the intranet zone.
Add the following value to the registry and the problem should be solved:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp\1.x\ItssRestrictions]
"MaxAllowedZone"=dword:00000001
More info here: http://support.microsoft.com/kb/896054
Here is an example that does a union between two completely unrelated tables: the Student and the Products table. It generates an output that is 4 columns:
select
FirstName as Column1,
LastName as Column2,
email as Column3,
null as Column4
from
Student
union
select
ProductName as Column1,
QuantityPerUnit as Column2,
null as Column3,
UnitsInStock as Column4
from
Products
Obviously you'll tweak this for your own environment...
This basically has to do with the hardware architecture (i.e. RAM and caches).
If you don't use synchronized
together with wait()
or notify()
, another thread could enter the same block instead of waiting for the monitor to enter it. Moreover, when e.g. accessing an array without a synchronized block, another thread may not see the changement to it...actually another thread will not see any changements to it when it already has a copy of the array in the x-level cache (a.k.a. 1st/2nd/3rd-level caches) of the thread handling CPU core.
But synchronized blocks are only one side of the medal: If you actually access an object within a synchronized context from a non-synchronized context, the object still won't be synchronized even within a synchronized block, because it holds an own copy of the object in its cache. I wrote about this issues here: https://stackoverflow.com/a/21462631 and When a lock holds a non-final object, can the object's reference still be changed by another thread?
Furthermore, I'm convinced that the x-level caches are responsible for most non-reproducible runtime errors. That's because the developers usually don't learn the low-level stuff, like how CPU's work or how the memory hierarchy affects the running of applications: http://en.wikipedia.org/wiki/Memory_hierarchy
It remains a riddle why programming classes don't start with memory hierarchy and CPU architecture first. "Hello world" won't help here. ;)
if (!$_GET) echo "empty";
why do you need such a checking?
lol
you guys too direct-minded.
don't take as offense but sometimes not-minded at all
$_GET is very special variable, not like others.
it is supposed to be always set. no need to treat it as other variables.
when $_GET is not set and it's expected - it is emergency case and that's what "Undefined variable" notice invented for
def awgn(sinal):
regsnr=54
sigpower=sum([math.pow(abs(sinal[i]),2) for i in range(len(sinal))])
sigpower=sigpower/len(sinal)
noisepower=sigpower/(math.pow(10,regsnr/10))
noise=math.sqrt(noisepower)*(np.random.uniform(-1,1,size=len(sinal)))
return noise
I found this here that describes how to set the VBA Project Password. You should be able to modify it to unset the VBA Project Password.
This one does not use SendKeys.
Let me know if this helps! JFV
@PathVariable
is to obtain some placeholder from the URI (Spring call it an URI Template)
— see Spring Reference Chapter 16.3.2.2 URI Template Patterns@RequestParam
is to obtain a parameter from the URI as well — see Spring Reference Chapter 16.3.3.3 Binding request parameters to method parameters with @RequestParamIf the URL http://localhost:8080/MyApp/user/1234/invoices?date=12-05-2013
gets the invoices for user 1234 on December 5th, 2013, the controller method would look like:
@RequestMapping(value="/user/{userId}/invoices", method = RequestMethod.GET)
public List<Invoice> listUsersInvoices(
@PathVariable("userId") int user,
@RequestParam(value = "date", required = false) Date dateOrNull) {
...
}
Also, request parameters can be optional, and as of Spring 4.3.3 path variables can be optional as well. Beware though, this might change the URL path hierarchy and introduce request mapping conflicts. For example, would /user/invoices
provide the invoices for user null
or details about a user with ID "invoices"?
I recently needed to document how to get a version of it installed, so I've copied my steps here, as the other answers were using different sources from what I recommend, which is Cygwin. I like Cygwin because it is well maintained and provides a wealth of other utilities for Windows. Cygwin also allows you to easily update the versions as needed when vulnerabilities are fixed. Please update your version of OpenSSL often!
Open a Windows Command prompt and check to see if you have OpenSSL installed by entering: openssl version
If you get an error message that the command is NOT recognized, then install OpenSSL by referring to Cygwin following the summary steps below:
Basically, download and run the Cygwin Windows Setup App to install and to update as needed the OpenSSL application:
C:\Program Files\mosquitto>openssl versionOpenSSL 1.1.1f 31 Mar 2020
The (^) XOR operator generates 1 when it is applied on two different bits (0 and 1). It generates 0 when it is applied on two same bits (0 and 0 or 1 and 1).
Late to the party admittedly, how about this which will make your host operating system keys available to root inside the container, on the fly:
docker run -v ~/.ssh:/mnt -it my_image /bin/bash -c "ln -s /mnt /root/.ssh; ssh [email protected]"
I'm not in favour of using Dockerfile to install keys since iterations of your container may leave private keys behind.
This ia s global constant visible/accessible only in the compilation module (.cpp file). BTW using static for this purpose is deprecated. Better use an anonymous namespace and an enum:
namespace
{
enum
{
foo = 42
};
}
Look here:
It recommends using pscp.exe
from PuTTY, which can be found here: https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html
A direct transfer like FTP is not possible, because all commands during your session are send to the server.
Just to rule out the possibility you aren't actually trying to see the fragment on a GET/POST and actually want to know how to access that part of a URI object you have within your server-side code, it is under Uri.Fragment (MSDN docs).
I know you've found a solution, but really the proper way to do what you're asking is to just use the android:hint
attribute in your EditText. This text shows up when the box is empty and not focused, but disappears upon selecting the EditText box.
If someone ends up here from google, looking to convert a single figure to a .pdf (that was what I was looking for):
import matplotlib.pyplot as plt
f = plt.figure()
plt.plot(range(10), range(10), "o")
plt.show()
f.savefig("foo.pdf", bbox_inches='tight')
32 chars as hexdecimal representation, thats 2 chars per byte.
A form submission causes the page to navigate away to the action
of the form. So, you cannot submit both forms in the traditional way. If you try to do so with JavaScript by calling form.submit()
on each form in succession, each request will be aborted except for the last submission. So, you need to submit the first form asynchronously via JavaScript:
var f = document.forms.updateDB;
var postData = [];
for (var i = 0; i < f.elements.length; i++) {
postData.push(f.elements[i].name + "=" + f.elements[i].value);
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "mypage.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(postData.join("&"));
document.forms.payPal.submit();
On ubuntu most perl modules are already packaged, so installing is much faster than most other systems which have to compile.
To install Foo::Bar
at a commmand prompt for example usually you just do:
sudo apt-get install libfoo-bar-perl
Sadly not all modules follow that naming convention.
There's another way by setting the OS variable, SPRING_PROFILES_ACTIVE.
for eg :
SPRING_PROFILES_ACTIVE=dev gradle clean bootRun
Reference : How to set active Spring profiles
Probably you are behind proxy. Happened to me, used my mobile tethering (no proxy) rebuild project and error disappeared. Returned to original connection (with proxy) and rebuild with no errors.
$ ruby -ne 'puts $_.scan(/id=(\d+)/)' file
9
10
To Add a Function To a new Button on your Form: (and avoid using macro to call function)
After you created your Function (Function MyFunctionName()) and you are in form design view:
Add a new button (I don't think you can reassign an old button - not sure though).
When the button Wizard window opens up click Cancel.
Go to the Button properties Event Tab - On Click - field.
At that fields drop down menu select: Event Procedure.
Now click on button beside drop down menu that has ... in it and you will be taken to a new Private Sub in the forms Visual Basic window.
In that Private Sub type: Call MyFunctionName
It should look something like this:
Private Sub Command23_Click()
Call MyFunctionName
End Sub
Then just save it.
You can try this way :
* { margin: 0px; padding: 0px; }_x000D_
#body { height: 100vh; width: 100vw; position: relative; _x000D_
text-align: center; _x000D_
background-image: url('https://s-media-cache-ak0.pinimg.com/originals/96/2d/ff/962dff2247ad680c542622e20f44a645.jpg'); _x000D_
background-size: cover; background-repeat: no-repeat; }_x000D_
.text { position: absolute; top: 0; bottom: 0; left: 0; right: 0; height:100px; _x000D_
display: inline-block; margin: auto; z-index: 999999; }
_x000D_
<html>_x000D_
<body>_x000D_
<div id="body" class="container-fluid">_x000D_
<!--Background-->_x000D_
<!--Text-->_x000D_
<div class="text">_x000D_
<p>Random</p>_x000D_
</div> _x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
You could extend the "string" class to let you return a limited string.
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// since specified strings are treated on the fly as string objects...
string limit5 = "The quick brown fox jumped over the lazy dog.".LimitLength(5);
string limit10 = "The quick brown fox jumped over the lazy dog.".LimitLength(10);
// this line should return us the entire contents of the test string
string limit100 = "The quick brown fox jumped over the lazy dog.".LimitLength(100);
Console.WriteLine("limit5 - {0}", limit5);
Console.WriteLine("limit10 - {0}", limit10);
Console.WriteLine("limit100 - {0}", limit100);
Console.ReadLine();
}
}
public static class StringExtensions
{
/// <summary>
/// Method that limits the length of text to a defined length.
/// </summary>
/// <param name="source">The source text.</param>
/// <param name="maxLength">The maximum limit of the string to return.</param>
public static string LimitLength(this string source, int maxLength)
{
if (source.Length <= maxLength)
{
return source;
}
return source.Substring(0, maxLength);
}
}
}
Result:
limit5 - The q
limit10 - The quick
limit100 - The quick brown fox jumped over the lazy dog.
I solved this error
A connection attempt failed with "ECONNREFUSED - Connection refused by server"
by changing my port to 22 that was successful
You could simplify the above equations using the following:
boolean flag = sqlInt != 0;
If the int representation (sqlInt) of the boolean is 0 (false), the boolean (flag) will be false, otherwise it will be true.
Concise code is always nicer to work with :)
Guys Its very interesting to know that many of us face the problem of replication of lookup value while using the Vlookup/Index with Match or Hlookup.... If we have duplicate value in a cell we all know, Vlookup will pick up against the first item would be matching in loopkup array....So here is solution for you all...
e.g.
in Column A we have field called company....
Column A Column B Column C
Company_Name Value
Monster 25000
Naukri 30000
WNS 80000
American Express 40000
Bank of America 50000
Alcatel Lucent 35000
Google 75000
Microsoft 60000
Monster 35000
Bank of America 15000
Now if you lookup the above dataset, you would see the duplicity is in Company Name at Row No# 10 & 11. So if you put the vlookup, the data will be picking up which comes first..But if you use the below formula, you can make your lookup value Unique and can pick any data easily without having any dispute or facing any problem
Put the formula in C2.........A2&"_"&COUNTIF(A2:$A$2,A2)
..........Result will be Monster_1
for first line item and for row no 10 & 11.....Monster_2, Bank of America_2
respectively....Here you go now you have the unique value so now you can pick any data easily now..
Cheers!!! Anil Dhawan
Your problem is that you have declare twice the exec-maven-plugin :
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>C:\apache-camel-2.11.0\examples\camel-example-smooks-
integration\src\main\java\example\Main< /mainClass>
</configuration>
</plugin>
...
< plugin>
< groupId>org.codehaus.mojo</groupId>
< artifactId>exec-maven-plugin</artifactId>
< version>1.2</version>
< /plugin>
select get_something('NAME', sys.diutil.int_to_bool(1)) from dual;
Rules that tell how to compare and sort strings: letters order; whether case matters, whether diacritics matter etc.
For instance, if you want all letters to be different (say, if you store filenames in UNIX
), you use UTF8_BIN
collation:
SELECT 'A' COLLATE UTF8_BIN = 'a' COLLATE UTF8_BIN
---
0
If you want to ignore case and diacritics differences (say, for a search engine), you use UTF8_GENERAL_CI
collation:
SELECT 'A' COLLATE UTF8_GENERAL_CI = 'ä' COLLATE UTF8_GENERAL_CI
---
1
As you can see, this collation (comparison rule) considers capital A
and lowecase ä
the same letter, ignoring case and diacritic differences.
Use:
mysql -u root -p password -D database_name << import.sql
Use the MySQL help for details - mysql --help
.
I think these will be useful options in our context:
[~]$ mysql --help
mysql Ver 14.14 Distrib 5.7.20, for osx10.12 (x86_64) using EditLine wrapper
Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
Usage: mysql [OPTIONS] [database]
-?, --help Display this help and exit.
-I, --help Synonym for -?
--bind-address=name IP address to bind to.
-D, --database=name Database to use.
--delimiter=name Delimiter to be used.
--default-character-set=name Set the default character set.
-f, --force Continue even if we get an SQL error.
-p, --password[=name] Password to use when connecting to server.
-h, --host=name Connect to host.
-P, --port=# Port number to use for connection or 0 for default to, in order of preference, my.cnf, $MYSQL_TCP_PORT, /etc/services, built-in default (3306).
--protocol=name The protocol to use for connection (tcp, socket, pipe,
-s, --silent Be more silent. Print results with a tab as separator, each row on new line.
-v, --verbose Write more. (-v -v -v gives the table output format).
-V, --version Output version information and exit.
-w, --wait Wait and retry if connection is down.
What is fun, if we are importing a large database and not having a progress bar. Use Pipe Viewer and see the data transfer through the pipe
For Mac, brew install pv
For Debian/Ubuntu, apt-get install pv
.
For others, refer to pv - Pipe Viewer
pv import.sql | mysql -u root -p password -D database_name
1.45GiB 1:50:07 [339.0KiB/s] [=============> ] 14% ETA 11:09:36
1.46GiB 1:50:14 [ 246KiB/s] [=============> ] 14% ETA 11:09:15
1.47GiB 1:53:00 [ 385KiB/s] [=============> ] 14% ETA 11:05:36
Here's the one I'm using:
#include <stdint.h>
#include <stdlib.h>
static char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/'};
static char *decoding_table = NULL;
static int mod_table[] = {0, 2, 1};
char *base64_encode(const unsigned char *data,
size_t input_length,
size_t *output_length) {
*output_length = 4 * ((input_length + 2) / 3);
char *encoded_data = malloc(*output_length);
if (encoded_data == NULL) return NULL;
for (int i = 0, j = 0; i < input_length;) {
uint32_t octet_a = i < input_length ? (unsigned char)data[i++] : 0;
uint32_t octet_b = i < input_length ? (unsigned char)data[i++] : 0;
uint32_t octet_c = i < input_length ? (unsigned char)data[i++] : 0;
uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F];
}
for (int i = 0; i < mod_table[input_length % 3]; i++)
encoded_data[*output_length - 1 - i] = '=';
return encoded_data;
}
unsigned char *base64_decode(const char *data,
size_t input_length,
size_t *output_length) {
if (decoding_table == NULL) build_decoding_table();
if (input_length % 4 != 0) return NULL;
*output_length = input_length / 4 * 3;
if (data[input_length - 1] == '=') (*output_length)--;
if (data[input_length - 2] == '=') (*output_length)--;
unsigned char *decoded_data = malloc(*output_length);
if (decoded_data == NULL) return NULL;
for (int i = 0, j = 0; i < input_length;) {
uint32_t sextet_a = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t sextet_b = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t sextet_c = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t sextet_d = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t triple = (sextet_a << 3 * 6)
+ (sextet_b << 2 * 6)
+ (sextet_c << 1 * 6)
+ (sextet_d << 0 * 6);
if (j < *output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;
if (j < *output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;
if (j < *output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;
}
return decoded_data;
}
void build_decoding_table() {
decoding_table = malloc(256);
for (int i = 0; i < 64; i++)
decoding_table[(unsigned char) encoding_table[i]] = i;
}
void base64_cleanup() {
free(decoding_table);
}
Keep in mind that this doesn't do any error-checking while decoding - non base 64 encoded data will get processed.
The command is gradle dependencies
, and its output is much improved in Gradle 1.2. (You can already try 1.2-rc-1 today.)
You are getting this error because you are using the resultSet before the resultSet.next() method.
To get the count the just use this:
while (rs.next ()) `{ count = rs.getInt (1); }
You will get your result.
this is how you can create an array of boolean in TS and initialize it with false:
var array: boolean[] = [false, false, false]
or another approach can be:
var array2: Array<boolean> =[false, false, false]
you can specify the type after the colon which in this case is boolean array
I solved it with library PHP_PDO , because my hosting provider didn't accept my requirement for installation of PDO driver to apache server.
The course contains a logical error:
assertTrue("Book check in failed", ml.checkIn(b1));
assertFalse("Book was aleready checked in", ml.checkIn(b1));
In the first assert we expect the checkIn to return True (because checkin is succesful). If this would fail we would print a message like "book check in failed. Now in the second assert we expect the checkIn to fail, because the book was checked in already in the first line. So we expect a checkIn to return a False. If for some reason checkin returns a True (which we don't expect) than the message should never be "Book was already checked in", because the checkin was succesful.
Shift
and right clicking on a file in Windows Explorer gives you an option called Copy as Path
.
This will copy the full path of the file to clipboard. realpath yourfile
to get the full path of a file as suggested by others.I tried using the dtypes=[datetime, ...] option, but
import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4']
dtypes = [datetime, datetime, str, float]
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)
I encountered the following error:
TypeError: data type not understood
The only change I had to make is to replace datetime with datetime.datetime
import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4']
dtypes = [datetime.datetime, datetime.datetime, str, float]
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)
In ASP.NET Core, use PasswordHasher<TUser>
.
• Namespace: Microsoft.AspNetCore.Identity
• Assembly: Microsoft.Extensions.Identity.Core.dll
(NuGet | Source)
To hash a password, use HashPassword()
:
var hashedPassword = new PasswordHasher<object?>().HashPassword(null, password);
To verify a password, use VerifyHashedPassword()
:
var passwordVerificationResult = new PasswordHasher<object?>().VerifyHashedPassword(null, hashedPassword, password);
switch (passwordVerificationResult)
{
case PasswordVerificationResult.Failed:
Console.WriteLine("Password incorrect.");
break;
case PasswordVerificationResult.Success:
Console.WriteLine("Password ok.");
break;
case PasswordVerificationResult.SuccessRehashNeeded:
Console.WriteLine("Password ok but should be rehashed and updated.");
break;
default:
throw new ArgumentOutOfRangeException();
}
Pros:
PasswordHasherOptions
).Cons:
I have python 2.7.3 and this solved my problem:
pip install pysqlite
In my case I have succeed with the following solution for converting field ClockInTime from ClockTime collection from string to Date type:
db.ClockTime.find().forEach(function(doc) {
doc.ClockInTime=new Date(doc.ClockInTime);
db.ClockTime.save(doc);
})
On your local machine, run command:
ssh-keygen -t rsa -C "SomeAlias"
After that command runs, a file ending in *.pub will be generated. Copy the contents of that file.
On the Amazon machine, edit ~/.ssh/authorized_keys and paste the contents of the *.pub file (and remove any existing contents first).
You can then SSH using the other file that was generated from the ssh-keygen command (the private key).
select to_char(sysdate, 'Month') from dual
in your example will be:
select to_char(to_date('15-11-2010', 'DD-MM-YYYY'), 'Month') from dual
try this
$("label").html(your value);
or $("label").text(your value);
If you are using prototype.js then you can do this:
transport_select.observe('change', function(){
toggleSelect(transport_select_id)
})
This eliminate (as hope) the problem in cross-browsers
You can figure out which proxy server you're using by accessing some websites with a browser and then running the DOS command:
netstat
and you'll see some connections in the Foreign Address column on port 80 or 8080 (common proxy server ports). Ideally you will be able to identify the proxy server by its naming convention.
Edited:
I think you are trying to do as done in this DEMO
There are three states of a button: normal, hover and active
You need to use CSS Image Sprites for the button states.
See The Mystery of CSS Sprites
/*CSS*/_x000D_
_x000D_
.imgClass { _x000D_
background-image: url(http://inspectelement.com/wp-content/themes/inspectelementv2/style/images/button.png);_x000D_
background-position: 0px 0px;_x000D_
background-repeat: no-repeat;_x000D_
width: 186px;_x000D_
height: 53px;_x000D_
border: 0px;_x000D_
background-color: none;_x000D_
cursor: pointer;_x000D_
outline: 0;_x000D_
}_x000D_
.imgClass:hover{ _x000D_
background-position: 0px -52px;_x000D_
}_x000D_
_x000D_
.imgClass:active{_x000D_
background-position: 0px -104px;_x000D_
}
_x000D_
<!-- HTML -->_x000D_
<input type="submit" value="" class="imgClass" />
_x000D_
You're missing a FROM and you need to give the subquery an alias.
SELECT COUNT(*) FROM
(
SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
FROM dbo.Table_A AS a
INNER JOIN dbo.Table_B AS b
ON a.a_id = b.a_id
) AS subquery;
And my 15 cent. A one liner for the mac terminal etc just set the MIN= to whatever and a message
MIN=15 && for i in $(seq $(($MIN*60)) -1 1); do echo "$i, "; sleep 1; done; echo -e "\n\nMac Finder should show a popup" afplay /System/Library/Sounds/Funk.aiff; osascript -e 'tell app "Finder" to display dialog "Look away. Rest your eyes"'
A bonus example for inspiration to combine more commands; this will put a mac put to standby sleep upon the message too :) the sudo login is needed then, a multiplication as the 60*2 for two hours goes aswell
sudo su
clear; echo "\n\nPreparing for a sleep when timers done \n"; MIN=60*2 && for i in $(seq $(($MIN*60)) -1 1); do printf "\r%02d:%02d:%02d" $((i/3600)) $(( (i/60)%60)) $((i%60)); sleep 1; done; echo "\n\n Time to sleep zzZZ"; afplay /System/Library/Sounds/Funk.aiff; osascript -e 'tell app "Finder" to display dialog "Time to sleep zzZZ"'; shutdown -h +1 -s
As far as I understand VS has nothing to do with TS installed by NPM. (You may notice after you install TS using NPM, there is no tsc.exe file). VS targets only tsc.exe installed by TS for VS extension, which installes TS to c:\Program Files (x86)\Microsoft SDKs\TypeScript\X.Y. You may have multiple folders under c:\Program Files (x86)\Microsoft SDKs\TypeScript. Set TypeScriptToolsVersion to the highest version installed. In my case I had folders "1.0", "1.7", "1.8", so I set TypeScriptToolsVersion = 1.8, and if you run tsc - v inside that folder you will get 1.8.3 or something, however, when u run tsc outside that folder, it will use PATH variable pointing to TS version installed by NPM, which is in my case 1.8.10. I believe TS for VS will always be a little behind the latest version of TS you install using NPM. But as far as I understand, VS doesnt know anything about TS installed by NPM, it only targets whateve versions installed by TS for VS extensions, and the version specified in TypeScriptToolsVersion in your project file.