CONVERT(VARCHAR(32), HashBytes('MD5', '[email protected]'), 2)
It is possible to use filter predicates to specify which rows to include in the index.
From the documentation:
WHERE <filter_predicate> Creates a filtered index by specifying which rows to include in the index. The filtered index must be a nonclustered index on a table. Creates filtered statistics for the data rows in the filtered index.
Example:
CREATE TABLE Table1 (
NullableCol int NULL
)
CREATE UNIQUE INDEX IX_Table1 ON Table1 (NullableCol) WHERE NullableCol IS NOT NULL;
I found a faster way of embedding:
I see Federico you've found solution by yourself. The problem was in two places. Assignations need proper quoting, in your case
SOME_PATH="/$COMPANY/someProject/some path"
is one of possible solutions.
But in shell those quotes are not stored in a memory, so when you want to use this variable, you need to quote it again, for example:
NEW_VAR="$SOME_PATH"
because if not, space will be expanded to command level, like this:
NEW_VAR=/YourCompany/someProject/some path
which is not what you want.
For more info you can check out my article about it http://www.cofoh.com/white-shell
You're looking for the IN()
clause:
SELECT * FROM `Buses` WHERE `BusID` IN (1,2,3,5,7,9,11,44,88,etc...);
The problem I need to solve is to store contracts containing a few fields (address, book, num_of_days, borrower_addr, blk_data), blk_data is a transaction list (block number and transaction address). This question and answer helped me. I would like to share my code as below. Hope this helps.
- Schema definition. See blk_data.
var ContractSchema = new Schema(
{
address: {type: String, required: true, max: 100}, //contract address
// book_id: {type: String, required: true, max: 100}, //book id in the book collection
book: { type: Schema.ObjectId, ref: 'clc_books', required: true }, // Reference to the associated book.
num_of_days: {type: Number, required: true, min: 1},
borrower_addr: {type: String, required: true, max: 100},
// status: {type: String, enum: ['available', 'Created', 'Locked', 'Inactive'], default:'Created'},
blk_data: [{
tx_addr: {type: String, max: 100}, // to do: change to a list
block_number: {type: String, max: 100}, // to do: change to a list
}]
}
);
- Create a record for the collection in the MongoDB. See blk_data.
// Post submit a smart contract proposal to borrowing a specific book.
exports.ctr_contract_propose_post = [
// Validate fields
body('book_id', 'book_id must not be empty.').isLength({ min: 1 }).trim(),
body('req_addr', 'req_addr must not be empty.').isLength({ min: 1 }).trim(),
body('new_contract_addr', 'contract_addr must not be empty.').isLength({ min: 1 }).trim(),
body('tx_addr', 'tx_addr must not be empty.').isLength({ min: 1 }).trim(),
body('block_number', 'block_number must not be empty.').isLength({ min: 1 }).trim(),
body('num_of_days', 'num_of_days must not be empty.').isLength({ min: 1 }).trim(),
// Sanitize fields.
sanitizeBody('*').escape(),
// Process request after validation and sanitization.
(req, res, next) => {
// Extract the validation errors from a request.
const errors = validationResult(req);
if (!errors.isEmpty()) {
// There are errors. Render form again with sanitized values/error messages.
res.status(400).send({ errors: errors.array() });
return;
}
// Create a Book object with escaped/trimmed data and old id.
var book_fields =
{
_id: req.body.book_id, // This is required, or a new ID will be assigned!
cur_contract: req.body.new_contract_addr,
status: 'await_approval'
};
async.parallel({
//call the function get book model
books: function(callback) {
Book.findByIdAndUpdate(req.body.book_id, book_fields, {}).exec(callback);
},
}, function(error, results) {
if (error) {
res.status(400).send({ errors: errors.array() });
return;
}
if (results.books.isNew) {
// res.render('pg_error', {
// title: 'Proposing a smart contract to borrow the book',
// c: errors.array()
// });
res.status(400).send({ errors: errors.array() });
return;
}
var contract = new Contract(
{
address: req.body.new_contract_addr,
book: req.body.book_id,
num_of_days: req.body.num_of_days,
borrower_addr: req.body.req_addr
});
var blk_data = {
tx_addr: req.body.tx_addr,
block_number: req.body.block_number
};
contract.blk_data.push(blk_data);
// Data from form is valid. Save book.
contract.save(function (err) {
if (err) { return next(err); }
// Successful - redirect to new book record.
resObj = {
"res": contract.url
};
res.status(200).send(JSON.stringify(resObj));
// res.redirect();
});
});
},
];
- Update a record. See blk_data.
// Post lender accept borrow proposal.
exports.ctr_contract_propose_accept_post = [
// Validate fields
body('book_id', 'book_id must not be empty.').isLength({ min: 1 }).trim(),
body('contract_id', 'book_id must not be empty.').isLength({ min: 1 }).trim(),
body('tx_addr', 'tx_addr must not be empty.').isLength({ min: 1 }).trim(),
body('block_number', 'block_number must not be empty.').isLength({ min: 1 }).trim(),
// Sanitize fields.
sanitizeBody('*').escape(),
// Process request after validation and sanitization.
(req, res, next) => {
// Extract the validation errors from a request.
const errors = validationResult(req);
if (!errors.isEmpty()) {
// There are errors. Render form again with sanitized values/error messages.
res.status(400).send({ errors: errors.array() });
return;
}
// Create a Book object with escaped/trimmed data
var book_fields =
{
_id: req.body.book_id, // This is required, or a new ID will be assigned!
status: 'on_loan'
};
// Create a contract object with escaped/trimmed data
var contract_fields = {
$push: {
blk_data: {
tx_addr: req.body.tx_addr,
block_number: req.body.block_number
}
}
};
async.parallel({
//call the function get book model
book: function(callback) {
Book.findByIdAndUpdate(req.body.book_id, book_fields, {}).exec(callback);
},
contract: function(callback) {
Contract.findByIdAndUpdate(req.body.contract_id, contract_fields, {}).exec(callback);
},
}, function(error, results) {
if (error) {
res.status(400).send({ errors: errors.array() });
return;
}
if ((results.book.isNew) || (results.contract.isNew)) {
res.status(400).send({ errors: errors.array() });
return;
}
var resObj = {
"res": results.contract.url
};
res.status(200).send(JSON.stringify(resObj));
});
},
];
Vlad's code is overquoted. Should be:
MY_PATH=`dirname "$0"`
MY_PATH=`( cd "$MY_PATH" && pwd )`
it happens to me when I wrote
gem install cocoapods
instead of
sudo gem install cocoapods
if sudo command is not found also, write
export PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:$PATH
before sudo command
To deal with situations where there are a possibility of multiple values (v in your example), I use PIVOT
and LISTAGG
:
SELECT * FROM
(
SELECT id, k, v
FROM _kv
)
PIVOT
(
LISTAGG(v ,',')
WITHIN GROUP (ORDER BY k)
FOR k IN ('name', 'age','gender','status')
)
ORDER BY id;
Since you want dynamic values, use dynamic SQL and pass in the values determined by running a select on the table data before calling the pivot statement.
Please try the below lines in order to get the current date.
import datetime
now = datetime.datetime.now()
print (now.strftime("%Y-%m-%d %H:%M:%S"))
Output:
2020-02-26 21:15:32
Refer : https://beginnersbug.com/how-to-get-the-current-date-in-pyspark-with-example/
I just wrote a directive to handle this, so you can simply add the attribute bs-active-link
to the parent <ul>
element, and any time the route changed, it will find the matching link, and add the active
class to the corresponding <li>
.
You can see it in action here: http://jsfiddle.net/8mcedv3b/
Example HTML:
<ul class="nav navbar-nav" bs-active-link>
<li><a href="/home">Home</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
Javascript:
angular.module('appName')
.directive('bsActiveLink', ['$location', function ($location) {
return {
restrict: 'A', //use as attribute
replace: false,
link: function (scope, elem) {
//after the route has changed
scope.$on("$routeChangeSuccess", function () {
var hrefs = ['/#' + $location.path(),
'#' + $location.path(), //html5: false
$location.path()]; //html5: true
angular.forEach(elem.find('a'), function (a) {
a = angular.element(a);
if (-1 !== hrefs.indexOf(a.attr('href'))) {
a.parent().addClass('active');
} else {
a.parent().removeClass('active');
};
});
});
}
}
}]);
You were correct to use WaitForSeconds. But I suspect that you tried using it without coroutines. That's how it should work:
public void SomeMethod()
{
StartCoroutine(SomeCoroutine());
}
private IEnumerator SomeCoroutine()
{
TextUI.text = "Welcome to Number Wizard!";
yield return new WaitForSeconds (3);
TextUI.text = ("The highest number you can pick is " + max);
yield return new WaitForSeconds (3);
TextUI.text = ("The lowest number you can pick is " + min);
}
I was getting this on Angular 2 rc1. Turns out some names changed with typings v1 vs the old 0.x. The browser.d.ts
files became index.d.ts
.
After running typings install
locate your startup file (where you bootstrap) and add:
/// <reference path="../typings/index.d.ts" />
(or without the ../
if your startup file is in the same folder as the typings folder)
Adding index.d.ts
to the files list in tsconfig.json
did not work for some reason.
Also, the es6-shim
package was not needed.
I recently had to do this and had to sift through all these answers and their comments to eventually piece the information together, so I'll put it all here, in one post, for your convenience:
Step 1: ssh keys
Create any keypairs you'll need. In this example I've named me default/original 'id_rsa' (which is the default) and my new one 'id_rsa-work':
ssh-keygen -t rsa -C "[email protected]"
Step 2: ssh config
Set up multiple ssh profiles by creating/modifying ~/.ssh/config. Note the slightly differing 'Host' values:
# Default GitHub
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa
# Work GitHub
Host work.github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_work
Step 3: ssh-add
You may or may not have to do this. To check, list identity fingerprints by running:
$ ssh-add -l
2048 1f:1a:b8:69:cd:e3:ee:68:e1:c4:da:d8:96:7c:d0:6f stefano (RSA)
2048 6d:65:b9:3b:ff:9c:5a:54:1c:2f:6a:f7:44:03:84:3f [email protected] (RSA)
If your entries aren't there then run:
ssh-add ~/.ssh/id_rsa_work
Step 4: test
To test you've done this all correctly, I suggest the following quick check:
$ ssh -T [email protected]
Hi stefano! You've successfully authenticated, but GitHub does not provide shell access.
$ ssh -T [email protected]
Hi stefano! You've successfully authenticated, but GitHub does not provide shell access.
Note that you'll have to change the hostname (github / work.github) depending on what key/identity you'd like to use. But now you should be good to go! :)
×
stands for ×
in html.
Use &times
to get ×
I think the easiest way is to add another div, in the same place as the iframe, then
make its z-index
bigger than the iframe container, so you can easly just style your own div. If you need to click on it, just use pointer-events:none
on your own div, so the iframe would be working in case you need to click on it ;)
I hope It will help someone ;)
A more simplified approach based on the accepted answer:
static public string Beautify(this XmlDocument doc) {
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true
};
using (XmlWriter writer = XmlWriter.Create(sb, settings)) {
doc.Save(writer);
}
return sb.ToString();
}
Setting the new line is not necessary. Indent characters also has the default two spaces so I preferred not to set it as well.
There are several ways to add files to an existing Java project in Eclipse. So lets assume you have already created the Java project in Eclipse (e.g. using File
-> New
-> Project...
- and select Java project
).
To get Java files into the new project you can do any of the following. Note that there are other ways as well. The sequence is my preference.
Navigator
view directly from the native file manager. You must create any needed Java packages first. This method is best for a few files in an existing Java package.File
-> Import...
- select File System
. Here you can then select exactly which files to import into the new project and in which Java package to put them. This is extremely handy if you want to import many files or there are multiple Java packages.File
-> Refresh
to refresh the Eclipse view of the native system. Remember to select the new project before the refresh.The last one is what you did - minus the refresh...
Try the following code:
function getStackTrace(){
var f = arguments.callee;
var ret = [];
var item = {};
var iter = 0;
while ( f = f.caller ){
// Initialize
item = {
name: f.name || null,
args: [], // Empty array = no arguments passed
callback: f
};
// Function arguments
if ( f.arguments ){
for ( iter = 0; iter<f.arguments.length; iter++ ){
item.args[iter] = f.arguments[iter];
}
} else {
item.args = null; // null = argument listing not supported
}
ret.push( item );
}
return ret;
}
Worked for me in Firefox-21 and Chromium-25.
The new way of doing it with php7.4 is Spread operator [...]
$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
var_dump($fruits);
Spread operator should have better performance than array_merge
A significant advantage of Spread operator is that it supports any traversable objects, while the array_merge function only supports arrays.
Ok, I know that it's an old issue but I post my answer anyway.
I like this solution. I only have to specify the identity column(s).
SELECT * INTO TempTable FROM MyTable_T WHERE id = 1;
ALTER TABLE TempTable DROP COLUMN id;
INSERT INTO MyTable_T SELECT * FROM TempTable;
DROP TABLE TempTable;
The "id"-column is the identity column and that's the only column I have to specify. It's better than the other way around anyway. :-)
I use SQL Server. You may want to use "CREATE TABLE
" and "UPDATE TABLE
" at row 1 and 2.
Hmm, I saw that I did not really give the answer that he wanted. He wanted to copy the id to another column also. But this solution is nice for making a copy with a new auto-id.
I edit my solution with the idéas from Michael Dibbets.
use MyDatabase;
SELECT * INTO #TempTable FROM [MyTable] WHERE [IndexField] = :id;
ALTER TABLE #TempTable DROP COLUMN [IndexField];
INSERT INTO [MyTable] SELECT * FROM #TempTable;
DROP TABLE #TempTable;
You can drop more than one column by separating them with a ",". The :id should be replaced with the id of the row you want to copy. MyDatabase, MyTable and IndexField should be replaced with your names (of course).
If a user from Safari Web browser (Apple devices) visit your site. The browser tries to fetch the site icon if it is not defined in <head>
in the following order:
To resolve this issue either define an icon for safari web browsers or apple devices. Add something like this to head section of your site:
<link rel="apple-touch-icon" href="/custom_icon.png"/>
If you want to keep <head>
clean then upload the icon to root dir of your site with proper name.
The default icon size is 57px.
You can find more details on iOS developer library.
If you only want to commit all the changes in one commit as if you typed yourself, --squash will do too
$ git merge --squash v1.0
$ git commit
You could use :
int a = 12;
if (a>0 || a<0){
cout << "Your text"<<endl;
}
I'm pretty sure it works.
I have a similar problem (at least I think it is similar). In one of the replies here the solution is as follows:
select
A.*
from
table_A A
inner join table_B B
on A.id = B.id
where
B.tag = 'chair'
That WHERE clause I would like to be:
WHERE B.tag = A.<col_name>
or, in my specific case:
WHERE B.val BETWEEN A.val1 AND A.val2
More detailed:
Table A carries status information of a fleet of equipment. Each status record carries with it a start and stop time of that status. Table B carries regularly recorded, timestamped data about the equipment, which I want to extract for the duration of the period indicated in table A.
So everyone agree on how this should be done, but since no one want to give a complete solution, here goes:
int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText("text to clip");
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("text label","text to clip");
clipboard.setPrimaryClip(clip);
}
I assume you have something like following declared in manifest:
<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="14" />
Adding the environment variable for nodejs path will solve this problem https://codetolive.in/development/npm-is-not-recognized-as-internal-or-external-command-operable-program-or-batch-file/
You can also use a while loop:
while (true) {
//your code
}
It depends what is a use of those tables, but you might consider putting trigger on original table on insert and update. When insert or update is done, update the second table based on only one item from the original table. It will be quicker.
width, height = map(int, input().split())
def rectanglePerimeter(width, height):
return ((width + height)*2)
print(rectanglePerimeter(width, height))
Running it like this produces:
% echo "1 2" | test.py
6
I suspect IDLE is simply passing a single string to your script. The first input()
is slurping the entire string. Notice what happens if you put some print statements in after the calls to input()
:
width = input()
print(width)
height = input()
print(height)
Running echo "1 2" | test.py
produces
1 2
Traceback (most recent call last):
File "/home/unutbu/pybin/test.py", line 5, in <module>
height = input()
EOFError: EOF when reading a line
Notice the first print statement prints the entire string '1 2'
. The second call to input()
raises the EOFError
(end-of-file error).
So a simple pipe such as the one I used only allows you to pass one string. Thus you can only call input()
once. You must then process this string, split it on whitespace, and convert the string fragments to ints yourself. That is what
width, height = map(int, input().split())
does.
Note, there are other ways to pass input to your program. If you had run test.py
in a terminal, then you could have typed 1
and 2
separately with no problem. Or, you could have written a program with pexpect to simulate a terminal, passing 1
and 2
programmatically. Or, you could use argparse to pass arguments on the command line, allowing you to call your program with
test.py 1 2
If you do a straight git pull
then you will either be 'fast-forwarded' or merge an unknown number of commits from the remote repository. This happens as one action though, so the last commit that you were at immediately before the pull will be the last entry in the reflog and can be accessed as HEAD@{1}
. This means that you can do:
git diff HEAD@{1}
However, I would strongly recommend that if this is something you find yourself doing a lot then you should consider just doing a git fetch
and examining the fetched branch before manually merging or rebasing onto it. E.g. if you're on master and were going to pull in origin/master:
git fetch
git log HEAD..origin/master
# looks good, lets merge
git merge origin/master
I just went through all 4 pages of this so far, and I was rather surprised that I didn't see this way to shorten a check for InvokeRequired
:
using System;
using System.Windows.Forms;
/// <summary>
/// Extension methods acting on Control objects.
/// </summary>
internal static class ControlExtensionMethods
{
/// <summary>
/// Invokes the given action on the given control's UI thread, if invocation is needed.
/// </summary>
/// <param name="control">Control on whose UI thread to possibly invoke.</param>
/// <param name="action">Action to be invoked on the given control.</param>
public static void MaybeInvoke(this Control control, Action action)
{
if (control != null && control.InvokeRequired)
{
control.Invoke(action);
}
else
{
action();
}
}
/// <summary>
/// Maybe Invoke a Func that returns a value.
/// </summary>
/// <typeparam name="T">Return type of func.</typeparam>
/// <param name="control">Control on which to maybe invoke.</param>
/// <param name="func">Function returning a value, to invoke.</param>
/// <returns>The result of the call to func.</returns>
public static T MaybeInvoke<T>(this Control control, Func<T> func)
{
if (control != null && control.InvokeRequired)
{
return (T)(control.Invoke(func));
}
else
{
return func();
}
}
}
Usage:
myForm.MaybeInvoke(() => this.Text = "Hello world");
// Sometimes the control might be null, but that's okay.
var dialogResult = this.Parent.MaybeInvoke(() => MessageBox.Show(this, "Yes or no?", "Choice", MessageBoxButtons.YesNo));
Recently i had the same problem (Compiling OpenCV with CMake and Qt/MinGW on WIN764)
And I think I solve this including on my environment variable PATH (through Control Panel\All Control Panel Items\System\Advanced Sytem Settings
) with the %MINGW_DIR%\bin and %CMAKE_DIR%/bin
Furthermore, I installed cmake2.8 on an easy directory (without blanks on it)
on Windows insert:
set http_proxy=<proxy>
set https_proxy=<proxy>
before
php "%~dp0composer.phar" %*
or on Linux insert:
export http_proxy=<proxy>
export https_proxy=<proxy>
before
php "${dir}/composer.phar" "$@"
You can do it without modifying the XML stream: Tell the XmlReader to not be so picky.
Setting the XmlReaderSettings.ConformanceLevel
to ConformanceLevel.Fragment
will let the parser ignore the fact that there is no root node.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
using (XmlReader reader = XmlReader.Create(tr,settings))
{
...
}
Now you can parse something like this (which is an real time XML stream, where it is impossible to wrap with a node).
<event>
<timeStamp>1354902435238</timeStamp>
<eventId>7073822</eventId>
</event>
<data>
<time>1354902435341</time>
<payload type='80'>7d1300786a0000000bf9458b0518000000000000000000000000000000000c0c030306001b</payload>
</data>
<data>
<time>1354902435345</time>
<payload type='80'>fd1260780912ff3028fea5ffc0387d640fa550f40fbdf7afffe001fff8200fff00f0bf0e000042201421100224ff40312300111400004f000000e0c0fbd1e0000f10e0fccc2ff0000f0fe00f00f0eed00f11e10d010021420401</payload>
</data>
<data>
<time>1354902435347</time>
<payload type='80'>fd126078ad11fc4015fefdf5b042ff1010223500000000000000003007ff00f20e0f01000e0000dc0f01000f000000000000004f000000f104ff001000210f000013010000c6da000000680ffa807800200000000d00c0f0</payload>
</data>
For rooted users :whats app store all message and contacts in msgstore.db and wa.db files in plain text.These files are available in /data/data/com.whatsapp/databases/. you can open these files using any sqlite browser like SQLite Database Browser.
If I have open a package in BIDS ("Business Intelligence Development Studio", the tool you use to design the packages), and do not select any item in it, I have a "Properties" pane in the bottom right containing - among others, the MaximumErrorCount
property. If you do not see it, maybe it is minimized and you have to open it (have a look at tabs in the right).
If you cannot find it this way, try the menu: View/Properties Window.
Or try the F4 key.
Wrap the i tag in p or span, then you can use bootstrap css class
<p class="text-success"><i class="fa fa-check"></i></p>
Easy approach:
CREATE TABLE T
(
C [nvarchar](100) NOT NULL UNIQUE,
);
SET XACT_ABORT ON -- Turns on rollback if T-SQL statement raises a run-time error.
SELECT * FROM T; -- Check before.
BEGIN TRAN
INSERT INTO T VALUES ('A');
INSERT INTO T VALUES ('B');
INSERT INTO T VALUES ('B');
INSERT INTO T VALUES ('C');
COMMIT TRAN
SELECT * FROM T; -- Check after.
DELETE T;
So there are advantages and disadvantages to each event. The events onkeypress
and onkeydown
don't retrieve the latest value, and onkeypress
doesn't fire for non-printable characters in some browsers. The onkeyup
event doesn't detect when a key is held down for multiple characters.
This is a little hacky, but doing something like
function edValueKeyDown(input) {
var s = input.value;
var lblValue = document.getElementById("lblValue");
lblValue.innerText = "The text box contains: "+s;
//var s = $("#edValue").val();
//$("#lblValue").text(s);
}
<input id="edValue" type="text" onkeydown="setTimeout(edValueKeyDown, 0, this)" />
seems to handle the best of all worlds.
I put this forward to help anyone needing something readily practical for giving you a nice, prettified (indented) picture of a JS Node
. None of the other solutions worked for me for a Node
("cyclical error" or whatever...). This walks you through the tree under the DOM Node
(without using recursion) and gives you the depth, tagName
(if applicable) and textContent
(if applicable).
Any other details from the nodes you encounter as you walk the tree under the head node can be added as per your interest...
function printRNode( node ){
// make sort of human-readable picture of the node... a bit like PHP print_r
if( node === undefined || node === null ){
throwError( 'node was ' + typeof node );
}
let s = '';
// NB walkDOM could be made into a utility function which you could
// call with one or more callback functions as parameters...
function walkDOM( headNode ){
const stack = [ headNode ];
const depthCountDowns = [ 1 ];
while (stack.length > 0) {
const node = stack.pop();
const depth = depthCountDowns.length - 1;
// TODO non-text, non-BR nodes could show more details (attributes, properties, etc.)
const stringRep = node.nodeType === 3? 'TEXT: |' + node.nodeValue + '|' : 'tag: ' + node.tagName;
s += ' '.repeat( depth ) + stringRep + '\n';
const lastIndex = depthCountDowns.length - 1;
depthCountDowns[ lastIndex ] = depthCountDowns[ lastIndex ] - 1;
if( node.childNodes.length ){
depthCountDowns.push( node.childNodes.length );
stack.push( ... Array.from( node.childNodes ).reverse() );
}
while( depthCountDowns[ depthCountDowns.length - 1 ] === 0 ){
depthCountDowns.splice( -1 );
}
}
}
walkDOM( node );
return s;
}
I too got the same error, problem in my case is I included the column name in GROUP BY
clause and it caused this error. So removed the column from GROUP BY
clause and it worked!!!
You could fill the C Column with variations on the following formula:
=IF(ISERROR(MATCH(A1,$B:$B,0)),"",A1)
Then C would only contain values that were in A and C.
"^" For the begining of the line "$" for the end of it. Eg.:
var re = /^abc$/;
Would match "abc" but not "1abc" or "abc1". You can learn more at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
One approach is to add a pure virtual GetNodeType() method to NodeDTO and override it in the descendants so that each descendant returns actual type.
Heres the code that creates a Dialog which allows the user of your application to change the Look And Feel based on the user's systems. Alternatively, if you can store the wanted Look And Feel's on your application, then they could be "portable", which is the desired result.
public void changeLookAndFeel() {
List<String> lookAndFeelsDisplay = new ArrayList<>();
List<String> lookAndFeelsRealNames = new ArrayList<>();
for (LookAndFeelInfo each : UIManager.getInstalledLookAndFeels()) {
lookAndFeelsDisplay.add(each.getName());
lookAndFeelsRealNames.add(each.getClassName());
}
String changeLook = (String) JOptionPane.showInputDialog(this, "Choose Look and Feel Here:", "Select Look and Feel", JOptionPane.QUESTION_MESSAGE, null, lookAndFeelsDisplay.toArray(), null);
if (changeLook != null) {
for (int i = 0; i < lookAndFeelsDisplay.size(); i++) {
if (changeLook.equals(lookAndFeelsDisplay.get(i))) {
try {
UIManager.setLookAndFeel(lookAndFeelsRealNames.get(i));
break;
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
err.println(ex);
ex.printStackTrace(System.err);
}
}
}
}
}
In WPF, you use a DispatcherTimer
.
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0,5,0);
dispatcherTimer.Start();
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
// code goes here
}
I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above
public Form1()
{
InitializeComponent();
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted; //Tell the user how the process went
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled
}
//Start Process
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
//Cancel Process
private void button2_Click(object sender, EventArgs e)
{
//Check if background worker is doing anything and send a cancellation if it is
if (backgroundWorker1.IsBusy)
{
backgroundWorker1.CancelAsync();
}
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(1000);
backgroundWorker1.ReportProgress(i);
//Check if there is a request to cancel the process
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
backgroundWorker1.ReportProgress(0);
return;
}
}
//If the process exits the loop, ensure that progress is set to 100%
//Remember in the loop we set i < 100 so in theory the process will complete at 99%
backgroundWorker1.ReportProgress(100);
}
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
lblStatus.Text = "Process was cancelled";
}
else if (e.Error != null)
{
lblStatus.Text = "There was an error running the process. The thread aborted";
}
else
{
lblStatus.Text = "Process was completed";
}
}
I have added one answer, which was not supporting enumeration values, now added support which supports enumeration value assignment as well. Like in previous solution this one uses minimum define magic.
Here is header file:
#pragma once
#include <string>
#include <map>
#include <regex>
template <class Enum>
class EnumReflect
{
public:
static const char* getEnums() { return ""; }
};
//
// Just a container for each enumeration type.
//
template <class Enum>
class EnumReflectBase
{
public:
static std::map<std::string, int> enum2int;
static std::map<int, std::string> int2enum;
static void EnsureEnumMapReady( const char* enumsInfo )
{
if (*enumsInfo == 0 || enum2int.size() != 0 )
return;
// Should be called once per each enumeration.
std::string senumsInfo(enumsInfo);
std::regex re("^([a-zA-Z_][a-zA-Z0-9_]+) *=? *([^,]*)(,|$) *"); // C++ identifier to optional " = <value>"
std::smatch sm;
int value = 0;
for (; regex_search(senumsInfo, sm, re); senumsInfo = sm.suffix(), value++)
{
string enumName = sm[1].str();
string enumValue = sm[2].str();
if (enumValue.length() != 0)
value = atoi(enumValue.c_str());
enum2int[enumName] = value;
int2enum[value] = enumName;
}
}
};
template <class Enum>
std::map<std::string, int> EnumReflectBase<Enum>::enum2int;
template <class Enum>
std::map<int, std::string> EnumReflectBase<Enum>::int2enum;
#define DECLARE_ENUM(name, ...) \
enum name { __VA_ARGS__ }; \
template <> \
class EnumReflect<##name>: public EnumReflectBase<##name> { \
public: \
static const char* getEnums() { return #__VA_ARGS__; } \
};
/*
Basic usage:
Declare enumeration:
DECLARE_ENUM( enumName,
enumValue1,
enumValue2,
enumValue3 = 5,
// comment
enumValue4
);
Conversion logic:
From enumeration to string:
printf( EnumToString(enumValue3).c_str() );
From string to enumeration:
enumName value;
if( !StringToEnum("enumValue4", value) )
printf("Conversion failed...");
*/
//
// Converts enumeration to string, if not found - empty string is returned.
//
template <class T>
std::string EnumToString(T t)
{
EnumReflect<T>::EnsureEnumMapReady(EnumReflect<T>::getEnums());
auto& int2enum = EnumReflect<T>::int2enum;
auto it = int2enum.find(t);
if (it == int2enum.end())
return "";
return it->second;
}
//
// Converts string to enumeration, if not found - false is returned.
//
template <class T>
bool StringToEnum(const char* enumName, T& t)
{
EnumReflect<T>::EnsureEnumMapReady(EnumReflect<T>::getEnums());
auto& enum2int = EnumReflect<T>::enum2int;
auto it = enum2int.find(enumName);
if (it == enum2int.end())
return false;
t = (T) it->second;
return true;
}
And here is example test application:
DECLARE_ENUM(TestEnum,
ValueOne,
ValueTwo,
ValueThree = 5,
ValueFour = 7
);
DECLARE_ENUM(TestEnum2,
ValueOne2 = -1,
ValueTwo2,
ValueThree2 = -4,
ValueFour2
);
void main(void)
{
string sName1 = EnumToString(ValueOne);
string sName2 = EnumToString(ValueTwo);
string sName3 = EnumToString(ValueThree);
string sName4 = EnumToString(ValueFour);
TestEnum t1, t2, t3, t4, t5 = ValueOne;
bool b1 = StringToEnum(sName1.c_str(), t1);
bool b2 = StringToEnum(sName2.c_str(), t2);
bool b3 = StringToEnum(sName3.c_str(), t3);
bool b4 = StringToEnum(sName4.c_str(), t4);
bool b5 = StringToEnum("Unknown", t5);
string sName2_1 = EnumToString(ValueOne2);
string sName2_2 = EnumToString(ValueTwo2);
string sName2_3 = EnumToString(ValueThree2);
string sName2_4 = EnumToString(ValueFour2);
TestEnum2 t2_1, t2_2, t2_3, t2_4, t2_5 = ValueOne2;
bool b2_1 = StringToEnum(sName2_1.c_str(), t2_1);
bool b2_2 = StringToEnum(sName2_2.c_str(), t2_2);
bool b2_3 = StringToEnum(sName2_3.c_str(), t2_3);
bool b2_4 = StringToEnum(sName2_4.c_str(), t2_4);
bool b2_5 = StringToEnum("Unknown", t2_5);
Updated version of same header file will be kept here:
https://github.com/tapika/cppreflect/blob/master/cppreflect/enumreflect.h
AFAIK Android doesn't support vCard files out of the Box at least not until 2.2.
You could use the app vCardIO to read vcf files from your SD card and save to you contacts. So you have to save them on your SD card in the first place and import them afterwards.
vCardIO is also available trough the market.
The fundamental problem can often be simply solved by changing an =
to IN
, in cases where you've got a one-to-many relationship. For example, if you wanted to update or delete a bunch of accounts for a given customer:
WITH accounts_to_delete AS
(
SELECT account_id
FROM accounts a
INNER JOIN customers c
ON a.customer_id = c.id
WHERE c.customer_name='Some Customer'
)
-- this fails if "Some Customer" has multiple accounts, but works if there's 1:
DELETE FROM accounts
WHERE accounts.guid =
(
SELECT account_id
FROM accounts_to_delete
);
-- this succeeds with any number of accounts:
DELETE FROM accounts
WHERE accounts.guid IN
(
SELECT account_id
FROM accounts_to_delete
);
Shuffling is the process by which intermediate data from mappers are transferred to 0,1 or more reducers. Each reducer receives 1 or more keys and its associated values depending on the number of reducers (for a balanced load). Further the values associated with each key are locally sorted.
According to git push
documentation:
git push origin HEAD
A handy way to push the current branch to the same name on the remote.
So I think what you need is git push origin HEAD
. Also it can be useful git push -u origin HEAD
to set upstream tracking information in the local branch, if you haven't already pushed to the origin.
UPDATED
I've updated your demo: http://jsfiddle.net/terryyounghk/QS56z/18/
Also, I've changed two ^=
to *=
. See http://api.jquery.com/category/selectors/
And note the :checked
selector. See http://api.jquery.com/checked-selector/
function createcodes() {
//run through each row
$('.authors-list tr').each(function (i, row) {
// reference all the stuff you need first
var $row = $(row),
$family = $row.find('input[name*="family"]'),
$grade = $row.find('input[name*="grade"]'),
$checkedBoxes = $row.find('input:checked');
$checkedBoxes.each(function (i, checkbox) {
// assuming you layout the elements this way,
// we'll take advantage of .next()
var $checkbox = $(checkbox),
$line = $checkbox.next(),
$size = $line.next();
$line.val(
$family.val() + ' ' + $size.val() + ', ' + $grade.val()
);
});
});
}
One way to solve this problem, specialization of member functions is to put the specialization into another class, then inherit from that class. You may have to change the order of inheritence to get access to all of the other underlying data but this technique does work.
template< class T, bool condition> struct FooImpl;
template<class T> struct FooImpl<T, true> {
T foo() { return 10; }
};
template<class T> struct FoolImpl<T,false> {
T foo() { return 5; }
};
template< class T >
class Y : public FooImpl<T, boost::is_integer<T> > // whatever your test is goes here.
{
public:
typedef FooImpl<T, boost::is_integer<T> > inherited;
// you will need to use "inherited::" if you want to name any of the
// members of those inherited classes.
};
The disadvantage of this technique is that if you need to test a lot of different things for different member functions you'll have to make a class for each one, and chain it in the inheritence tree. This is true for accessing common data members.
Ex:
template<class T, bool condition> class Goo;
// repeat pattern above.
template<class T, bool condition>
class Foo<T, true> : public Goo<T, boost::test<T> > {
public:
typedef Goo<T, boost::test<T> > inherited:
// etc. etc.
};
Just for fun, a pure math answer using divmod. Pretty inneficient because of the multiplication, could do just as well a simple check on the number of month (if equal to 12, increase year, etc)
year = today.year
month = today.month
nm = list(divmod(year * 12 + month + 1, 12))
if nm[1] == 0:
nm[1] = 12
nm[0] -= 1
pm = list(divmod(year * 12 + month - 1, 12))
if pm[1] == 0:
pm[1] = 12
pm[0] -= 1
next_month = nm
previous_month = pm
To increase performance for further tree manipulation is good to transform tree view into line collection view, like [obj1, obj2, obj3]. You can store parent-child object relations to easy navigate to parent/child scope.
Searching element inside collection is more efficient then find element inside tree (recursion, addition dynamic function creation, closure).
That's right. 'list index out of range' most likely means you are referring to n-th
element of the list, while the length of the list is smaller than n
.
On Windows, type cd
for the working current path.
On Linux, pwd
for the current working path.
Did you try using clientVia to see the message sent, using SOAP toolkit or something like that? This could help to see if the error is coming from the client itself or from somewhere else.
You have to check which version of Excel you are targeting?
If you are targeting Excel 2010 use version 14 (as per Grant's screenshot answer), Excel 2007 use version 12 . You can not support Excel 2003 using vS2012 as they do not have the correct Interop dll installed.
Add a <version>
element after the <plugin>
<artifactId>
in your pom.xml
file. Find the following text:
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
Add the version tag to it:
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
The warning should be resolved.
Regarding this:
'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing
Many people have mentioned why the issue is happening, but fail to suggest a fix. All I needed to do was to go into my POM file for my project, and add the <version>
tag as shown above.
To discover the version number, one way is to look in Maven's output after it finishes running. Where you are missing version numbers, Maven will display its default version:
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ entities ---
Take that version number (as in the 2.3.2
above) and add it to your POM, as shown.
You can simply traverse the array in three nested loops and write their values to your file. For reading, you simply use the same exact loop construction. You will get the values in exactly the right order to fill your arrays correctly again.
Hmm. By default, <label>
is display: inline;
and <input>
is (roughly, at least) display: inline-block;
, so they should both be on the same line. See http://jsfiddle.net/BJU4f/
Perhaps a stylesheet is setting label
or input
to display: block
?
Think of TCP as a dedicated scheduled UPS/FedEx pickup/dropoff of packages between two locations, while UDP is the equivalent of throwing a postcard in a mailbox.
UPS/FedEx will do their damndest to make sure that the package you mail off gets there, and get it there on time. With the post card, you're lucky if it arrives at all, and it may arrive out of order or late (how many times have you gotten a postcard from someone AFTER they've gotten home from the vacation?)
TCP is as close to a guaranteed delivery protocol as you can get, while UDP is just "best effort".
You could also create the input button in this way:
var button = '<input type="button" id="questionButton" value='+variable+'> <br />';
It might be the syntax of the Button creation that is off somehow.
The single ampersand & is the logical AND operator. The double ampersand && is again a logical AND operator that employs short-circuiting behaviour. Short-circuiting just means the second operand (right hand side) is evaluated only when the result is not fully determined by the first operand (left hand side)
A & B (A and B are evaluated)
A && B (B is only evaluated if A is true)
Not knowing your code, it's a bit hard to answer your question, but based on all the info here, I believe the issue is you're trying to use Collections.sort passing in an object defined as Collection, and sort doesn't support that.
First question. Why is client defined so generically? Why isn't it a List, Map, Set or something a little more specific?
If client was defined as a List, Map or Set, you wouldn't have this issue, as then you'd be able to directly use Collections.sort(client).
HTH
First of all you need to remove the data-toggle attribute. We will use some JQuery, so make sure you include it.
<ul class='nav nav-tabs'>
<li class='active'><a href='#home'>Home</a></li>
<li><a href='#menu1'>Menu 1</a></li>
<li><a href='#menu2'>Menu 2</a></li>
<li><a href='#menu3'>Menu 3</a></li>
</ul>
<div class='tab-content'>
<div id='home' class='tab-pane fade in active'>
<h3>HOME</h3>
<div id='menu1' class='tab-pane fade'>
<h3>Menu 1</h3>
</div>
<div id='menu2' class='tab-pane fade'>
<h3>Menu 2</h3>
</div>
<div id='menu3' class='tab-pane fade'>
<h3>Menu 3</h3>
</div>
</div>
</div>
<script>
$(document).ready(function(){
// Handling data-toggle manually
$('.nav-tabs a').click(function(){
$(this).tab('show');
});
// The on tab shown event
$('.nav-tabs a').on('shown.bs.tab', function (e) {
alert('Hello from the other siiiiiide!');
var current_tab = e.target;
var previous_tab = e.relatedTarget;
});
});
</script>
In SQL Server 2008 you can use Change Data Capture for this. Details of how to set it up on a table are here http://msdn.microsoft.com/en-us/library/cc627369.aspx
This post shows a couple of ways of controlling the session timeout: http://bytes.com/topic/php/insights/889606-setting-timeout-php-sessions
IMHO the second option is a nice solution:
<?php
/***
* Starts a session with a specific timeout and a specific GC probability.
* @param int $timeout The number of seconds until it should time out.
* @param int $probability The probablity, in int percentage, that the garbage
* collection routine will be triggered right now.
* @param strint $cookie_domain The domain path for the cookie.
*/
function session_start_timeout($timeout=5, $probability=100, $cookie_domain='/') {
// Set the max lifetime
ini_set("session.gc_maxlifetime", $timeout);
// Set the session cookie to timout
ini_set("session.cookie_lifetime", $timeout);
// Change the save path. Sessions stored in teh same path
// all share the same lifetime; the lowest lifetime will be
// used for all. Therefore, for this to work, the session
// must be stored in a directory where only sessions sharing
// it's lifetime are. Best to just dynamically create on.
$seperator = strstr(strtoupper(substr(PHP_OS, 0, 3)), "WIN") ? "\\" : "/";
$path = ini_get("session.save_path") . $seperator . "session_" . $timeout . "sec";
if(!file_exists($path)) {
if(!mkdir($path, 600)) {
trigger_error("Failed to create session save path directory '$path'. Check permissions.", E_USER_ERROR);
}
}
ini_set("session.save_path", $path);
// Set the chance to trigger the garbage collection.
ini_set("session.gc_probability", $probability);
ini_set("session.gc_divisor", 100); // Should always be 100
// Start the session!
session_start();
// Renew the time left until this session times out.
// If you skip this, the session will time out based
// on the time when it was created, rather than when
// it was last used.
if(isset($_COOKIE[session_name()])) {
setcookie(session_name(), $_COOKIE[session_name()], time() + $timeout, $cookie_domain);
}
}
Look at these lines:
If yes_ans > no_ans and yes_ans > na_ans
and similar. To what do "yes_ans" etc. refer? You're not using these in the context of a query; the "if exists" condition doesn't extend to the column names you're using inside.
Consider assigning those values to variables you can then use for your conditional flow below. Thus,
if exists (some record)
begin
set @var = column, @var2 = column2, ...
if (@var1 > @var2)
-- do something
end
The return type is also mismatched with the declaration. It would help a lot if you indented, used ANSI-standard punctuation (terminate statements with semicolons), and left out superfluous begin/end - you don't need these for single-statement lines executed as the result of a test.
Implementation 1 returns the magnitude of the vector that would result from a regular 3D cross product of the input vectors, taking their Z values implicitly as 0 (i.e. treating the 2D space as a plane in the 3D space). The 3D cross product will be perpendicular to that plane, and thus have 0 X & Y components (thus the scalar returned is the Z value of the 3D cross product vector).
Note that the magnitude of the vector resulting from 3D cross product is also equal to the area of the parallelogram between the two vectors, which gives Implementation 1 another purpose. In addition, this area is signed and can be used to determine whether rotating from V1 to V2 moves in an counter clockwise or clockwise direction. It should also be noted that implementation 1 is the determinant of the 2x2 matrix built from these two vectors.
Implementation 2 returns a vector perpendicular to the input vector still in the same 2D plane. Not a cross product in the classical sense but consistent in the "give me a perpendicular vector" sense.
Note that 3D euclidean space is closed under the cross product operation--that is, a cross product of two 3D vectors returns another 3D vector. Both of the above 2D implementations are inconsistent with that in one way or another.
Hope this helps...
You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.
Usually, one should put a transaction at the service layer.
But as stated before, the atomicity of an operation is what tells us where an annotation is necessary. Thus, if you use frameworks like Hibernate, where a single "save/update/delete/...modification" operation on an object has the potential to modify several rows in several tables (because of the cascade through the object graph), of course there should also be transaction management on this specific DAO method.
User extend AppCompatActivity
& it will work !!
There are several ways to do it:
n = L[0][0]
m = len(A)
found = False
for i in range(m):
if found:
break
for j in range(m):
if L[i][j] != n:
found = True
break
Pros: easy to understand Cons: additional conditional statement for every loop
n = L[0][0]
m = len(A)
try:
for x in range(3):
for z in range(3):
if L[i][j] != n:
raise StopIteration
except StopIteration:
pass
Pros: very straightforward Cons: you use Exception outside of their semantic
def is_different_value(l, elem, size):
for x in range(size):
for z in range(size):
if l[i][j] != elem:
return True
return False
if is_different_value(L, L[0][0], len(A)):
print "Doh"
pros: much cleaner and still efficient cons: yet feels like C
def is_different_value(iterable):
first = iterable[0][0]
for l in iterable:
for elem in l:
if elem != first:
return True
return False
if is_different_value(L):
print "Doh"
pros: still clean and efficient cons: you reinvdent the wheel
any()
:def is_different_value(iterable):
first = iterable[0][0]
return any(any((cell != first for cell in col)) for elem in iterable)):
if is_different_value(L):
print "Doh"
pros: you'll feel empowered with dark powers cons: people that will read you code may start to dislike you
There is new method in SQL Server 2017:
SELECT STRING_AGG (column, ',') AS column FROM Table;
that will produce 1,3,5,9
for you
In your XML set the Background
attribute to any colour, White(#FFFFFF)
shade or Black(#000000)
shade. If you want transparency, just put 80 before the actual hash code:
#80000000
This will change any colour you want to a transparent one.. :)
i have used this, this library is very useful
from pyjavaproperties import Properties
p = Properties()
p.load(open('test.properties'))
p.list()
print(p)
print(p.items())
print(p['name3'])
p['name3'] = 'changed = value'
I use System.getEnv() to get the map and I keep as a field, so I can mock it:
public class AAA {
Map<String, String> environmentVars;
public String readEnvironmentVar(String varName) {
if (environmentVars==null) environmentVars = System.getenv();
return environmentVars.get(varName);
}
}
public class AAATest {
@Test
public void test() {
aaa.environmentVars = new HashMap<String,String>();
aaa.environmentVars.put("NAME", "value");
assertEquals("value",aaa.readEnvironmentVar("NAME"));
}
}
The tidyverse
version is this:
> library(dplyr)
> library(scales)
> set.seed(1)
> m <- runif(5)
> dt <- as.data.frame(m)
> dt %>% mutate(perc=percent(m,accuracy=0.001))
m perc
1 0.2655087 26.551%
2 0.3721239 37.212%
3 0.5728534 57.285%
4 0.9082078 90.821%
5 0.2016819 20.168%
Looks tidy as usual.
By the way, a history of Java SE versions.
I have an solution for a generic List<> with dynamic binded items.
class PersonalList it's the root element
[XmlRoot("PersonenListe")]
[XmlInclude(typeof(Person))] // include type class Person
public class PersonalList
{
[XmlArray("PersonenArray")]
[XmlArrayItem("PersonObjekt")]
public List<Person> Persons = new List<Person>();
[XmlElement("Listname")]
public string Listname { get; set; }
// Konstruktoren
public PersonalList() { }
public PersonalList(string name)
{
this.Listname = name;
}
public void AddPerson(Person person)
{
Persons.Add(person);
}
}
class Person it's an single list element
[XmlType("Person")] // define Type
[XmlInclude(typeof(SpecialPerson)), XmlInclude(typeof(SuperPerson))]
// include type class SpecialPerson and class SuperPerson
public class Person
{
[XmlAttribute("PersID", DataType = "string")]
public string ID { get; set; }
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("City")]
public string City { get; set; }
[XmlElement("Age")]
public int Age { get; set; }
// Konstruktoren
public Person() { }
public Person(string name, string city, int age, string id)
{
this.Name = name;
this.City = city;
this.Age = age;
this.ID = id;
}
}
class SpecialPerson inherits Person
[XmlType("SpecialPerson")] // define Type
public class SpecialPerson : Person
{
[XmlElement("SpecialInterests")]
public string Interests { get; set; }
public SpecialPerson() { }
public SpecialPerson(string name, string city, int age, string id, string interests)
{
this.Name = name;
this.City = city;
this.Age = age;
this.ID = id;
this.Interests = interests;
}
}
class SuperPerson inherits Person
[XmlType("SuperPerson")] // define Type
public class SuperPerson : Person
{
[XmlArray("Skills")]
[XmlArrayItem("Skill")]
public List<String> Skills { get; set; }
[XmlElement("Alias")]
public string Alias { get; set; }
public SuperPerson()
{
Skills = new List<String>();
}
public SuperPerson(string name, string city, int age, string id, string[] skills, string alias)
{
Skills = new List<String>();
this.Name = name;
this.City = city;
this.Age = age;
this.ID = id;
foreach (string item in skills)
{
this.Skills.Add(item);
}
this.Alias = alias;
}
}
and the main test Source
static void Main(string[] args)
{
PersonalList personen = new PersonalList();
personen.Listname = "Friends";
// normal person
Person normPerson = new Person();
normPerson.ID = "0";
normPerson.Name = "Max Man";
normPerson.City = "Capitol City";
normPerson.Age = 33;
// special person
SpecialPerson specPerson = new SpecialPerson();
specPerson.ID = "1";
specPerson.Name = "Albert Einstein";
specPerson.City = "Ulm";
specPerson.Age = 36;
specPerson.Interests = "Physics";
// super person
SuperPerson supPerson = new SuperPerson();
supPerson.ID = "2";
supPerson.Name = "Superman";
supPerson.Alias = "Clark Kent";
supPerson.City = "Metropolis";
supPerson.Age = int.MaxValue;
supPerson.Skills.Add("fly");
supPerson.Skills.Add("strong");
// Add Persons
personen.AddPerson(normPerson);
personen.AddPerson(specPerson);
personen.AddPerson(supPerson);
// Serialize
Type[] personTypes = { typeof(Person), typeof(SpecialPerson), typeof(SuperPerson) };
XmlSerializer serializer = new XmlSerializer(typeof(PersonalList), personTypes);
FileStream fs = new FileStream("Personenliste.xml", FileMode.Create);
serializer.Serialize(fs, personen);
fs.Close();
personen = null;
// Deserialize
fs = new FileStream("Personenliste.xml", FileMode.Open);
personen = (PersonalList)serializer.Deserialize(fs);
serializer.Serialize(Console.Out, personen);
Console.ReadLine();
}
Important is the definition and includes of the diffrent types.
create table encrypt(username varchar(20),password varbinary(200))
insert into encrypt values('raju',aes_encrypt('kumar','key')) select *,cast(aes_decrypt(password,'key') as char(40)) from encrypt where username='raju';
Have you tried height="100%"
in the definition of your iframe ? It seems to do what you seek, if you add height:100%
in the css for "body" (if you do not, 100% will be "100% of your content").
EDIT: do not do this. The height
attribute (as well as the width
one) must have an integer as value, not a string.
PHP mail()
command does not support authentication. Your options:
you can reset to HEAD^
then force push it.
git reset HEAD^
git push -u origin master --force
It will delete your last commit and will reflect on bitbucket as commit deleted but will still remain on their server.
I would change your binding to be:
<button type="button" value="click me" onclick="check_me" />
I would then change your check_me()
function declaration to be:
function check_me() {
//event.preventDefault();
var hello = document.myForm.username.value;
var err = '';
if(hello == '' || hello == null) {
err = 'User name required';
}
if(err != '') {
alert(err);
$('username').focus();
event.preventDefault();
} else {
return true; }
}
You can. Try something like this:
@Path("/todo/{varX}/{varY}")
@Produces({"application/xml", "application/json"})
public Todo whatEverNameYouLike(@PathParam("varX") String varX,
@PathParam("varY") String varY) {
Todo todo = new Todo();
todo.setSummary(varX);
todo.setDescription(varY);
return todo;
}
Then call your service with this URL;
http://localhost:8088/JerseyJAXB/rest/todo/summary/description
To get a position of an element in a vector knowing an iterator pointing to the element, simply subtract v.begin()
from the iterator:
ptrdiff_t pos = find(Names.begin(), Names.end(), old_name_) - Names.begin();
Now you need to check pos
against Names.size()
to see if it is out of bounds or not:
if(pos >= Names.size()) {
//old_name_ not found
}
vector iterators behave in ways similar to array pointers; most of what you know about pointer arithmetic can be applied to vector iterators as well.
Starting with C++11 you can use std::distance
in place of subtraction for both iterators and pointers:
ptrdiff_t pos = distance(Names.begin(), find(Names.begin(), Names.end(), old_name_));
Try this theme
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="colorPrimaryDark">@android:color/transparent</item>
<item name="colorPrimary">@color/md_blue_200</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:windowTranslucentStatus">true</item>
</style>
Be sure that, your layout set
android:fitsSystemWindows="false"
You are using setTimeout
wrong way. The (one of) function signature is setTimeout(callback, delay)
. So you can easily specify what code should be run after what delay.
var codeAddress = (function() {
var index = 0;
var delay = 100;
function GeocodeCallback(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
new google.maps.Marker({ map: map, position: results[0].geometry.location, animation: google.maps.Animation.DROP });
console.log(results);
}
else alert("Geocode was not successful for the following reason: " + status);
};
return function(vPostCode) {
if (geocoder) setTimeout(geocoder.geocode.bind(geocoder, { 'address': "'" + vPostCode + "'"}, GeocodeCallback), index*delay);
index++;
};
})();
This way, every codeAddress()
call will result in geocoder.geocode()
being called 100ms later after previous call.
I also added animation to marker so you will have a nice animation effect with markers being added to map one after another. I'm not sure what is the current google limit, so you may need to increase the value of delay
variable.
Also, if you are each time geocoding the same addresses, you should instead save the results of geocode to your db and next time just use those (so you will save some traffic and your application will be a little bit quicker)
Try this:
if (Boolean.TRUE.equals(yourValue)) { ... }
As additional benefit this is null-safe.
If you don't specify the platform for the app you won't able to add app domain correctly.
Here is an example -- validate that its a type a website platform.
This error raised up because you trying to update dict
object by using a wrong sequence (list
or tuple
) structure.
cash_id.create(cr, uid, lines,context=None)
trying to convert lines
into dict object:
(0, 0, {
'name': l.name,
'date': l.date,
'amount': l.amount,
'type': l.type,
'statement_id': exp.statement_id.id,
'account_id': l.account_id.id,
'account_analytic_id': l.analytic_account_id.id,
'ref': l.ref,
'note': l.note,
'company_id': l.company_id.id
})
Remove the second zero from this tuple to properly convert it into a dict object.
To test it your self, try this into python shell:
>>> l=[(0,0,{'h':88})]
>>> a={}
>>> a.update(l)
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
a.update(l)
ValueError: dictionary update sequence element #0 has length 3; 2 is required
>>> l=[(0,{'h':88})]
>>> a.update(l)
You need to access the page_source
property:
from selenium import webdriver
browser = webdriver.Firefox()
browser.get("http://example.com")
html_source = browser.page_source
if "whatever" in html_source:
# do something
else:
# do something else
The quintessential example of this is an array of pointers to structs or objects (that are mutable).
A shallow copy copies the array and maintains references to the original objects.
A deep copy will copy (clone) the objects too so they bear no relation to the original. Implicit in this is that the object themselves are deep copied. This is where it gets hard because there's no real way to know if something was deep copied or not.
The copy constructor is used to initilize the new object with the previously created object of the same class. By default compiler wrote a shallow copy. Shallow copy works fine when dynamic memory allocation is not involved because when dynamic memory allocation is involved then both objects will points towards the same memory location in a heap, Therefore to remove this problem we wrote deep copy so both objects have their own copy of attributes in a memory.
In order to read the details with complete examples and explanations you could see the article Constructors and destructors.
The default copy constructor is shallow. You can make your own copy constructors deep or shallow, as appropriate. See C++ Notes: OOP: Copy Constructors.
http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
Using Guava:
if (CharMatcher.anyOf("ABC...").matches(symbol)) { ... }
Or if many of those characters are a range, such as "A" to "U" but some aren't:
CharMatcher.inRange('A', 'U').or(CharMatcher.anyOf("1379"))
You can also declare this as a static final
field so the matcher doesn't have to be created each time.
private static final CharMatcher MATCHER = CharMatcher.anyOf("ABC...");
In windows, you need to use double quotes "". So the command would be
git commit -m "t"
I tried in online compiler https://www.onlinegdb.com/online_c++_compiler
int main()
{
cout<<"Hello World";
int x = 10;
int *p = &x;
printf("\nAddress of x is %p\n", &x); // 0x7ffc7df0ea54
printf("Address of p is %p\n", p); // 0x7ffc7df0ea54
return 0;
}
I found an event OnError
in confluent Kafka:
consumer.OnError += Consumer_OnError;
private void Consumer_OnError(object sender, Error e)
{
Debug.Log("connection error: "+ e.Reason);
ConsumerConnectionError(e);
}
And its documentation in code:
//
// Summary:
// Raised on critical errors, e.g. connection failures or all brokers down. Note
// that the client will try to automatically recover from errors - these errors
// should be seen as informational rather than catastrophic
//
// Remarks:
// Executes on the same thread as every other Consumer event handler (except OnLog
// which may be called from an arbitrary thread).
public event EventHandler<Error> OnError;
Loop over Application.Current.Windows[]
and find the one with IsActive == true
.
An update to Martin Alléus's answer, to get the full screen whether it is a phone or a iPad without having to hard code:
CGRect rect = [[UIScreen mainScreen] bounds];
CGSize screenSize = rect.size;
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,screenSize.width,screenSize.height)];
NSString *path = [[NSBundle mainBundle] pathForResource:@"pdf" ofType:@"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
You can also add
<Resource
auth="Container"
driverClassName="org.apache.derby.jdbc.EmbeddedDriver"
maxActive="20"
maxIdle="10"
maxWait="-1"
name="ds/flexeraDS"
type="javax.sql.DataSource"
url="jdbc:derby:flexeraDB;create=true"
/>
under META-INF/context.xml
file (This will be only at application level).
The simplest way of doing this would be to add
include_directories(${CMAKE_SOURCE_DIR}/inc)
link_directories(${CMAKE_SOURCE_DIR}/lib)
add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # libbar.so is found in ${CMAKE_SOURCE_DIR}/lib
The modern CMake version that doesn't add the -I and -L
flags to every compiler invocation would be to use imported libraries:
add_library(bar SHARED IMPORTED) # or STATIC instead of SHARED
set_target_properties(bar PROPERTIES
IMPORTED_LOCATION "${CMAKE_SOURCE_DIR}/lib/libbar.so"
INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_SOURCE_DIR}/include/libbar"
)
set(FOO_SRCS "foo.cpp")
add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # also adds the required include path
If setting the INTERFACE_INCLUDE_DIRECTORIES
doesn't add the path, older versions of CMake also allow you to use target_include_directories(bar PUBLIC /path/to/include)
. However, this no longer works with CMake 3.6 or newer.
Your Fragment can subclass ListFragment.
And onCreateView() from ListFragment
will return a ListView
you can then populate.
I'm surprised nobody has mentioned the new Fetch API, supported by all browsers except IE11 at the time of writing. It simplifies the XMLHttpRequest syntax you see in many of the other examples.
The API includes a lot more, but start with the fetch()
method. It takes two arguments:
Simple GET:
const userAction = async () => {
const response = await fetch('http://example.com/movies.json');
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
}
Recreating the previous top answer, a POST:
const userAction = async () => {
const response = await fetch('http://example.com/movies.json', {
method: 'POST',
body: myBody, // string or object
headers: {
'Content-Type': 'application/json'
}
});
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
}
By having the .5s delay on transitioning the opacity property, the element will be completely transparent (and thus invisible) the whole time its height is transitioning. So the only thing you will actually see is the opacity changing. So you will get the same effect as leaving the height property out of the transition :
"transition: opacity .5s .5s;"
Is that what you're wanting? If not, and you're wanting to see the height transition, you can't have an opacity of zero during the whole time that it's transitioning.
You need to do two things:
ie
one.start();
one.join();
If you don't start()
it, nothing will happen - creating a Thread doesn't execute it.
If you don't join)
it, your main thread may finish and exit and the whole program exit before the other thread has been scheduled to execute. It's indeterminate whether it runs or not if you don't join it. The new thread may usually run, but may sometimes not run. Better to be certain.
If you are using java 7 then make sure you have Tomcat 7
brew install tomcat@7
and update run configuration to Tomcat 7
Tomcat 9 is working with java 8
Silverlight applications do not have direct access to machine.config.
Apply these changes in phpmyconfig/config.inc. Type in your username and password that you have set:
$cfg['Servers'][$i]['user'] = 'user';
$cfg['Servers'][$i]['password'] = 'password';
$cfg['Servers'][$i]['AllowNoPassword'] = false;
This works for me.
i'm dealing with the same problem and i get it worked.
it is probably that your jdk version is not right.
now i installed jdk1.8 and it is ok now.
I created a small library that does this (along with some other handy conversions). It's called reimg, and it's really simple to use.
ReImg.fromCanvas(yourCanvasElement).toPng()
Try GraphIT from TechNewLogic, you can find it on CodePlex here: http://graphit.codeplex.com
Full Disclosure: I am the developer of GraphIT and owner of the developing company.
Try this
Actions dragger = new Actions(driver);
WebElement draggablePartOfScrollbar = driver.findElement(By.xpath("//*[@id='jobreslist_outercontainer']/div/div[2]/div"));
// drag downwards
int numberOfPixelsToDragTheScrollbarDown = 50;
for (int i=10;i<500;i=i+numberOfPixelsToDragTheScrollbarDown){
try{
// this causes a gradual drag of the scroll bar, 10 units at a time
dragger.moveToElement(draggablePartOfScrollbar).clickAndHold().moveByOffset(0,numberOfPixelsToDragTheScrollbarDown).release().perform();
Thread.sleep(1000L);
}catch(Exception e1){}
}
// now drag opposite way (downwards)
numberOfPixelsToDragTheScrollbarDown = -50;
for (int i=500;i>10;i=i+numberOfPixelsToDragTheScrollbarDown){
// this causes a gradual drag of the scroll bar, -10 units at a time
dragger.moveToElement(draggablePartOfScrollbar).clickAndHold().moveByOffset(0,numberOfPixelsToDragTheScrollbarDown).release().perform();
Thread.sleep(1000L);
}
HashMap does not allow primitive data types as arguments. It can only accept objects so
HashMap<int, myObject> myMap = new HashMap<int, myObject>();
will not work.
You have to change the declaration to
HashMap<Integer, myObject> myMap = new HashMap<Integer, myObject>();
so even when you do the following
myMap.put(2,myObject);
The primitive data type is autoboxed to an Integer object.
8 (int) === boxing ===> 8 (Integer)
You can read more on autoboxing here http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html
If you wish, you can also use the column names instead of column numbers.
For example, if you want to read data from DataGridView on the 4. row and the "Name" column. It provides me a better understanding for which variable I am dealing with.
dataGridView.Rows[4].Cells["Name"].Value.ToString();
Hope it helps.
Try using printf
function or the concatination operator
In KitKat and above, you could use evaluateJavascript
method on webview
wvbrowser.evaluateJavascript(
"(function() { return ('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>'); })();",
new ValueCallback<String>() {
@Override
public void onReceiveValue(String html) {
Log.d("HTML", html);
// code here
}
});
See this answer for more examples
If you are super cool, you might try:
$test_server = $_SERVER['SERVER_NAME'] == "127.0.0.1" || $_SERVER['SERVER_NAME'] == "localhost" || substr($_SERVER['SERVER_NAME'],0,3) == "192";
ini_set('display_errors',$test_server);
error_reporting(E_ALL|E_STRICT);
This will only display errors when you are running locally. It also gives you the test_server variable to use in other places where appropriate.
Any errors that happen before the script runs won't be caught, but for 99% of errors that I make, that's not an issue.
This same problem occurs when the owners of the file have been deleted. When this happens, if you go to the file's properties, you will see a SID rather than a user name. Take ownership of the file (giving yourself FULL CONTROL). Once that is done you can do whatever you need to do with the file.
I've had this work when logging in as the administrator didn't do the trick.
These are identical for printf
but different for scanf
. For printf
, both %d
and %i
designate a signed decimal integer. For scanf
, %d
and %i
also means a signed integer but %i
inteprets the input as a hexadecimal number if preceded by 0x
and octal if preceded by 0
and otherwise interprets the input as decimal.
The AJAX request never has the opportunity to NOT follow the redirect (i.e., it must follow the redirect). More information can be found in this answer https://stackoverflow.com/a/2573589/965648
You can access the values in a vector just as you access any other array.
for (int i = 0; i < v.size(); i++)
{
v[i] -= 1;
}
I fixed the same issue in my application by adding below code in the css -
.dataTables_scrollHeadInner
{
width: 640px !important;
}
Here my example ssl socket server threads (multiple connection) https://github.com/breakermind/CppLinux/blob/master/QtSslServerThreads/breakermindsslserver.cpp
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <iostream>
#include <breakermindsslserver.h>
using namespace std;
int main(int argc, char *argv[])
{
BreakermindSslServer boom;
boom.Start(123,"/home/user/c++/qt/BreakermindServer/certificate.crt", "/home/user/c++/qt/BreakermindServer/private.key");
return 0;
}
This is the easiest way that I found to install a plugin locally at eclipse -
Function | Copies metadata |
Copies permissions |
Uses file object | Destination may be directory |
---|---|---|---|---|
shutil.copy | No | Yes | No | Yes |
shutil.copyfile | No | No | No | No |
shutil.copy2 | Yes | Yes | No | Yes |
shutil.copyfileobj | No | No | Yes | No |
I was looking for an answer to this question and later I developed a method! :) A fair warning, it's rounding up the value.
private float limitDigits(float number) {
return Float.valueOf(String.format(Locale.getDefault(), "%.2f", number));
}
with open("input", "rb") as input:
with open("output", "wb") as output:
while True:
data = input.read(1024)
if data == "":
break
output.write(data)
The above will read 1 kilobyte at a time, and write it. You can support incredibly large files this way, as you won't need to read the entire file into memory.
Use parseJSON jquery method to covert string into object
var objData = jQuery.parseJSON(data);
Now you can write code
$('#result').html(objData .status +':' + objData .message);
Use option -t for sendmail.
in your case - echo -e $mail | /usr/sbin/sendmail -t
and add yout Recepient list to message itself like To: [email protected] [email protected]
right after the line From:.....
-t
option means -
Read message for recipients. To:, Cc:, and Bcc: lines will be scanned for recipient addresses. The Bcc: line will be deleted before transmission.
Qberticus's answer is good, but one useful detail is missing. If you are implementing these in a library replace:
xmlns:whatever="http://schemas.android.com/apk/res/org.example.mypackage"
with:
xmlns:whatever="http://schemas.android.com/apk/res-auto"
Otherwise the application that uses the library will have runtime errors.
If you want to ignore the step to check if file exists or not, then you can use a fairly easy command, which will delete the file if exists and does not throw an error if it is non-existing.
rm -f xyz.csv
You simply cannot and should not do this. However, this might be helpful:
<script type = "text/javascript" >
history.pushState(null, null, 'pagename');
window.addEventListener('popstate', function(event) {
history.pushState(null, null, 'pagename');
});
</script>
This works in my Google Chrome and Firefox.
the same problem also happened to me when i training my classification model. the reason caused this problem is as what the warning message said "in labels with no predicated samples", it will caused the zero-division when compute f1-score. I found another solution when i read sklearn.metrics.f1_score doc, there is a note as follows:
When true positive + false positive == 0, precision is undefined; When true positive + false negative == 0, recall is undefined. In such cases, by default the metric will be set to 0, as will f-score, and UndefinedMetricWarning will be raised. This behavior can be modified with zero_division
the zero_division
default value is "warn"
, you could set it to 0
or 1
to avoid UndefinedMetricWarning
.
it works for me ;) oh wait, there is another problem when i using zero_division
, my sklearn report that no such keyword argument by using scikit-learn 0.21.3. Just update your sklearn to the latest version by running pip install scikit-learn -U
Added IF/ELSEIF statements to the code from Dave and AmalMurali for handling strings without spaces
if ((strpos($string, ' ') !== false) && (strlen($string) > 200)) {
$WidgetText = substr($string, 0, strrpos(substr($string, 0, 200), ' '));
}
elseif (strlen($string) > 200) {
$WidgetText = substr($string, 0, 200);
}
It would be the highest available priority setting, and would usually only be used on box that was dedicated to running that specific program. It's actually high enough that it could cause starvation of the keyboard and mouse threads to the extent that they become unresponsive.
So basicly, if you have to ask, don't use it :)
New answer (2016-04-20)
Using Spring Boot 1.3.1.RELEASE
New Step 1 - It is easy and less intrusive to add the following properties to the application.properties:
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
Much easier than modifying the existing DispatcherServlet instance (as below)! - JO'
If working with a full RESTful Application, it is very important to disable the automatic mapping of static resources since if you are using Spring Boot's default configuration for handling static resources then the resource handler will be handling the request (it's ordered last and mapped to /** which means that it picks up any requests that haven't been handled by any other handler in the application) so the dispatcher servlet doesn't get a chance to throw an exception.
New Answer (2015-12-04)
Using Spring Boot 1.2.7.RELEASE
New Step 1 - I found a much less intrusive way of setting the "throExceptionIfNoHandlerFound" flag. Replace the DispatcherServlet replacement code below (Step 1) with this in your application initialization class:
@ComponentScan()
@EnableAutoConfiguration
public class MyApplication extends SpringBootServletInitializer {
private static Logger LOG = LoggerFactory.getLogger(MyApplication.class);
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(MyApplication.class, args);
DispatcherServlet dispatcherServlet = (DispatcherServlet)ctx.getBean("dispatcherServlet");
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
}
In this case, we're setting the flag on the existing DispatcherServlet, which preserves any auto-configuration by the Spring Boot framework.
One more thing I've found - the @EnableWebMvc annotation is deadly to Spring Boot. Yes, that annotation enables things like being able to catch all the controller exceptions as described below, but it also kills a LOT of the helpful auto-configuration that Spring Boot would normally provide. Use that annotation with extreme caution when you use Spring Boot.
Original Answer:
After a lot more research and following up on the solutions posted here (thanks for the help!) and no small amount of runtime tracing into the Spring code, I finally found a configuration that will handle all Exceptions (not Errors, but read on) including 404s.
Step 1 - tell SpringBoot to stop using MVC for "handler not found" situations. We want Spring to throw an exception instead of returning to the client a view redirect to "/error". To do this, you need to have an entry in one of your configuration classes:
// NEW CODE ABOVE REPLACES THIS! (2015-12-04)
@Configuration
public class MyAppConfig {
@Bean // Magic entry
public DispatcherServlet dispatcherServlet() {
DispatcherServlet ds = new DispatcherServlet();
ds.setThrowExceptionIfNoHandlerFound(true);
return ds;
}
}
The downside of this is that it replaces the default dispatcher servlet. This hasn't been a problem for us yet, with no side effects or execution problems showing up. If you're going to do anything else with the dispatcher servlet for other reasons, this is the place to do them.
Step 2 - Now that spring boot will throw an exception when no handler is found, that exception can be handled with any others in a unified exception handler:
@EnableWebMvc
@ControllerAdvice
public class ServiceExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Throwable.class)
@ResponseBody
ResponseEntity<Object> handleControllerException(HttpServletRequest req, Throwable ex) {
ErrorResponse errorResponse = new ErrorResponse(ex);
if(ex instanceof ServiceException) {
errorResponse.setDetails(((ServiceException)ex).getDetails());
}
if(ex instanceof ServiceHttpException) {
return new ResponseEntity<Object>(errorResponse,((ServiceHttpException)ex).getStatus());
} else {
return new ResponseEntity<Object>(errorResponse,HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Override
protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
Map<String,String> responseBody = new HashMap<>();
responseBody.put("path",request.getContextPath());
responseBody.put("message","The URL you have reached is not in service at this time (404).");
return new ResponseEntity<Object>(responseBody,HttpStatus.NOT_FOUND);
}
...
}
Keep in mind that I think the "@EnableWebMvc" annotation is significant here. It seems that none of this works without it. And that's it - your Spring boot app will now catch all exceptions, including 404s, in the above handler class and you may do with them as you please.
One last point - there doesn't seem to be a way to get this to catch thrown Errors. I have a wacky idea of using aspects to catch errors and turn them into Exceptions that the above code can then deal with, but I have not yet had time to actually try implementing that. Hope this helps someone.
Any comments/corrections/enhancements will be appreciated.
You can test using eval
:
try:
eval("1 if True else 2")
except SyntaxError:
# doesn't have ternary
Also, with
is available in Python 2.5, just add from __future__ import with_statement
.
EDIT: to get control early enough, you could split it into different .py
files and check compatibility in the main file before importing (e.g. in __init__.py
in a package):
# __init__.py
# Check compatibility
try:
eval("1 if True else 2")
except SyntaxError:
raise ImportError("requires ternary support")
# import from another module
from impl import *
Take a look there : http://developer.android.com/guide/topics/intents/intents-filters.html
DO you have update your manifest file in order to give call rights ?
There is an option “unlimited scrollback buffer” which you can find under Preferences > Profiles > Terminal
or you can just pump up number of lines that you want to have in history in the same place.
TL;DR. In Visual Studio 2019
, when you add an Icon
resource to a Win32
(desktop) application you get an auto-generated icon file that has the formats below. I assume that the #1 developer tool for Windows does this right. Thus, a Windows
compatible should have the following formats:
| Resolution | Color depth | Format |
|:-----------|------------:|:------:|
| 256x256 | 32-bit | PNG |
| 64x64 | 32-bit | BMP |
| 48x48 | 32-bit | BMP |
| 32x32 | 32-bit | BMP |
| 16x16 | 32-bit | BMP |
| 48x48 | 8-bit | BMP |
| 32x32 | 8-bit | BMP |
| 16x16 | 8-bit | BMP |
You Can Wrap your widget with Flexible Widget and than you can set property of Text using overflow property of Text Widget. you have to set TextOverflow.clip for example:-
Flexible
(child: new Text("This is Dummy Long Text",
style: TextStyle(
fontFamily: "Roboto",
color: Colors.black,
fontSize: 10.0,
fontWeight: FontWeight.bold),
overflow: TextOverflow.clip,),)
hope this help someone :)
Another alternative is to link libedit for proper line editing (arrow keys, etc.) and optional history support. I wanted this for a project I'm starting and put together a basic example for how I set it up.
Usage from swift
let prompt: Prompt = Prompt(argv0: C_ARGV[0])
while (true) {
if let line = prompt.gets() {
print("You typed \(line)")
}
}
ObjC wrapper to expose libedit
#import <histedit.h>
char* prompt(EditLine *e) {
return "> ";
}
@implementation Prompt
EditLine* _el;
History* _hist;
HistEvent _ev;
- (instancetype) initWithArgv0:(const char*)argv0 {
if (self = [super init]) {
// Setup the editor
_el = el_init(argv0, stdin, stdout, stderr);
el_set(_el, EL_PROMPT, &prompt);
el_set(_el, EL_EDITOR, "emacs");
// With support for history
_hist = history_init();
history(_hist, &_ev, H_SETSIZE, 800);
el_set(_el, EL_HIST, history, _hist);
}
return self;
}
- (void) dealloc {
if (_hist != NULL) {
history_end(_hist);
_hist = NULL;
}
if (_el != NULL) {
el_end(_el);
_el = NULL;
}
}
- (NSString*) gets {
// line includes the trailing newline
int count;
const char* line = el_gets(_el, &count);
if (count > 0) {
history(_hist, &_ev, H_ENTER, line);
return [NSString stringWithCString:line encoding:NSUTF8StringEncoding];
}
return nil;
}
@end
Initialize tSize to
tSize = ""
before your if block to be safe. Also in your else case, put tSize in quotes so it is a string not an int. Also also you are comparing strings to ints.
In Order to implement Line Break in SSRS, there are 2 ways
<br/>
tag to introduce line break within the expression ="first line of text. Param1 value: " & Parameters!Param1.Value & "<br/>" & Parameters!Param1.Value
="first line of text. Param1 value: " & Parameters!Param1.Value & Environment.NewLine()
& Parameters!Param1.Value
Note:- Always remember to leave a space after every "&" (ampersand) in order to evaluate the expression properly
Often times we are interested in calculating the full significant digits, but for the visual aesthetics, we may want to see only few decimal point when we display the dataframe.
In jupyter-notebook, pandas can utilize the html formatting taking advantage of the method called style
.
For the case of just seeing two significant digits of some columns, we can use this code snippet:
import numpy as np
import pandas as pd
df = pd.DataFrame({'var1': [1.458315, 1.576704, 1.629253, 1.6693310000000001, 1.705139, 1.740447, 1.77598, 1.812037, 1.85313, 1.9439849999999999],
'var2': [1.500092, 1.6084450000000001, 1.652577, 1.685456, 1.7120959999999998, 1.741961, 1.7708009999999998, 1.7993270000000001, 1.8229819999999999, 1.8684009999999998],
'var3': [-0.0057090000000000005, -0.005122, -0.0047539999999999995, -0.003525, -0.003134, -0.0012230000000000001, -0.0017230000000000001, -0.002013, -0.001396, 0.005732]})
print(df)
var1 var2 var3
0 1.458315 1.500092 -0.005709
1 1.576704 1.608445 -0.005122
2 1.629253 1.652577 -0.004754
3 1.669331 1.685456 -0.003525
4 1.705139 1.712096 -0.003134
5 1.740447 1.741961 -0.001223
6 1.775980 1.770801 -0.001723
7 1.812037 1.799327 -0.002013
8 1.853130 1.822982 -0.001396
9 1.943985 1.868401 0.005732
df.style.format({'var1': "{:.2f}",'var2': "{:.2f}",'var3': "{:.2%}"})
Gives:
var1 var2 var3
id
0 1.46 1.50 -0.57%
1 1.58 1.61 -0.51%
2 1.63 1.65 -0.48%
3 1.67 1.69 -0.35%
4 1.71 1.71 -0.31%
5 1.74 1.74 -0.12%
6 1.78 1.77 -0.17%
7 1.81 1.80 -0.20%
8 1.85 1.82 -0.14%
9 1.94 1.87 0.57%
If display command is not found try following:
from IPython.display import display
df_style = df.style.format({'var1': "{:.2f}",'var2': "{:.2f}",'var3': "{:.2%}"})
display(df_style)
display
command, you need to have installed Ipython in your machine.display
command does not work in online python interpreter which do not have IPyton
installed such as https://repl.it/languages/python3You can use cstdlib
Although- http://www.cplusplus.com/articles/j3wTURfi/
#include <cstdlib>
const int dir= system("mkdir -p foo");
if (dir< 0)
{
return;
}
you can also check if the directory exists already by using
#include <dirent.h>
Now for the missing class problem.
I'm an Eclipse Java EE developer and have been in the habit for many years of adding third-party libraries via the "User Library" mechanism in Build Path. Of course, there are at least 3 ways to add a third-party library, the one I use is the most elegant, in my humble opinion.
This will not work, however, for Android, whose Dalvik "JVM" cannot handle an ordinary Java-compiled class, but must have it converted to a special format. This does not happen when you add a library in the way I'm wont to do it.
Instead, follow the (widely available) instructions for importing the third-party library, then adding it using Build Path (which makes it known to Eclipse for compilation purposes). Here is the step-by-step:
NOTE
Step 5 may not be needed, if the lib is already included in your build path. Just ensure that its existence first before adding it.
What you've done here accomplishes two things:
Your code looks good, in fact it works (apart from the calls themselves) when copied & pasted into a sample jsFiddle: http://jsfiddle.net/VGaWD/
Hard to say what is going on without seeing a more complete example but I hope that the above jsFiddle will be helpful. What I'm suspecting is that you are not initializing your app with the 'productServices' module. It would give the same error, we can see this in another jsFiddle: http://jsfiddle.net/a69nX/1/
If you are planning to work with AngularJS and MongoLab I would suggest using an existing adapter for the $resource and MongoLab: https://github.com/pkozlowski-opensource/angularjs-mongolab It eases much of the pain working with MongoLab, you can see it in action here: http://jsfiddle.net/pkozlowski_opensource/DP4Rh/ Disclaimer! I'm maintaining this adapter (written based on AngularJS examples) so I'm obviously biased here.
I have a library called colorit. It is super simple.
Here are some examples:
from colorit import *
# Use this to ensure that ColorIt will be usable by certain command line interfaces
# Note: This clears the terminal
init_colorit()
# Foreground
print(color("This text is red", Colors.red))
print(color("This text is orange", Colors.orange))
print(color("This text is yellow", Colors.yellow))
print(color("This text is green", Colors.green))
print(color("This text is blue", Colors.blue))
print(color("This text is purple", Colors.purple))
print(color("This text is white", Colors.white))
# Background
print(background("This text has a background that is red", Colors.red))
print(background("This text has a background that is orange", Colors.orange))
print(background("This text has a background that is yellow", Colors.yellow))
print(background("This text has a background that is green", Colors.green))
print(background("This text has a background that is blue", Colors.blue))
print(background("This text has a background that is purple", Colors.purple))
print(background("This text has a background that is white", Colors.white))
# Custom
print(color("This color has a custom grey text color", (150, 150, 150)))
print(background("This color has a custom grey background", (150, 150, 150)))
# Combination
print(
background(
color("This text is blue with a white background", Colors.blue), Colors.white
)
)
# If you are using Windows Command Line, this is so that it doesn't close immediately
input()
This gives you:
It's also worth noting that this is cross platform and has been tested on Mac, Linux, and Windows.
You might want to try it out: https://github.com/SuperMaZingCoder/colorit
colorit
is now available to be installed with PyPi! You can install it with pip install color-it
on Windows and pip3 install color-it
on macOS and Linux.
Working example
@Repository
public interface TenantRepository extends JpaRepository< Tenant, Long > {
List<Tenant>findByTenantName(String tenantName,Pageable pageRequest);
long countByTenantName(String tenantName);
}
Calling from DAO layer
@Override
public long countByTenantName(String tenantName) {
return repository.countByTenantName(tenantName);
}
This alternate approach with filtering for format counts all available grub kernel modules:
ls -l /boot/grub/*.mod | wc -l
Or just mydict.keys()
That's a builtin method call for dictionaries. Also explore mydict.values()
and mydict.items()
.
//Ah, OP post confused me.
Your browser's default font-family will be inherited for that case.
You can check the browser default font in chrome: Settings > Web content > Customize fonts...
$myVar = $someVar ?? 42;
Is equivalent to :
$myVar = isset($someVar) ? $someVar : 42;
For constants, the behaviour is the same when using a constant that already exists :
define("FOO", "bar");
define("BAR", null);
$MyVar = FOO ?? "42";
$MyVar2 = BAR ?? "42";
echo $MyVar . PHP_EOL; // bar
echo $MyVar2 . PHP_EOL; // 42
However, for constants that don't exist, this is different :
$MyVar3 = IDONTEXIST ?? "42"; // Raises a warning
echo $MyVar3 . PHP_EOL; // IDONTEXIST
Warning: Use of undefined constant IDONTEXIST - assumed 'IDONTEXIST' (this will throw an Error in a future version of PHP)
Php will convert the non-existing constant to a string.
You can use constant("ConstantName")
that returns the value of the constant or null if the constant doesn't exist, but it will still raise a warning. You can prepended the function with the error control operator @
to ignore the warning message :
$myVar = @constant("IDONTEXIST") ?? "42"; // No warning displayed anymore
echo $myVar . PHP_EOL; // 42
There are 7 hex color formats: ""#FF0000","0xFF0000", "FF0000", "F00", "red", 0x00FF00 , 16711935
NSColorParser.nsColor("#FF0000",1)//red nsColor
NSColorParser.nsColor("FF0",1)//red nsColor
NSColorParser.nsColor("0xFF0000",1)//red nsColor
NSColorParser.nsColor("#FF0000",1)//red nsColor
NSColorParser.nsColor("FF0000",1)//red nsColor
NSColorParser.nsColor(0xFF0000,1)//red nsColor
NSColorParser.nsColor(16711935,1)//red nsColor
CAUTION: This isn't a "one-file-solution", there are some dependencies, but hunting them down may be faster than researching this from scratch.
Permalink:
https://github.com/eonist/Element/wiki/Progress#supporting-7-hex-color-types
From https://developer.mozilla.org/en-US/docs/Web/CSS/background-color
To set background color:
/* Hexadecimal value with color and 100% transparency*/
background-color: #11ffee00; /* Fully transparent */
/* Special keyword values */
background-color: transparent;
/* HSL value with color and 100% transparency*/
background-color: hsla(50, 33%, 25%, 1.00); /* 100% transparent */
/* RGB value with color and 100% transparency*/
background-color: rgba(117, 190, 218, 1.0); /* 100% transparent */
I realise that posting links are not the best way to do things, but I highly recommend you read the following documentation from Google themselves. This is the official android doc on how to control your system ui (things like actionbar, nav bar etc). Unfortunately the info is too much to post directly, but after reading this you will understand exactly how to show and hide features no matter what version you are developing for, its so simple!
Incase the link ever changes, it can be found under the official android documentation under training -> getting started -> Best practices for user interface -> managing the system ui
To turn off line numbering, again follow the preceding instructions, except this time enter the following line at the : prompt:
set nonumber
The best way to extract the values is to just do the following
json.loads(dataframe[column].value_counts().to_json())
This returns a dictionary which you can use like any other dict. Using values or keys.
{"apple": 5, "sausage": 2, "banana": 2, "cheese": 1}
To complete Sandy Chapman's answer, here is a solution in Objective-C (put this category anywhere you want to change UILabel
Appearance
):
@implementation UILabel (FontOverride)
- (void)setSubstituteFontName:(NSString *)name UI_APPEARANCE_SELECTOR {
self.font = [UIFont fontWithName:name size:self.font.pointSize];
}
@end
The interface file, should have this method declared publicly to be used later from places like your app delegate:
@interface UILabel (FontOverride)
- (void)setSubstituteFontName:(NSString *)name UI_APPEARANCE_SELECTOR;
@end
Then, you can change the Appearance
with:
[[UILabel appearance] setSubstituteFontName:@"SourceSansPro-Light"];
A lot of the answers here do not work for (string)"0.00".
Try this:
if (isset($_POST['num1']) && (float)$_POST['num1'] != 0) {
...
}
Or even more strict:
if (isset($_POST['num1']) && is_numeric($_POST['num1']) && (float)$_POST['num1'] != 0) {
...
}
Why to use regex? PHP has some built in functionality to do that
<?php
$valid_symbols = array('-', '_');
$string1 = "This is a string*";
$string2 = "this_is-a-string";
if(preg_match('/\s/',$string1) || !ctype_alnum(str_replace($valid_symbols, '', $string1))) {
echo "String 1 not acceptable acceptable";
}
?>
preg_match('/\s/',$username)
will check for blank space
!ctype_alnum(str_replace($valid_symbols, '', $string1))
will check for valid_symbols
What do you want it to do once it gets there? Each command is executed in a subshell, so the subshell changes directory, but the end result is that the next command is still in the current directory.
With GNU make, you can do something like:
BIN=/bin
foo:
$(shell cd $(BIN); ls)
Have you tried by setting the MIME type of your .m4v to "video/m4v" or "video/x-m4v" ?
Browsers might use the canPlayType
method internally to check if a <source>
is candidate to playback.
In Chrome, I have these results:
document.createElement("video").canPlayType("video/mp4"); // "maybe"
document.createElement("video").canPlayType("video/m4v"); // ""
document.createElement("video").canPlayType("video/x-m4v"); // "maybe"
When you need to toggle an element away, and you don't need to animate the margin property. You could try margin-top: -999999em
. Just don't transition all.
According to the documentation, in Sublime 2, the data directory should be on these locations:
This information is available here: http://docs.sublimetext.info/en/sublime-text-2/basic_concepts.html#the-data-directory
For Sublime 3, the locations are the following:
This information is available here:http://docs.sublimetext.info/en/sublime-text-3/basic_concepts.html#the-data-directory
import urllib.parse
urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
To test if the POST variable has an element called 'userID' you would be better off using array_key_exists .. which actually tests for the existence of the array key not whether its value has been set .. a subtle and probably only semantic difference, but it does improve readability.
and right now your $uid is being set to a boolean value depending whether $__POST['userID'] is set or not ... If I recall from memory you might want to try ...
$uid = (array_key_exists('userID', $_POST)?$_POST['userID']:'guest';
Then you can use an identifiable 'guest' user and render your code that much more readable :)
Another point re isset() even though it is unlikely to apply in this scenario, it's worth remembering if you don't want to get caught out later ... an array element can be legitimately set to NULL ... i.e. it can exist, but be as yet unpopulated, and this could be a valid, acceptable, and testable condition. but :
a = array('one'=>1, 'two'=>null, 'three'=>3);
isset(a['one']) == true
isset(a['two']) == false
array_key_exists(a['one']) == true
array_key_exists(a['two']) == true
Bw sure you know which function you want to use for which purpose.
I would emphasize the importance of limiting the ::ng-deep
to only children of a component by requiring the parent to be an encapsulated css class.
For this to work it's important to use the ::ng-deep
after the parent, not before otherwise it would apply to all the classes with the same name the moment the component is loaded.
Using the :host
keyword before ::ng-deep
will handle this automatically:
:host ::ng-deep .mat-checkbox-layout
Alternatively you can achieve the same behavior by adding a component scoped CSS class before the ::ng-deep
keyword:
.my-component ::ng-deep .mat-checkbox-layout {
background-color: aqua;
}
Component template:
<h1 class="my-component">
<mat-checkbox ....></mat-checkbox>
</h1>
Resulting (Angular generated) css will then include the uniquely generated name and apply only to its own component instance:
.my-component[_ngcontent-c1] .mat-checkbox-layout {
background-color: aqua;
}
Here is the JSfiddle Demo
I changed your HTML and give your input textfield an id of value. I removed the passed param for your verifyorder function, and instead grab the content of your textfield by using document.getElementById(); then i convert the str into value with +order
so you can check if it's greater than zero:
<input type="text" maxlength="3" name="value" id='value' />
<input type="button" value="submit" onclick="verifyorder()" />
</p>
<p id="error"></p>
<p id="detspace"></p>
function verifyorder() {
var order = document.getElementById('value').value;
if (+order > 0) {
alert(+order);
return true;
}
else {
alert("Sorry, you need to enter a positive integer value, try again");
document.getElementById('error').innerHTML = "Sorry, you need to enter a positive integer value, try again";
}
}
I think the Default place for IIS logging is: c:\inetpub\wwwroot\log\w3svc
You can use numpy.nonzero to find zero.
>>> import numpy as np
>>> x = np.array([1,0,2,0,3,0,0,4,0,5,0,6]).reshape(4, 3)
>>> np.nonzero(x==0) # this is what you want
(array([0, 1, 1, 2, 2, 3]), array([1, 0, 2, 0, 2, 1]))
>>> np.nonzero(x)
(array([0, 0, 1, 2, 3, 3]), array([0, 2, 1, 1, 0, 2]))
IP address uses following authentication :
9 ---> 1-9
import re
k = 0
while k < 5 :
i = input("\nEnter Ip address : ")
ip = re.match("^([1][0-9][0-9].|^[2][5][0-5].|^[2][0-4][0-9].|^[1][0-9][0-9].|^[0-9][0-9].|^[0-9].)([1][0-9][0-9].|[2][5][0-5].|[2][0-4][0-9].|[1][0-9][0-9].|[0-9][0-9].|[0-9].)([1][0-9][0-9].|[2][5][0-5].|[2][0-4][0-9].|[1][0-9][0-9].|[0-9][0-9].|[0-9].)([1][0-9][0-9]|[2][5][0-5]|[2][0-4][0-9]|[1][0-9][0-9]|[0-9][0-9]|[0-9])$",i)
k = k + 1
if ip:
print ("\n=====================")
print ("Valid IP address")
print ("=====================")
break
else :
print ("\nInvalid IP")
else :
print ("\nAllowed Max 5 times")
Reply me if you have doubt?
This is the only solution that worked for me:
var app = angular.module('plunker', ['ngSanitize']);
app.controller('MainCtrl', function($scope, $sce) {
$scope.trustSrc = function(src) {
return $sce.trustAsResourceUrl(src);
}
$scope.movie = {src:"http://www.youtube.com/embed/Lx7ycjC8qjE", title:"Egghead.io AngularJS Binding"};
});
Then in an iframe:
<iframe class="youtube-player" type="text/html" width="640" height="385"
ng-src="{{trustSrc(movie.src)}}" allowfullscreen frameborder="0">
</iframe>
My component used an object myClassObject
of type MyClass
, which itself was using MyEnum
. This lead to the same issue described above. Solved it by doing:
export enum MyEnum {
Option1,
Option2,
Option3
}
export class MyClass {
myEnum: typeof MyEnum;
myEnumField: MyEnum;
someOtherField: string;
}
and then using this in the template as
<div [ngSwitch]="myClassObject.myEnumField">
<div *ngSwitchCase="myClassObject.myEnum.Option1">
Do something for Option1
</div>
<div *ngSwitchCase="myClassObject.myEnum.Option2">
Do something for Option2
</div>
<div *ngSwitchCase="myClassObject.myEnum.Option3">
Do something for Opiton3
</div>
</div>
I’ve been struggling with this for a while now. Dycey’s solution is correct in that specifying the src
multiple times outputs the same thing in your css file. However, this seems to break in OSX Firefox 23 (probably other versions too, but I don’t have time to test).
The cross-browser @font-face
solution from Font Squirrel looks like this:
@font-face {
font-family: 'fontname';
src: url('fontname.eot');
src: url('fontname.eot?#iefix') format('embedded-opentype'),
url('fontname.woff') format('woff'),
url('fontname.ttf') format('truetype'),
url('fontname.svg#fontname') format('svg');
font-weight: normal;
font-style: normal;
}
To produce the src
property with the comma-separated values, you need to write all of the values on one line, since line-breaks are not supported in Sass. To produce the above declaration, you would write the following Sass:
@font-face
font-family: 'fontname'
src: url('fontname.eot')
src: url('fontname.eot?#iefix') format('embedded-opentype'), url('fontname.woff') format('woff'), url('fontname.ttf') format('truetype'), url('fontname.svg#fontname') format('svg')
font-weight: normal
font-style: normal
I think it seems silly to write out the path a bunch of times, and I don’t like overly long lines in my code, so I worked around it by writing this mixin:
=font-face($family, $path, $svg, $weight: normal, $style: normal)
@font-face
font-family: $family
src: url('#{$path}.eot')
src: url('#{$path}.eot?#iefix') format('embedded-opentype'), url('#{$path}.woff') format('woff'), url('#{$path}.ttf') format('truetype'), url('#{$path}.svg##{$svg}') format('svg')
font-weight: $weight
font-style: $style
Usage: For example, I can use the previous mixin to setup up the Frutiger Light font like this:
+font-face('frutigerlight', '../fonts/frutilig-webfont', 'frutigerlight')
Use a js library like underscore.js for these reasons exactly. Use: union: Computes the union of the passed-in arrays: the list of unique items, in order, that are present in one or more of the arrays.
_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2, 3, 101, 10]
select min(table.id), table.column1
from table
group by table.column1
This is a very long explanation that I typed up for a coworker of mine. I think it would be helpful here as well. Be patient, though. I get to the real issue that you are having toward the end. Just as a teaser, it's an issue of having extra references to your Line2D
objects hanging around.
WARNING: One other note before we dive in. If you are using IPython to test this out, IPython keeps references of its own and not all of them are weakrefs. So, testing garbage collection in IPython does not work. It just confuses matters.
Okay, here we go. Each matplotlib
object (Figure
, Axes
, etc) provides access to its child artists via various attributes. The following example is getting quite long, but should be illuminating.
We start out by creating a Figure
object, then add an Axes
object to that figure. Note that ax
and fig.axes[0]
are the same object (same id()
).
>>> #Create a figure
>>> fig = plt.figure()
>>> fig.axes
[]
>>> #Add an axes object
>>> ax = fig.add_subplot(1,1,1)
>>> #The object in ax is the same as the object in fig.axes[0], which is
>>> # a list of axes objects attached to fig
>>> print ax
Axes(0.125,0.1;0.775x0.8)
>>> print fig.axes[0]
Axes(0.125,0.1;0.775x0.8) #Same as "print ax"
>>> id(ax), id(fig.axes[0])
(212603664, 212603664) #Same ids => same objects
This also extends to lines in an axes object:
>>> #Add a line to ax
>>> lines = ax.plot(np.arange(1000))
>>> #Lines and ax.lines contain the same line2D instances
>>> print lines
[<matplotlib.lines.Line2D object at 0xce84bd0>]
>>> print ax.lines
[<matplotlib.lines.Line2D object at 0xce84bd0>]
>>> print lines[0]
Line2D(_line0)
>>> print ax.lines[0]
Line2D(_line0)
>>> #Same ID => same object
>>> id(lines[0]), id(ax.lines[0])
(216550352, 216550352)
If you were to call plt.show()
using what was done above, you would see a figure containing a set of axes and a single line:
Now, while we have seen that the contents of lines
and ax.lines
is the same, it is very important to note that the object referenced by the lines
variable is not the same as the object reverenced by ax.lines
as can be seen by the following:
>>> id(lines), id(ax.lines)
(212754584, 211335288)
As a consequence, removing an element from lines
does nothing to the current plot, but removing an element from ax.lines
removes that line from the current plot. So:
>>> #THIS DOES NOTHING:
>>> lines.pop(0)
>>> #THIS REMOVES THE FIRST LINE:
>>> ax.lines.pop(0)
So, if you were to run the second line of code, you would remove the Line2D
object contained in ax.lines[0]
from the current plot and it would be gone. Note that this can also be done via ax.lines.remove()
meaning that you can save a Line2D
instance in a variable, then pass it to ax.lines.remove()
to delete that line, like so:
>>> #Create a new line
>>> lines.append(ax.plot(np.arange(1000)/2.0))
>>> ax.lines
[<matplotlib.lines.Line2D object at 0xce84bd0>, <matplotlib.lines.Line2D object at 0xce84dx3>]
>>> #Remove that new line
>>> ax.lines.remove(lines[0])
>>> ax.lines
[<matplotlib.lines.Line2D object at 0xce84dx3>]
All of the above works for fig.axes
just as well as it works for ax.lines
Now, the real problem here. If we store the reference contained in ax.lines[0]
into a weakref.ref
object, then attempt to delete it, we will notice that it doesn't get garbage collected:
>>> #Create weak reference to Line2D object
>>> from weakref import ref
>>> wr = ref(ax.lines[0])
>>> print wr
<weakref at 0xb758af8; to 'Line2D' at 0xb757fd0>
>>> print wr()
<matplotlib.lines.Line2D at 0xb757fd0>
>>> #Delete the line from the axes
>>> ax.lines.remove(wr())
>>> ax.lines
[]
>>> #Test weakref again
>>> print wr
<weakref at 0xb758af8; to 'Line2D' at 0xb757fd0>
>>> print wr()
<matplotlib.lines.Line2D at 0xb757fd0>
The reference is still live! Why? This is because there is still another reference to the Line2D
object that the reference in wr
points to. Remember how lines
didn't have the same ID as ax.lines
but contained the same elements? Well, that's the problem.
>>> #Print out lines
>>> print lines
[<matplotlib.lines.Line2D object at 0xce84bd0>, <matplotlib.lines.Line2D object at 0xce84dx3>]
To fix this problem, we simply need to delete `lines`, empty it, or let it go out of scope.
>>> #Reinitialize lines to empty list
>>> lines = []
>>> print lines
[]
>>> print wr
<weakref at 0xb758af8; dead>
So, the moral of the story is, clean up after yourself. If you expect something to be garbage collected but it isn't, you are likely leaving a reference hanging out somewhere.
The git blame
command annotates lines with information from the revision which last modified the line, and... with Git 2.22 (Q2 2019), will do so faster, because of a performance fix around "git blame
", especially in a linear history (which is the norm we should optimize for).
See commit f892014 (02 Apr 2019) by David Kastrup (fedelibre
).
(Merged by Junio C Hamano -- gitster
-- in commit 4d8c4da, 25 Apr 2019)
blame.c
: don't drop origin blobs as eagerlyWhen a parent blob already has chunks queued up for blaming, dropping the blob at the end of one blame step will cause it to get reloaded right away, doubling the amount of I/O and unpacking when processing a linear history.
Keeping such parent blobs in memory seems like a reasonable optimization that should incur additional memory pressure mostly when processing the merges from old branches.
Interfaces do not contain any implementation.
Try setting these values, it solves problem in fast-cgi
fastcgi_buffer_size 16k;
fastcgi_buffers 4 16k;
try this:
powershell "C:\Dummy Directory 1\Foo.ps1 'C:\Dummy Directory 2\File.txt'"
SimpleORM, because it is straight-forward and no-magic. It defines all meta data structures in Java code and is very flexible.
SimpleORM provides similar functionality to Hibernate by mapping data in a relational database to Java objects in memory. Queries can be specified in terms of Java objects, object identity is aligned with database keys, relationships between objects are maintained and modified objects are automatically flushed to the database with optimistic locks.
But unlike Hibernate, SimpleORM uses a very simple object structure and architecture that avoids the need for complex parsing, byte code processing etc. SimpleORM is small and transparent, packaged in two jars of just 79K and 52K in size, with only one small and optional dependency (Slf4j). (Hibernate is over 2400K plus about 2000K of dependent Jars.) This makes SimpleORM easy to understand and so greatly reduces technical risk.
<textarea id="editor1" name="editor1">This is sample text</textarea>
<div id="trackingDiv" ></div>
<script type="text/javascript">
CKEDITOR.replace( 'editor1' );
</script>
Let try this..
Update :
To set data :
Create instance First::
var editor = CKEDITOR.instances['editor1'];
Then,
editor.setData('your data');
or
editor.insertHtml('your html data');
or
editor.insertText('your text data');
And Retrieve data from your editor::
editor.getData();
If change the particular para HTML data in CKEditor.
var html = $(editor.editable.$);
$('#id_of_para',html).html('your html data');
These are the possible ways that I know in CKEditor
it's well documented here:
https://cwiki.apache.org/confluence/display/TOMCAT/Connectors#Connectors-Q6
How do I bind to a specific ip address? - "Each Connector element allows an address property. See the HTTP Connector docs or the AJP Connector docs". And HTTP Connectors docs:
http://tomcat.apache.org/tomcat-7.0-doc/config/http.html
Standard Implementation -> address
"For servers with more than one IP address, this attribute specifies which address will be used for listening on the specified port. By default, this port will be used on all IP addresses associated with the server."
We can use the following options:-
// first option is:-
<Link to="myRoute" params={myParams} target="_blank">
// second option is:-
var href = this.props.history.createHref('myRoute', myParams);
<a href={href} target="_blank">
//third option is:-
var href = '/myRoute/' + myParams.foo + '/' + myParams.bar;
<a href={href} target="_blank">
We can use either of three option to open in new tab by react routing.
Use zip(*list)
:
>>> l = [(1,2), (3,4), (8,9)]
>>> list(zip(*l))
[(1, 3, 8), (2, 4, 9)]
The zip()
function pairs up the elements from all inputs, starting with the first values, then the second, etc. By using *l
you apply all tuples in l
as separate arguments to the zip()
function, so zip()
pairs up 1
with 3
with 8
first, then 2
with 4
and 9
. Those happen to correspond nicely with the columns, or the transposition of l
.
zip()
produces tuples; if you must have mutable list objects, just map()
the tuples to lists or use a list comprehension to produce a list of lists:
map(list, zip(*l)) # keep it a generator
[list(t) for t in zip(*l)] # consume the zip generator into a list of lists
Using Bootstrap 3's grid system:
<div class="container">
<div class="row">
<div class="col-xs-4">Menu</div>
<div class="col-xs-8">
<div class="row">
<div class="col-md-4 col-md-push-8">Right Content</div>
<div class="col-md-8 col-md-pull-4">Content</div>
</div>
</div>
</div>
</div>
Working example: http://bootply.com/93614
First, we set two columns that will stay in place no matter the screen resolution (col-xs-*
).
Next, we divide the larger, right hand column in to two columns that will collapse on top of each other on tablet sized devices and lower (col-md-*
).
Finally, we shift the display order using the matching class (col-md-[push|pull]-*
). You push the first column over by the amount of the second, and pull the second by the amount of the first.
A boolean is not an integer; 1
and 0
are not boolean values in Java. You'll need to convert them explicitly:
boolean multipleContacts = (1 == jsonObject.getInt("MultipleContacts"));
Try this:
<EditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="150dp"
android:inputType="text|textMultiLine"
android:gravity="top"/>
unset
is a function, not an operator. Use it like unset($_SESSION['key']);
to unset that session key. You can, however, use session_destroy();
as well. (Make sure to start the session with session_start();
as well)