As Chris shows, Linq will work; just use Last() to get a reference to the last one in the enumerable, and as long as you aren't working with that reference then do your normal code, but if you ARE working with that reference then do your extra thing. Its downside is that it will always be O(N)-complexity.
You can instead use Count() (which is O(1) if the IEnumerable is also an ICollection; this is true for most of the common built-in IEnumerables), and hybrid your foreach with a counter:
var i=0;
var count = Model.Results.Count();
foreach (Item result in Model.Results)
{
if (++i == count) //this is the last item
}
Root Cause: root has no password, and your python connect statement should reflect that.
To solve error 1698, change your python connect password to ''.
note: manually updating the user's password will not solve the problem, you will still get error 1698
You can use rows
and cols
:
cout << "Width : " << src.cols << endl;
cout << "Height: " << src.rows << endl;
or size()
:
cout << "Width : " << src.size().width << endl;
cout << "Height: " << src.size().height << endl;
Here are some popular MongoDB GUI administration tools:
dbKoda - cross-platform, tabbed editor with auto-complete, syntax highlighting and code formatting (plus auto-save, something Studio 3T doesn't support), visual tools (explain plan, real-time performance dashboard, query and aggregation pipeline builder), profiling manager, storage analyzer, index advisor, convert MongoDB commands to Node.js syntax etc. Lacks in-place document editing and the ability to switch themes.
Nosqlclient - multiple shell output tabs, autocomplete, schema analyzer, index management, user/role management, live monitoring, and other features. Electron/Meteor.js-based, actively developed on GitHub.
adminMongo - web-based or Electron app. Supports server monitoring and document editing.
find
queries against the database – all with zero knowledge of MongoDB's query language. Developed by MongoDB, Inc. No update
queries or access to the shell.Robo 3T – acquired by Studio 3T. A shell-centric cross-platform open source MongoDB management tool. Shell-related features only, e.g. multiple shells and results, autocomplete. No export/ import or other features are mentioned. Last commit: 2017-Jul-04
HumongouS.io – web-based interface with CRUD features, a chart builder and some collaboration capabilities. 14-day trial.
The second one is a classic example of the Arrow Anti-pattern So I'd avoid it...
If your conditions are too long extract them into methods/properties.
It is also (Transact-SQL) ... according to BOL.
-- exec sp_serveroption 'SERVER NAME', 'data access', 'true' --execute once
EXEC sp_primarykeys @table_server = N'server_name',
@table_name = N'table_name',
@table_catalog = N'db_name',
@table_schema = N'schema_name'; --frequently 'dbo'
For Windows 10:
Properties
./
not \
for path) as showed on the screenshot:PHP Folks:
print_r(preg_match('/^(?:[0-9A-F]{2}[:]?){5}(?:[0-9A-F]{2}?)$/i', '00:25:90:8C:B8:59'));
Need Explanation: http://regex101.com/r/wB0eT7
List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");
//lambda
//Output : A,B,C,D,E
items.forEach(item->System.out.println(item));
//Output : C
items.forEach(item->{
System.out.println(item);
System.out.println(item.toLowerCase());
}
});
In iOS7 I found that if I had a View inside a UIScrollView on a FreeForm-sized ViewController it would not scroll in the app, no matter what I did. I played around and found the following seemed to work, which uses no FreeForms:
Insert a UIScrollView inside the main View of a ViewController
Set the Autolayout constraints on the ScrollView as appropriate. For me I used 0 to Top Layout guide and 0 to Bottom layout Guide
Inside the ScrollView, place a Container View. Set its height to whatever you want (e.g. 1000)
Add a Height constraint (1000) to the Container so it doesn't resize. The bottom will be past the end of the form.
Add the line [self.scrollView setContentSize:CGSizeMake(320, 1000)]; to the ViewController that contains the scrollView (which you've hooked up as a IBOutlet)
The ViewController (automatically added) that is associated with the Container will have the desired height (1000) in Interface Builder and will also scroll properly in the original view controller. You can now use the container's ViewController to layout your controls.
to fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the
deserialized type so that it is a normal .NET type (e.g. not a primitive type like
integer, not a collection type like an array or List) that can be deserialized from a
JSON object.`
The whole message indicates that it is possible to serialize to a List object, but the input must be a JSON list. This means that your JSON must contain
"accounts" : [{<AccountObjectData}, {<AccountObjectData>}...],
Where AccountObject data is JSON representing your Account object or your Badge object
What it seems to be getting currently is
"accounts":{"github":"sergiotapia"}
Where accounts is a JSON object (denoted by curly braces), not an array of JSON objects (arrays are denoted by brackets), which is what you want. Try
"accounts" : [{"github":"sergiotapia"}]
Here's a simple approach:
$('.mybutton').click(function(){
/* Perform some button action ... */
alert("I don't like it when you press my button!");
/* Then, the most important part ... */
return false;
});
As @TechSpellBound suggested remove the quotes around the ? signs. Then add a space character at the end of each row in your concatenated string. Otherwise the entire query will be sent as (using only part of it as an example) : .... WHERE bookings.booking_end < date ?OR bookings.booking_start > date ?GROUP BY ....
The ?
and the OR
needs to be seperated by a space character. Do it wherever needed in the query string.
Thought I'd give a full answer combining some of the possible intricacies required for completeness.
w3wp.exe
. If it's showing as w3wp*32.exe
then it's 32-bit.Try my baby:
**
myApp.filter('inputSelected', function(){
return function(formData){
var keyArr = [];
var word = [];
Object.keys(formData).forEach(function(key){
if (formData[key]){
var keyCap = key.charAt(0).toUpperCase() + key.slice(1);
for (var char = 0; char<keyCap.length; char++ ) {
if (keyCap[char] == keyCap[char].toUpperCase()){
var spacedLetter = ' '+ keyCap[char];
word.push(spacedLetter);
}
else {
word.push(keyCap[char]);
}
}
}
keyArr.push(word.join(''))
word = [];
})
return keyArr.toString();
}
})
**
Then for any ng-model with checkboxes, it will return a string of all the input you selected:
<label for="Heard about ITN">How did you hear about ITN?: *</label><br>
<label class="checkbox-inline"><input ng-model="formData.heardAboutItn.brotherOrSister" type="checkbox" >Brother or Sister</label>
<label class="checkbox-inline"><input ng-model="formData.heardAboutItn.friendOrAcquaintance" type="checkbox" >Friend or Acquaintance</label>
{{formData.heardAboutItn | inputSelected }}
//returns Brother or Sister, Friend or Acquaintance
func Ternary(statement bool, a, b interface{}) interface{} {
if statement {
return a
}
return b
}
func Abs(n int) int {
return Ternary(n >= 0, n, -n).(int)
}
This will not outperform if/else and requires cast but works. FYI:
BenchmarkAbsTernary-8 100000000 18.8 ns/op
BenchmarkAbsIfElse-8 2000000000 0.27 ns/op
Try this if you unbind the onclick event by ID Then use:
$('#youLinkID').attr('onclick','').unbind('click');
Try this if you unbind the onclick event by Class Then use:
$('.className').attr('onclick','').unbind('click');
@DanielLittle has the easiest and most elegant answer to the specific question. However, if you are interested in converting to a specific timezone AND taking into account DST (Daylight Savings Time), the following works well:
CAST(DATEADD(S, [UnixTimestamp], '1970-01-01') AT TIME ZONE 'UTC' AT TIME ZONE 'Pacific Standard Time' AS Datetime)
Note: This solution only works on SQL Server 2016 and above (and Azure).
To create a function:
CREATE FUNCTION dbo.ConvertUnixTime (@input INT)
RETURNS Datetime
AS BEGIN
DECLARE @Unix Datetime
SET @Unix = CAST(DATEADD(S, @Input, '1970-01-01') AT TIME ZONE 'UTC' AT TIME ZONE 'Pacific Standard Time' AS Datetime)
RETURN @Unix
END
You can call the function like so:
SELECT dbo.ConvertUnixTime([UnixTimestamp])
FROM YourTable
A Subject
or Observable
doesn't have a current value. When a value is emitted, it is passed to subscribers and the Observable
is done with it.
If you want to have a current value, use BehaviorSubject
which is designed for exactly that purpose. BehaviorSubject
keeps the last emitted value and emits it immediately to new subscribers.
It also has a method getValue()
to get the current value.
In a pure Javascript way, you can submit the form after preventing default.
This is because HTMLFormElement.submit()
never calls the onSubmit()
. So we're relying on that specification oddity to submit the form as if it doesn't have a custom onsubmit handler here.
var submitHandler = (event) => {
event.preventDefault()
console.log('You should only see this once')
document.getElementById('formId').submit()
}
See this fiddle for a synchronous request.
Waiting for an async request to finish up is just as easy:
var submitHandler = (event) => {
event.preventDefault()
console.log('before')
setTimeout(function() {
console.log('done')
document.getElementById('formId').submit()
}, 1400);
console.log('after')
}
You can check out my fiddle for an example of an asynchronous request.
And if you are down with promises:
var submitHandler = (event) => {
event.preventDefault()
console.log('Before')
new Promise((res, rej) => {
setTimeout(function() {
console.log('done')
res()
}, 1400);
}).then(() => {
document.getElementById('bob').submit()
})
console.log('After')
}
And here's that request.
here is an example for right click context menu in javascript: Right Click Context Menu
Used raw javasScript Code for context menu functionality. Can you please check this, hope this will help you.
Live Code:
(function() {_x000D_
_x000D_
"use strict";_x000D_
_x000D_
_x000D_
/*********************************************** Context Menu Function Only ********************************/_x000D_
function clickInsideElement( e, className ) {_x000D_
var el = e.srcElement || e.target;_x000D_
if ( el.classList.contains(className) ) {_x000D_
return el;_x000D_
} else {_x000D_
while ( el = el.parentNode ) {_x000D_
if ( el.classList && el.classList.contains(className) ) {_x000D_
return el;_x000D_
}_x000D_
}_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
function getPosition(e) {_x000D_
var posx = 0, posy = 0;_x000D_
if (!e) var e = window.event;_x000D_
if (e.pageX || e.pageY) {_x000D_
posx = e.pageX;_x000D_
posy = e.pageY;_x000D_
} else if (e.clientX || e.clientY) {_x000D_
posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;_x000D_
posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;_x000D_
}_x000D_
return {_x000D_
x: posx,_x000D_
y: posy_x000D_
}_x000D_
}_x000D_
_x000D_
// Your Menu Class Name_x000D_
var taskItemClassName = "thumb";_x000D_
var contextMenuClassName = "context-menu",contextMenuItemClassName = "context-menu__item",contextMenuLinkClassName = "context-menu__link", contextMenuActive = "context-menu--active";_x000D_
var taskItemInContext, clickCoords, clickCoordsX, clickCoordsY, menu = document.querySelector("#context-menu"), menuItems = menu.querySelectorAll(".context-menu__item");_x000D_
var menuState = 0, menuWidth, menuHeight, menuPosition, menuPositionX, menuPositionY, windowWidth, windowHeight;_x000D_
_x000D_
function initMenuFunction() {_x000D_
contextListener();_x000D_
clickListener();_x000D_
keyupListener();_x000D_
resizeListener();_x000D_
}_x000D_
_x000D_
/**_x000D_
* Listens for contextmenu events._x000D_
*/_x000D_
function contextListener() {_x000D_
document.addEventListener( "contextmenu", function(e) {_x000D_
taskItemInContext = clickInsideElement( e, taskItemClassName );_x000D_
_x000D_
if ( taskItemInContext ) {_x000D_
e.preventDefault();_x000D_
toggleMenuOn();_x000D_
positionMenu(e);_x000D_
} else {_x000D_
taskItemInContext = null;_x000D_
toggleMenuOff();_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
/**_x000D_
* Listens for click events._x000D_
*/_x000D_
function clickListener() {_x000D_
document.addEventListener( "click", function(e) {_x000D_
var clickeElIsLink = clickInsideElement( e, contextMenuLinkClassName );_x000D_
_x000D_
if ( clickeElIsLink ) {_x000D_
e.preventDefault();_x000D_
menuItemListener( clickeElIsLink );_x000D_
} else {_x000D_
var button = e.which || e.button;_x000D_
if ( button === 1 ) {_x000D_
toggleMenuOff();_x000D_
}_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
/**_x000D_
* Listens for keyup events._x000D_
*/_x000D_
function keyupListener() {_x000D_
window.onkeyup = function(e) {_x000D_
if ( e.keyCode === 27 ) {_x000D_
toggleMenuOff();_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* Window resize event listener_x000D_
*/_x000D_
function resizeListener() {_x000D_
window.onresize = function(e) {_x000D_
toggleMenuOff();_x000D_
};_x000D_
}_x000D_
_x000D_
/**_x000D_
* Turns the custom context menu on._x000D_
*/_x000D_
function toggleMenuOn() {_x000D_
if ( menuState !== 1 ) {_x000D_
menuState = 1;_x000D_
menu.classList.add( contextMenuActive );_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* Turns the custom context menu off._x000D_
*/_x000D_
function toggleMenuOff() {_x000D_
if ( menuState !== 0 ) {_x000D_
menuState = 0;_x000D_
menu.classList.remove( contextMenuActive );_x000D_
}_x000D_
}_x000D_
_x000D_
function positionMenu(e) {_x000D_
clickCoords = getPosition(e);_x000D_
clickCoordsX = clickCoords.x;_x000D_
clickCoordsY = clickCoords.y;_x000D_
menuWidth = menu.offsetWidth + 4;_x000D_
menuHeight = menu.offsetHeight + 4;_x000D_
_x000D_
windowWidth = window.innerWidth;_x000D_
windowHeight = window.innerHeight;_x000D_
_x000D_
if ( (windowWidth - clickCoordsX) < menuWidth ) {_x000D_
menu.style.left = (windowWidth - menuWidth)-0 + "px";_x000D_
} else {_x000D_
menu.style.left = clickCoordsX-0 + "px";_x000D_
}_x000D_
_x000D_
// menu.style.top = clickCoordsY + "px";_x000D_
_x000D_
if ( Math.abs(windowHeight - clickCoordsY) < menuHeight ) {_x000D_
menu.style.top = (windowHeight - menuHeight)-0 + "px";_x000D_
} else {_x000D_
menu.style.top = clickCoordsY-0 + "px";_x000D_
}_x000D_
}_x000D_
_x000D_
_x000D_
function menuItemListener( link ) {_x000D_
var menuSelectedPhotoId = taskItemInContext.getAttribute("data-id");_x000D_
console.log('Your Selected Photo: '+menuSelectedPhotoId)_x000D_
var moveToAlbumSelectedId = link.getAttribute("data-action");_x000D_
if(moveToAlbumSelectedId == 'remove'){_x000D_
console.log('You Clicked the remove button')_x000D_
}else if(moveToAlbumSelectedId && moveToAlbumSelectedId.length > 7){_x000D_
console.log('Clicked Album Name: '+moveToAlbumSelectedId);_x000D_
}_x000D_
toggleMenuOff();_x000D_
}_x000D_
initMenuFunction();_x000D_
_x000D_
})();
_x000D_
/* For Body Padding and content */_x000D_
body { padding-top: 70px; }_x000D_
li a { text-decoration: none !important; }_x000D_
_x000D_
/* Thumbnail only */_x000D_
.thumb {_x000D_
margin-bottom: 30px;_x000D_
}_x000D_
.thumb:hover a, .thumb:active a, .thumb:focus a {_x000D_
border: 1px solid purple;_x000D_
}_x000D_
_x000D_
/************** For Context menu ***********/_x000D_
/* context menu */_x000D_
.context-menu { display: none; position: absolute; z-index: 9999; padding: 12px 0; width: 200px; background-color: #fff; border: solid 1px #dfdfdf; box-shadow: 1px 1px 2px #cfcfcf; }_x000D_
.context-menu--active { display: block; }_x000D_
_x000D_
.context-menu__items { list-style: none; margin: 0; padding: 0; }_x000D_
.context-menu__item { display: block; margin-bottom: 4px; }_x000D_
.context-menu__item:last-child { margin-bottom: 0; }_x000D_
.context-menu__link { display: block; padding: 4px 12px; color: #0066aa; text-decoration: none; }_x000D_
.context-menu__link:hover { color: #fff; background-color: #0066aa; }_x000D_
.context-menu__items ul { position: absolute; white-space: nowrap; z-index: 1; left: -99999em;}_x000D_
.context-menu__items > li:hover > ul { left: auto; padding-top: 5px ; min-width: 100%; }_x000D_
.context-menu__items > li li ul { border-left:1px solid #fff;}_x000D_
.context-menu__items > li li:hover > ul { left: 100%; top: -1px; }_x000D_
.context-menu__item ul { background-color: #ffffff; padding: 7px 11px; list-style-type: none; text-decoration: none; margin-left: 40px; }_x000D_
.page-media .context-menu__items ul li { display: block; }_x000D_
/************** For Context menu ***********/
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<body>_x000D_
_x000D_
_x000D_
_x000D_
<!-- Page Content -->_x000D_
<div class="container">_x000D_
_x000D_
<div class="row">_x000D_
_x000D_
<div class="col-lg-12">_x000D_
<h1 class="page-header">Thumbnail Gallery <small>(Right click to see the context menu)</small></h1>_x000D_
</div>_x000D_
_x000D_
<div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
<a class="thumbnail" href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
</a>_x000D_
</div>_x000D_
<div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
<a class="thumbnail" href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
</a>_x000D_
</div>_x000D_
<div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
<a class="thumbnail" href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
</a>_x000D_
</div>_x000D_
<div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
<a class="thumbnail" href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
</a>_x000D_
</div>_x000D_
<div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
<a class="thumbnail" href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
</a>_x000D_
</div>_x000D_
<div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
<a class="thumbnail" href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
</a>_x000D_
</div>_x000D_
<div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
<a class="thumbnail" href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
</a>_x000D_
</div>_x000D_
<div class="col-lg-3 col-md-4 col-xs-6 thumb">_x000D_
<a class="thumbnail" href="#">_x000D_
<img class="img-responsive" src="http://placehold.it/400x300" alt="">_x000D_
</a>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
<hr>_x000D_
_x000D_
_x000D_
</div>_x000D_
<!-- /.container -->_x000D_
_x000D_
_x000D_
<!-- / The Context Menu -->_x000D_
<nav id="context-menu" class="context-menu">_x000D_
<ul class="context-menu__items">_x000D_
<li class="context-menu__item">_x000D_
<a href="#" class="context-menu__link" data-action="Delete This Photo"><i class="fa fa-empire"></i> Delete This Photo</a>_x000D_
</li>_x000D_
<li class="context-menu__item">_x000D_
<a href="#" class="context-menu__link" data-action="Photo Option 2"><i class="fa fa-envira"></i> Photo Option 2</a>_x000D_
</li>_x000D_
<li class="context-menu__item">_x000D_
<a href="#" class="context-menu__link" data-action="Photo Option 3"><i class="fa fa-first-order"></i> Photo Option 3</a>_x000D_
</li>_x000D_
<li class="context-menu__item">_x000D_
<a href="#" class="context-menu__link" data-action="Photo Option 4"><i class="fa fa-gitlab"></i> Photo Option 4</a>_x000D_
</li>_x000D_
<li class="context-menu__item">_x000D_
<a href="#" class="context-menu__link" data-action="Photo Option 5"><i class="fa fa-ioxhost"></i> Photo Option 5</a>_x000D_
</li>_x000D_
<li class="context-menu__item">_x000D_
<a href="#" class="context-menu__link"><i class="fa fa-arrow-right"></i> Add Photo to</a>_x000D_
<ul>_x000D_
<li><a href="#!" class="context-menu__link" data-action="album-one"><i class="fa fa-camera-retro"></i> Album One</a></li>_x000D_
<li><a href="#!" class="context-menu__link" data-action="album-two"><i class="fa fa-camera-retro"></i> Album Two</a></li>_x000D_
<li><a href="#!" class="context-menu__link" data-action="album-three"><i class="fa fa-camera-retro"></i> Album Three</a></li>_x000D_
<li><a href="#!" class="context-menu__link" data-action="album-four"><i class="fa fa-camera-retro"></i> Album Four</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</nav>_x000D_
_x000D_
<!-- End # Context Menu -->_x000D_
_x000D_
_x000D_
</body>
_x000D_
It's also important to put
table-layout:fixed;
Onto the containing table, so it operates well in IE9 (if your utilize max-width) as well.
Another difference, I didn't see here:
Bubble sort has 3 value assignments per swap: you have to build a temporary variable first to save the value you want to push forward(no.1), than you have to write the other swap-variable into the spot you just saved the value of(no.2) and then you have to write your temporary variable in the spot other spot(no.3). You have to do that for each spot - you want to go forward - to sort your variable to the correct spot.
With insertion sort you put your variable to sort in a temporary variable and then put all variables in front of that spot 1 spot backwards, as long as you reach the correct spot for your variable. That makes 1 value assignement per spot. In the end you write your temp-variable into the the spot.
That makes far less value assignements, too.
This isn't the strongest speed-benefit, but i think it can be mentioned.
I hope, I expressed myself understandable, if not, sorry, I'm not a nativ Britain
Java is not call by reference it is call by value only
But all variables of object type are actually pointers.
So if you use a Mutable Object you will see the behavior you want
public class XYZ {
public static void main(String[] arg) {
StringBuilder toyNumber = new StringBuilder("5");
play(toyNumber);
System.out.println("Toy number in main " + toyNumber);
}
private static void play(StringBuilder toyNumber) {
System.out.println("Toy number in play " + toyNumber);
toyNumber.append(" + 1");
System.out.println("Toy number in play after increement " + toyNumber);
}
}
Output of this code:
run:
Toy number in play 5
Toy number in play after increement 5 + 1
Toy number in main 5 + 1
BUILD SUCCESSFUL (total time: 0 seconds)
You can see this behavior in Standard libraries too. For example Collections.sort(); Collections.shuffle(); These methods does not return a new list but modifies it's argument object.
List<Integer> mutableList = new ArrayList<Integer>();
mutableList.add(1);
mutableList.add(2);
mutableList.add(3);
mutableList.add(4);
mutableList.add(5);
System.out.println(mutableList);
Collections.shuffle(mutableList);
System.out.println(mutableList);
Collections.sort(mutableList);
System.out.println(mutableList);
Output of this code:
run:
[1, 2, 3, 4, 5]
[3, 4, 1, 5, 2]
[1, 2, 3, 4, 5]
BUILD SUCCESSFUL (total time: 0 seconds)
There is really quite a number of ways to do this and all of the above are in one way or another valid approaches... Let me add a straightforward proposition. So assuming your current existing json file looks is this....
{
"name":"myname"
}
And you want to bring in this new json content (adding key "id")
{
"id": "134",
"name": "myname"
}
My approach has always been to keep the code extremely readable with easily traceable logic. So first, we read the entire existing json file into memory, assuming you are very well aware of your json's existing key(s).
import json
# first, get the absolute path to json file
PATH_TO_JSON = 'data.json' # assuming same directory (but you can work your magic here with os.)
# read existing json to memory. you do this to preserve whatever existing data.
with open(PATH_TO_JSON,'r') as jsonfile:
json_content = json.load(jsonfile) # this is now in memory! you can use it outside 'open'
Next, we use the 'with open()' syntax again, with the 'w' option. 'w' is a write mode which lets us edit and write new information to the file. Here s the catch that works for us ::: any existing json with the same target write name will be erased automatically.
So what we can do now, is simply write to the same filename with the new data
# add the id key-value pair (rmbr that it already has the "name" key value)
json_content["id"] = "134"
with open(PATH_TO_JSON,'w') as jsonfile:
json.dump(json_content, jsonfile, indent=4) # you decide the indentation level
And there you go! data.json should be good to go for an good old POST request
Here's my solution using only Graph API Explorer & Access Token Debugger:
(Tested with API Version 2.9-2.11, 3.0-3.1)
This kind of example for class var. Don't include the name of bundle.
extension NSObject {
class var className: String {
return "\(self)"
}
}
I had the same problem on angular when switching page. I had to add this code before leaving the page to make it works:
$scope.$on('$locationChangeStart', function( event ) {
if(map != undefined)
{
map.remove();
map = undefined
document.getElementById('mapLayer').innerHTML = "";
}
});
Without document.getElementById('mapLayer').innerHTML = ""
the map was not displayed on the next page.
If I understand you correctly, you want to list to exclude duplicates on one column only, inner join to a sub-select
select u.* [whatever joined values]
from users u
inner join
(select name from users group by name having count(*)=1) uniquenames
on uniquenames.name = u.name
OK. If you don't want to use the correct way ng-options
, you can add ng-selected
attribute with a condition check logic for the option
directive to to make the pre-select work.
<select ng-model="filterCondition.operator">
<option ng-selected="{{operator.value == filterCondition.operator}}"
ng-repeat="operator in operators"
value="{{operator.value}}">
{{operator.displayName}}
</option>
</select>
This question is very helpfully BUT Don't forget to mount SD Card in your emulator, if you don't do this its doesn't work.
I lose my time before discover this.
Some time ago I've wrote library that might be useful for you. It allows you to have local and global listeners, multiple different ways of registering them, execution priority and so on.
from pyeventdispatcher import register
register("foo.bar", lambda event: print("second"))
register("foo.bar", lambda event: print("first "), -100)
dispatch(Event("foo.bar", {"id": 1}))
# first second
Have a look pyeventdispatcher
Here comes Linq:
var listItem = list.Single(i => i.Title == title);
It throws an exception if there's no item matching the predicate. Alternatively, there's SingleOrDefault
.
If you want a collection of items matching the title, there's:
var listItems = list.Where(i => i.Title == title);
Use the in
keyword.
if 'apples' in d:
if d['apples'] == 20:
print('20 apples')
else:
print('Not 20 apples')
If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get
function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None
instead):
if d.get('apples', 0) == 20:
print('20 apples.')
else:
print('Not 20 apples.')
The easier way is through the web management console:
Once you have an image you can launch another cloned instance, data and all. :)
You can use the extract() function
Drupal use it, in its theme() function.
Here it is a render function with a $variables
argument.
function includeWithVariables($filePath, $variables = array(), $print = true)
{
$output = NULL;
if(file_exists($filePath)){
// Extract the variables to a local namespace
extract($variables);
// Start output buffering
ob_start();
// Include the template file
include $filePath;
// End buffering and return its contents
$output = ob_get_clean();
}
if ($print) {
print $output;
}
return $output;
}
./index.php :
includeWithVariables('header.php', array('title' => 'Header Title'));
./header.php :
<h1><?php echo $title; ?></h1>
Html.Hidden and Html.HiddenFor used to generate name-value pairs which waited by action method in controller. Sample Usage(*):
@using (Html.BeginForm("RemoveFromCart", "Cart")) {
@Html.Hidden("ProductId", line.Product.ProductID)
@Html.HiddenFor(x => x.ReturnUrl)
<input class="btn btn-sm btn-warning"
type="submit" value="Remove" />
}
If your action method wait for "ProductId" you have to generate this name in form via using (Html.Hidden or Html.HiddenFor) For the case it is not possible to generate this name with strongly typed model you simple write this name with a string thats "ProductId".
public ViewResult RemoveFromCart(int productId, string returnUrl){...}
If I had written Html.HiddenFor(x => line.Product.ProductID), the helper would render a hidden field with the name "line.Product.ProductID". The name of the field would not match the names of the parameters for the "RemoveFromCart" action method which waiting the name of "ProductId". This would prevent the default model binders from working, so the MVC Framework would not be able to call the method.
*Adam Freeman (Apress - Pro ASP.Net MVC 5)
Based on Ivan Laharnar with less code and simplier:
declare
lastSeq number;
begin
SELECT MAX(ID) + 1 INTO lastSeq FROM <TABLE_NAME>;
if lastSeq IS NULL then lastSeq := 1; end if;
execute immediate 'CREATE SEQUENCE <SEQUENCE_NAME> INCREMENT BY 1 START WITH ' || lastSeq || ' MAXVALUE 999999999 MINVALUE 1 NOCACHE';
end;
I think I encountered the same problem as you. I addressed this problem with the following steps:
1) Go to Google Developers Console
2) Set JavaScript origins:
3) Set Redirect URIs:
I don't have enough reputation points to comment but for those who are having problems with getting "unrecognized" when they try using Maciej Gurban's ResponsiveToolKit, I was also getting that error until I noticed that Maciej actually references the toolkit from the bottom of the page in his CodePen
I tried doing that and suddenly it worked ! So, use the ResponsiveToolkit but put your links in the bottom of the page:
I don't know why it makes a difference but it does.
Just give full path to exclusion file: eg..
-- no - - - - -xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt
correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\list-of-excluded-files.txt
In this example the file would be located " C:\list-of-excluded-files.txt "
or...
correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\mybatch\list-of-excluded-files.txt
In this example the file would be located " C:\mybatch\list-of-excluded-files.txt "
Full path fixes syntax error.
The current selected solution appears to have misunderstood the problem.
The trick is to neither use absolute nor fixed positioning. Instead, have the close button outside of the div with its position set to relative and a left float so that it is immediately right of the div. Next, set a negative left margin and a positive z index so that it appears above the div.
Here's an example:
#close
{
position: relative;
float: left;
margin-top: 50vh;
margin-left: -100px;
z-index: 2;
}
#dialog
{
height: 100vh;
width: 100vw;
position: relative;
overflow: scroll;
float: left;
}
<body>
<div id="dialog">
****
</div>
<div id="close"> </div>
</body>
You can pip install pickle by running command pip install pickle-mixin
.
Proceed to import it using import pickle
.
This can be then used normally.
If you are aware of bootstrap you can do it easily by using 'flex' property.All you need to do is pass below css properties to parent div
.homepageSection {
overflow: hidden;
height: auto;
display: flex;
flex-flow: row;
}
where .homepageSection
is my parent div.
Now add child div in your html as
<div class="abc col-md-6">
<div class="abc col-md-6">
where abc is my child div.You can check equality of height in both child div irrespective of border just by giving border to child div
It's also possible to use jQuery's .load()
$('#submitform').click(function() {
$('#showresults').load('getinfo.asp #showresults', {
txtsearch: $('#appendedInputButton').val()
}, function() {
// alert('Load was performed.')
// $('#showresults').slideDown('slow')
});
});
unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.
We could modify the example above to use only part of the document that is fetched:
$( "#result" ).load( "ajax/test.html #container" );
When this method executes, it retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.
HTML
<a href="#top">Top</a>
<a href="#middle">Middle</a>
<a href="#bottom">Bottom</a>
<div id="top"><a href="top"></a>Top</div>
<div id="middle"><a href="middle"></a>Middle</div>
<div id="bottom"><a href="bottom"></a>Bottom</div>
CSS
#top,#middle,#bottom{
height: 600px;
width: 300px;
background: green;
}
Example http://jsfiddle.net/x4wDk/
you can float: left for all of them and set the width to 33.333%
All the solutions here are correct,but they are missing an important scenario in which the method Clear() is used, which doesn't provide OldItems
in the NotifyCollectionChangedEventArgs
object.
this is the perfect ObservableCollection
.
public delegate void ListedItemPropertyChangedEventHandler(IList SourceList, object Item, PropertyChangedEventArgs e);
public class ObservableCollectionEX<T> : ObservableCollection<T>
{
#region Constructors
public ObservableCollectionEX() : base()
{
CollectionChanged += ObservableCollection_CollectionChanged;
}
public ObservableCollectionEX(IEnumerable<T> c) : base(c)
{
CollectionChanged += ObservableCollection_CollectionChanged;
}
public ObservableCollectionEX(List<T> l) : base(l)
{
CollectionChanged += ObservableCollection_CollectionChanged;
}
#endregion
public new void Clear()
{
foreach (var item in this)
if (item is INotifyPropertyChanged i)
i.PropertyChanged -= Element_PropertyChanged;
base.Clear();
}
private void ObservableCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
foreach (var item in e.OldItems)
if (item != null && item is INotifyPropertyChanged i)
i.PropertyChanged -= Element_PropertyChanged;
if (e.NewItems != null)
foreach (var item in e.NewItems)
if (item != null && item is INotifyPropertyChanged i)
{
i.PropertyChanged -= Element_PropertyChanged;
i.PropertyChanged += Element_PropertyChanged;
}
}
}
private void Element_PropertyChanged(object sender, PropertyChangedEventArgs e) => ItemPropertyChanged?.Invoke(this, sender, e);
public ListedItemPropertyChangedEventHandler ItemPropertyChanged;
}
A Javascript version:
function subsetSum(numbers, target, partial) {_x000D_
var s, n, remaining;_x000D_
_x000D_
partial = partial || [];_x000D_
_x000D_
// sum partial_x000D_
s = partial.reduce(function (a, b) {_x000D_
return a + b;_x000D_
}, 0);_x000D_
_x000D_
// check if the partial sum is equals to target_x000D_
if (s === target) {_x000D_
console.log("%s=%s", partial.join("+"), target)_x000D_
}_x000D_
_x000D_
if (s >= target) {_x000D_
return; // if we reach the number why bother to continue_x000D_
}_x000D_
_x000D_
for (var i = 0; i < numbers.length; i++) {_x000D_
n = numbers[i];_x000D_
remaining = numbers.slice(i + 1);_x000D_
subsetSum(remaining, target, partial.concat([n]));_x000D_
}_x000D_
}_x000D_
_x000D_
subsetSum([3,9,8,4,5,7,10],15);_x000D_
_x000D_
// output:_x000D_
// 3+8+4=15_x000D_
// 3+5+7=15_x000D_
// 8+7=15_x000D_
// 5+10=15
_x000D_
Your declaration is int ttTreeInsert(int value);
However, your definition/implementation is
ttTree::ttTreeInsert(int value)
{
}
Notice that the return type int
is missing in the implementation. Instead it should be
int ttTree::ttTreeInsert(int value)
{
return 1; // or some valid int
}
If you scale 1600x900
to 1280x720
you have
scale_x = 1280.0/1600
scale_y = 720.0/900
Then you can use it to find button size, and button position
button_width = 300 * scale_x
button_height = 300 * scale_y
button_x = 1440 * scale_x
button_y = 860 * scale_y
If you scale 1280x720
to 1600x900
you have
scale_x = 1600.0/1280
scale_y = 900.0/720
and rest is the same.
I add .0
to value to make float
- otherwise scale_x
, scale_y
will be rounded to integer
- in this example to 0
(zero) (Python 2.x)
You can use the collate clause in a query (I can't find my example right now, so my syntax is probably wrong - I hope it points you in the right direction)
select sone_field collate SQL_Latin1_General_CP850_CI_AI
from table_1
inner join table_2
on (table_1.field collate SQL_Latin1_General_CP850_CI_AI = table_2.field)
where whatever
I use SQLite Database Browser for SQLite3 currently and it's pretty useful. Works across Windows/OS X/Linux and is lightweight and fast. Slightly unstable with executing SQL on the DB if it's incorrectly formatted.
Edit: I have recently discovered SQLite Manager, a plugin for Firefox. Obviously you need to run Firefox, but you can close all windows and just run it "standalone". It's very feature complete, amazingly stable and it remembers your databases! It has tonnes of features so I've moved away from SQLite Database Browser as the instability and lack of features is too much to bear.
To check version of cocoapods from terminal:
For Sudoless:
gem which cocoapods
For Sudo:
sudo gem which cocoapods
Also note: If you want to edit podfile or podfile.lock don't edit it in editors. Open only with XCode.
I am a Windows and XAMPP user. What works for me is adding extension=php_pdo_mysql.dll
in both php.ini
of XAMPP and php.ini
in C:\php\php.ini
.
Run this command in your cmd to know where your config file is
php -i | find /i "Configuration File
git clone
to clone your repository into a folder (say work). You should see a new subfolder, work/.git
.PS: Blow away the temporary folder.
There are (at least) two types of package dependencies you can indicate in your package.json files:
Those packages that are required in order to use your module are listed under the "dependencies" property. Using npm you can add those dependencies to your package.json file this way:
npm install --save packageName
Those packages required in order to help develop your module are listed under the "devDependencies" property. These packages are not necessary for others to use the module, but if they want to help develop the module, these packages will be needed. Using npm you can add those devDependencies to your package.json file this way:
npm install --save-dev packageName
Your module and your class AthleteList
have the same name. The line
import AthleteList
imports the module and creates a name AthleteList
in your current scope that points to the module object. If you want to access the actual class, use
AthleteList.AthleteList
In particular, in the line
return(AthleteList(templ.pop(0), templ.pop(0), templ))
you are actually accessing the module object and not the class. Try
return(AthleteList.AthleteList(templ.pop(0), templ.pop(0), templ))
Delete node folder completely from program file folder. Uninstall node.js and then reinstall it. change Path of environment variable PATH. delete .npmrc file from C:\users\yourusername
There are two main differences.
The first one is related to how you will access the relationship. For a unidirectional association, you can navigate the association from one end only.
So, for a unidirectional @ManyToOne
association, it means you can only access the relationship from the child side where the foreign key resides.
If you have a unidirectional @OneToMany
association, it means you can only access the relationship from the parent side which manages the foreign key.
For the bidirectional @OneToMany
association, you can navigate the association in both ways, either from the parent or from the child side.
You also need to use add/remove utility methods for bidirectional associations to make sure that both sides are properly synchronized.
The second aspect is related to performance.
@OneToMany
, unidirectional associations don't perform as well as bidirectional ones.@OneToOne
, a bidirectional association will cause the parent to be fetched eagerly if Hibernate cannot tell whether the Proxy should be assigned or a null value.@ManyToMany
, the collection type makes quite a difference as Sets
perform better than Lists
.in my case, i couldn't delete container created with nomad jobs,
there's no output for the docker logs <ContainerID>
and, in general, it looks like frozen.
until now the solution is: sudo service docker restart
, may someone suggest better one?
git reset c14809fafb08b9e96ff2879999ba8c807d10fb07
is what you're after...
You can simply handle the NO_DATA_FOUND
exception by setting your variable to NULL
. This way, only one query is required.
v_column my_table.column%TYPE;
BEGIN
BEGIN
select column into v_column from my_table where ...;
EXCEPTION
WHEN NO_DATA_FOUND THEN
v_column := NULL;
END;
... use v_column here
END;
/^\d+(\.\d{1,2})?$/
var regexp = /^\d+(\.\d{1,2})?$/;_x000D_
_x000D_
console.log("'.74' returns " + regexp.test('.74'));_x000D_
console.log("'7' returns " + regexp.test('7'));_x000D_
console.log("'10.5' returns " + regexp.test('10.5'));_x000D_
console.log("'115.25' returns " + regexp.test('115.25'));_x000D_
console.log("'1535.803' returns " + regexp.test('1535.803'));_x000D_
console.log("'153.14.5' returns " + regexp.test('153.14.5'));_x000D_
console.log("'415351108140' returns " + regexp.test('415351108140'));_x000D_
console.log("'415351108140.5' returns " + regexp.test('415351108140.5'));_x000D_
console.log("'415351108140.55' returns " + regexp.test('415351108140.55'));_x000D_
console.log("'415351108140.556' returns " + regexp.test('415351108140.556'));
_x000D_
/ /
: the beginning and end of the expression^
: whatever follows should be at the beginning of the string you're testing\d+
: there should be at least one digit( )?
: this part is optional\.
: here goes a dot\d{1,2}
: there should be between one and two digits here$
: whatever precedes this should be at the end of the string you're testingYou can use regexr.com or regex101.com for testing regular expressions directly in the browser!
You can set your cookie value containing expiry and get your expiry from cookie value.
// set
$expiry = time()+3600;
setcookie("mycookie", "mycookievalue|$expiry", $expiry);
// get
if (isset($_COOKIE["mycookie"])) {
list($value, $expiry) = explode("|", $_COOKIE["mycookie"]);
}
// Remember, some two-way encryption would be more secure in this case. See: https://github.com/qeremy/Cryptee
If you are adding new foreign key to an existing table and the columns are not null and not assigned default value, you will get this error,
Either you need to make it nullable
or assign default value
, or delete all the existing records
to solve it.
unset()
and initialization:unset($_POST);
$_POST = array();
Or in a single statement:
unset($_POST) ? $_POST = array() : $_POST = array();
But what is the reason you want to do this?
The method I prefer assigns an array of data to the combobox. Click on the body of your userform and change the "Click" event to "Initialize". Now the combobox will fill upon the initializing of the userform. I hope this helps.
Sub UserForm_Initialize()
ComboBox1.List = Array("1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", "1010")
End Sub
Thanks to @Dirk Lachowski for pointing me in the right direction. The solution isn't as elegant as I would have liked, but I got it working. Reading the spring docs, I can listen on the EmbeddedServletContainerInitializedEvent and get the port once the server is up and running. Here's what it looks like -
import org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class MyListener implements ApplicationListener<EmbeddedServletContainerInitializedEvent> {
@Override
public void onApplicationEvent(final EmbeddedServletContainerInitializedEvent event) {
int thePort = event.getEmbeddedServletContainer().getPort();
}
}
the whole if
should be enclosed in brackets and the or
operator is ||
an not !!
, so
if ((Type == 2 && PageCount == 0) || (Type == 2 && PageCount == '')) { ...
none of all above answers working good on my app
here is my working code
on your exit button:
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
ComponentName cn = intent.getComponent();
Intent mainIntent = IntentCompat.makeRestartActivityTask(cn);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
mainIntent.putExtra("close", true);
startActivity(mainIntent);
finish();
that code is to close any other activity and bring MainActivity on top now on your MainActivity:
if( getIntent().getBooleanExtra("close", false)){
finish();
}
I found This simpler yet powerful tutorial which uses the fileReader
Object. It simply creates an img element and, using the fileReader object, assigns its source attribute as the value of the form input
function previewFile() {_x000D_
var preview = document.querySelector('img');_x000D_
var file = document.querySelector('input[type=file]').files[0];_x000D_
var reader = new FileReader();_x000D_
_x000D_
reader.onloadend = function () {_x000D_
preview.src = reader.result;_x000D_
}_x000D_
_x000D_
if (file) {_x000D_
reader.readAsDataURL(file);_x000D_
} else {_x000D_
preview.src = "";_x000D_
}_x000D_
}
_x000D_
<input type="file" onchange="previewFile()"><br>_x000D_
<img src="" height="200" alt="Image preview...">
_x000D_
BLOB stores binary data which are more than 2 GB. Max size for BLOB is 4 GB. Binary data means unstructured data i.e images audio files vedio files digital signature
Text is used to store large string.
(Explanation in more details can be found in an archived Microsoft KB article.)
Three things to know:
%1
, %2
, ...Two percent signs with any characters in between them are interpreted as a variable:
echo %myvar%
%%f
Why's that?
For example, if we execute your (simplified) command line
FOR /f %f in ('dir /b .') DO somecommand %f
in a batch file, rule 2 would try to interpret
%f in ('dir /b .') DO somecommand %
as a variable. In order to prevent that, you have to apply rule 3 and escape the %
with an second %
:
FOR /f %%f in ('dir /b .') DO somecommand %%f
I was facing a similar issue when processing a huge csv file (6 million rows). I had three issues:
df = pd.read_csv(csv_file,sep=';', encoding = 'ISO-8859-1',
names=['permission','owner_name','group_name','size','ctime','mtime','atime','filename','full_filename'],
dtype={'permission':str,'owner_name':str,'group_name':str,'size':str,'ctime':object,'mtime':object,'atime':object,'filename':str,'full_filename':str,'first_date':object,'last_date':object})
try:
df['file_format'] = [Path(f).suffix[1:] for f in df.filename.tolist()]
except:
df['file_format'] = ''
A first stab at it seems to work for your particular case.
awk '{ f = $1; i = $NF; while (i <= 0); gsub(/^[A-Z][A-Z][ ][ ]/,""); print $i, f; }'
Well I was searching for an easy way. And find out on medium.
First to copy the json text and validate it on jsonlint or something similar. Then to copy from jsonlint, already the json is formatted. And paste the code on Xcode with preserving the format, shortcut shift + option + command + v
The at
command exists specifically for this purpose (unlike cron
which is intended for scheduling recurring tasks).
at $(cat file) </path/to/script
You can scale image that will also reduce the size of your image. There is a library for it you can download and use it. https://github.com/niraj124124/Images-Files-scale-and-compress.git
How to use 1)Import the compressor-v1.0. jar to your project. 2)Add the below sample code to test. ResizeLimiter resize = ImageResizer.build(); resize.scale("inputImagePath", "outputImagePath",imageWidth, imageHeight); Many more methods are there according to your requirement
strtok
is an overlooked function for this sort of thing. It is meant to be quite fast.
$s = '233718_This_is_a_string';
$firstPart = strtok( $s, '_' );
$allTheRest = strtok( '' );
Empty string like this will force the rest of the string to be returned.
NB if there was nothing at all after the '_' you would get a FALSE
value for $allTheRest
which, as stated in the documentation, must be tested with ===, to distinguish from other falsy values.
From version 4.x, only Android SDK 24+ is supported by default, and androidx is required.
Add the following to your build.gradle file:
repositories {
jcenter()
}
dependencies {
implementation 'com.journeyapps:zxing-android-embedded:4.1.0'
implementation 'androidx.appcompat:appcompat:1.0.2'
}
android {
buildToolsVersion '28.0.3' // Older versions may give compile errors
}
Older SDK versions
For Android SDK versions < 24, you can downgrade zxing:core to 3.3.0 or earlier for Android 14+ support:
repositories {
jcenter()
}
dependencies {
implementation('com.journeyapps:zxing-android-embedded:4.1.0') { transitive = false }
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'com.google.zxing:core:3.3.0'
}
android {
buildToolsVersion '28.0.3'
}
You'll also need this in your Android manifest:
<uses-sdk tools:overrideLibrary="com.google.zxing.client.android" />
Source : https://github.com/journeyapps/zxing-android-embedded
This is works for me
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp2
{
public static class AsyncHelper
{
private static readonly TaskFactory _myTaskFactory = new TaskFactory(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default);
public static void RunSync(Func<Task> func)
{
_myTaskFactory.StartNew(func).Unwrap().GetAwaiter().GetResult();
}
public static TResult RunSync<TResult>(Func<Task<TResult>> func)
{
return _myTaskFactory.StartNew(func).Unwrap().GetAwaiter().GetResult();
}
}
class SomeClass
{
public async Task<object> LoginAsync(object loginInfo)
{
return await Task.FromResult(0);
}
public object Login(object loginInfo)
{
return AsyncHelper.RunSync(() => LoginAsync(loginInfo));
//return this.LoginAsync(loginInfo).Result.Content;
}
}
class Program
{
static void Main(string[] args)
{
var someClass = new SomeClass();
Console.WriteLine(someClass.Login(1));
Console.ReadLine();
}
}
}
Check out ALL_TRIGGERS:
http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/statviews_2107.htm#i1592586
It's been a while since I read it (so, I'm not sure how much of it is still relevant), but my recollection is that Joe Celko's SQL for Smarties book provides a lot of info on writing elegant, effective, and efficient queries.
While doing "figure(1), figure(2),..." will solve the problem in most cases, it will not solve them in all cases. Suppose you have a bunch of MATLAB figures on your desktop and how many you have open varies from time to time before you run your code. Using the answers provided, you will overwrite these figures, which you may not want. The easy workaround is to just use the command "figure" before you plot.
Example: you have five figures on your desktop from a previous script you ran and you use
figure(1);
plot(...)
figure(2);
plot(...)
You just plotted over the figures on your desktop. However the code
figure;
plot(...)
figure;
plot(...)
just created figures 6 and 7 with your desired plots and left your previous plots 1-5 alone.
All XAMPP packages come with Multibyte String (php_mbstring.dll) extension installed.
If you have accidentally removed DLL file from php/ext
folder, just add it back (get the copy from XAMPP zip archive - its downloadable).
If you have deleted the accompanying INI configuration line from php.ini
file, add it back as well:
extension=php_mbstring.dll
Also, ensure to restart your webserver (Apache) using XAMPP control panel.
Additional Info on Enabling PHP Extensions
/XAMPP/php/ext
directory)extension_dir = "ext"
)Use In
instead of =
select * from dbo.books
where isbn in (select isbn from dbo.lending
where act between @fdate and @tdate
and stat ='close'
)
or you can use Exists
SELECT t1.*,t2.*
FROM books t1
WHERE EXISTS ( SELECT * FROM dbo.lending t2 WHERE t1.isbn = t2.isbn and
t2.act between @fdate and @tdate and t2.stat ='close' )
Check this link.. It will definitely solve your problem.. There are plenty of solutions to make cross domain GET Ajax calls BUT POST REQUEST FOR CROSS DOMAIN IS SOLVED HERE. It took me 3 days to figure it out.
I was getting this same error, in our case it was caused by a load balancer. We hade to make sure that the persistance was set to Source IP. Otherwise the login form was opened by one server, and processed by the other, which would fail to set the authentication cookie correctly. Maybe this helps someone else
Indeed, thanks to the comments to my post here, it looks like sparse directories are the way to go. I believe the following should do it:
svn checkout --depth empty http://svnserver/trunk/proj
svn update --set-depth infinity proj/foo
svn update --set-depth infinity proj/bar
svn update --set-depth infinity proj/baz
Alternatively, --depth immediates
instead of empty
checks out files and directories in trunk/proj
without their contents. That way you can see which directories exist in the repository.
As mentioned in @zigdon's answer, you can also do a non-recursive checkout. This is an older and less flexible way to achieve a similar effect:
svn checkout --non-recursive http://svnserver/trunk/proj
svn update trunk/foo
svn update trunk/bar
svn update trunk/baz
length
and dbms_lob.getlength
return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength
will return the number of bytes, which may differ from the number of characters in a multi-byte character set.
As the documentation doesn't specify what happens when you apply length
on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength
.
You can have a look on these built-in classes :
for (int i=0; i<dt_pattern.Rows.Count; i++)
{
DataRow dr = dt_pattern.Rows[i];
}
In the loop, you can now reference row i+1 (assuming there is an i+1)
Using AES or implementing AES? To use AES, there is the System.Security.Cryptography.RijndaelManaged class.
Uses the jquery prop() to clear the selected option
$('#mySelect option:selected').prop('selected', false);
Just call moment as a function without any arguments:
moment()
For timezone information with moment, look at the moment-timezone
package: http://momentjs.com/timezone/
Well, instead of passing Application.Current.MainWindow
, just pass a reference to whichever window it is you want: new WindowInteropHelper(this).Handle
and so on.
The accepted answer works for me only for the first 30 characters. This works for me:
select convert(varchar(max), convert(varbinary(max),myBlobColumn)) FROM table_name
LTRIM(RTRIM(FCT_TYP_CD)) & ') AND (' & LTRIM(RTRIM(DEP_TYP_ID)) & ')'
I think you're missing a )
on both of the trims. Some SQL versions support just TRIM which does both L and R trims...
Run this:
init = tf.global_variables_initializer()
sess.run(init)
Or (depending on the version of TF that you have):
init = tf.initialize_all_variables()
sess.run(init)
If I understand correctly the question, you want to have a JavaScript code in your Controller. (Your question is clear enough, but the voted and accepted answers are throwing some doubt)
So: you can do this by using the .NET's System.Windows.Forms.WebBrowser
control to execute javascript code, and everything that a browser can do. It requires reference to System.Windows.Forms though, and the interaction is somewhat "old school". E.g:
void webBrowser1_DocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
HtmlElement search = webBrowser1.Document.GetElementById("searchInput");
if(search != null)
{
search.SetAttribute("value", "Superman");
foreach(HtmlElement ele in search.Parent.Children)
{
if (ele.TagName.ToLower() == "input" && ele.Name.ToLower() == "go")
{
ele.InvokeMember("click");
break;
}
}
}
}
So probably nowadays, that would not be the easiest solution.
The other option is to use Javascript .NET or jint to run javasctipt, or another solution, based on the specific case.
Some related questions on this topic or possible duplicates:
Embedding JavaScript engine into .NET
Load a DOM and Execute javascript, server side, with .Net
Hope this helps.
I've found this code to detect if the device is in landscape orientation and in this case add a splash page saying "change orientation to see the site". It's working on iOS, android and windows phones. I think that this is very useful since it's quite elegant and avoid to set a landscape view for the mobile site. The code is working very well. The only thing not completely satisfying is that if someone load the page being in landscape view the splash page doesn't appears.
<script>
(function() {
'use strict';
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i);
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
if (isMobile.any()) {
doOnOrientationChange();
window.addEventListener('resize', doOnOrientationChange, 'false');
}
function doOnOrientationChange() {
var a = document.getElementById('alert');
var b = document.body;
var w = b.offsetWidth;
var h = b.offsetHeight;
(w / h > 1) ? (a.className = 'show', b.className = 'full-body') : (a.className = 'hide', b.className = '');
}
})();
</script>
And the HTML: <div id="alert" class="hide"> <div id="content">This site is not thought to be viewed in landscape mode, please turn your device </div> </div>
If you log in a web application using tomcat add:
-Djava.util.logging.ConsoleHandler.formatter = org.apache.juli.OneLineFormatter
On VM arguments
$a = array( 'one', 'two', 'three', 'four' );
$b = in_array( 'ONE', $a, false );
How about sed?
hour=`echo $hour|sed -e "s/^0*//g"`
You can use the classes found in the System.Json Namespace which were added in .NET 4.5. You need to add a reference to the System.Runtime.Serialization assembly
The JsonValue.Parse() Method parses JSON text and returns a JsonValue:
JsonValue value = JsonValue.Parse(@"{ ""name"":""Prince Charming"", ...");
If you pass a string with a JSON object, you should be able to cast the value to a JsonObject:
using System.Json;
JsonObject result = value as JsonObject;
Console.WriteLine("Name .... {0}", (string)result["name"]);
Console.WriteLine("Artist .. {0}", (string)result["artist"]);
Console.WriteLine("Genre ... {0}", (string)result["genre"]);
Console.WriteLine("Album ... {0}", (string)result["album"]);
The classes are quite similar to those found in the System.Xml.Linq Namespace.
In Javascript method names are camel case, so it's replace
, not Replace
:
$scope.newString = oldString.replace("stackover","NO");
Note that contrary to how the .NET Replace
method works, the Javascript replace
method replaces only the first occurrence if you are using a string as first parameter. If you want to replace all occurrences you need to use a regular expression so that you can specify the global (g) flag:
$scope.newString = oldString.replace(/stackover/g,"NO");
See this example.
Escape the quotes with backslashes:
printf("She said \"time flies like an arrow, but fruit flies like a banana\".");
There are special escape characters that you can use in string literals, and these are denoted with a leading backslash.
BigDataCloud also has a nice API for this, also for nodejs users.
they have API for client - free. But also for backend, using API_KEY (free according to quota).
the code looks like:
const client = require('@bigdatacloudapi/client')(API_KEY);
async foo() {
...
const location: string = await client.getReverseGeocode({
latitude:'32.101786566878445',
longitude: '34.858965073072056'
});
}
It is being answer long back but i have tried to do this in the following way to just avoid null pointer exception and may be useful for someone using C# null check operator ?.
//fragments is a list which can be null
fragments?.ForEach((obj) =>
{
//do something with obj
});
None of the above solutions worked for me.
But I noticed that of our five ASP.NET MVC projects in our main solution, four of them put the deployment package in the right place, while one left it under obj\Debug.
I compared the projects and found a discrepancy. The solution was to change this:
<Import
Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" />
to this:
<Import
Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets"
Condition="'$(VSToolsPath)' != ''" />
<Import
Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets"
Condition="false" />
After I made this change, all five projects put their deployment packages in the right spot.
(Sorry about the long lines, but I couldn't find a better way to condense them.)
here is a pure-javascript, minimalistic approach. I use JQuery but you can use any library (or even no libraries at all).
<html>
<head>
<title>An example</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function call_counter(url, pk) {
window.open(url);
$.get('YOUR_VIEW_HERE/'+pk+'/', function (data) {
alert("counter updated!");
});
}
</script>
</head>
<body>
<button onclick="call_counter('http://www.google.com', 12345);">
I update object 12345
</button>
<button onclick="call_counter('http://www.yahoo.com', 999);">
I update object 999
</button>
</body>
</html>
Alternative approach
Instead of placing the JavaScript code, you can change your link in this way:
<a target="_blank"
class="btn btn-info pull-right"
href="{% url YOUR_VIEW column_3_item.pk %}/?next={{column_3_item.link_for_item|urlencode:''}}">
Check It Out
</a>
and in your views.py
:
def YOUR_VIEW_DEF(request, pk):
YOUR_OBJECT.objects.filter(pk=pk).update(views=F('views')+1)
return HttpResponseRedirect(request.GET.get('next')))
For old Python (tested on 2.4) the top solution points the way. You can do this:
import string
def try_interp():
d = 1
f = 1.1
s = "s"
print string.Template("d: $d f: $f s: $s").substitute(**locals())
try_interp()
And you get
d: 1 f: 1.1 s: s
Seems to me like you want to create a property.
public int MyProperty
{
get { return _myProperty; }
set
{
_myProperty = value;
if (_myProperty == 1)
{
// DO SOMETHING HERE
}
}
}
private int _myProperty;
This allows you to run some code any time the property value changes. You could raise an event here, if you wanted.
select RTRIM(A.FIELD) from SCHEMA.TABLE A where RTRIM(A.FIELD) = ('10544175A')
UNION
select RTRIM(A.FIELD) from SCHEMA.TABLE A where RTRIM(A.FIELD) = ('10328189B')
UNION
select RTRIM(A.FIELD) from SCHEMA.TABLE A where RTRIM(A.FIELD) = ('103498732H')
I had the same problem and this is my solution. I had the following code:
se.GiftDescription = rs.getString(1);
se.GiftAmount = rs.getInt(2);
And I changed it to:
se.GiftDescription = rs.getString("DESCRIPTION");
se.GiftAmount = rs.getInt("AMOUNT");
And the problem was, after I restarted my PC, the column positions changed. That's why I got this error.
Yes. This should work on all major browsers.
This is a barebones look at what I've done to float one image over another.
img {_x000D_
position: absolute;_x000D_
top: 25px;_x000D_
left: 25px;_x000D_
}_x000D_
.imgA1 {_x000D_
z-index: 1;_x000D_
}_x000D_
.imgB1 {_x000D_
z-index: 3;_x000D_
}
_x000D_
<img class="imgA1" src="https://placehold.it/200/333333">_x000D_
<img class="imgB1" src="https://placehold.it/100">
_x000D_
Try this
<input type="text" style="font-size:18pt;height:420px;width:200px;">
Or else
<input type="text" id="txtbox">
with the css:
#txtbox
{
font-size:18pt;
height:420px;
width:200px;
}
UIImageView* animatedImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
animatedImageView.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:@"image1.gif"],
[UIImage imageNamed:@"image2.gif"],
[UIImage imageNamed:@"image3.gif"],
[UIImage imageNamed:@"image4.gif"], nil];
animatedImageView.animationDuration = 1.0f;
animatedImageView.animationRepeatCount = 0;
[animatedImageView startAnimating];
[self.view addSubview: animatedImageView];
You can load more than one gif images.
You can split your gif using the following ImageMagick command:
convert +adjoin loading.gif out%d.gif
I add new environment variable "ANDROID_SDK_HOME" and set it, like my path to android SDK folder (c:/Android) and it's work!
Use ToString()
with this format:
12345.678901.ToString("0.0000"); // outputs 12345.6789
12345.0.ToString("0.0000"); // outputs 12345.0000
Put as much zero as necessary at the end of the format.
I already said that I was new to exec()
function. After doing some more digging, I came upon 2>&1
which needs to be added at the end of command in exec()
.
Thanks @mattosmat
for pointing it out in the comments too. I did not try this at once because you said it is a Linux command, I am on Windows.
So, what I have discovered, the command is actually executing in the back-end. That is why I could not see it actually running, which I was expecting to happen.
For all of you, who had similar problem, my advise is to use that command. It will point out all the errors and also tell you info/details about execution.
exec('some_command 2>&1', $output);
print_r($output); // to see the response to your command
Thanks for all the help guys, I appreciate it ;)
Update: since the answer from @r2evans, it is much easier to insert images into R Markdown and control the size of the image.
The bookdown book does a great job of explaining that the best way to include images is by using include_graphics()
. For example, a full width image can be printed with a caption below:
```{r pressure, echo=FALSE, fig.cap="A caption", out.width = '100%'}
knitr::include_graphics("temp.png")
```
The reason this method is better than the pandoc approach ![your image](path/to/image)
:
fig.width
), the output width in the report (out.width
), add captions (fig.cap
) etc.knitr::kable()
is the best way to include tables in an R Markdown report as explained fully here. Again, this function is intelligent in automatically selecting the correct formatting for the output selected.
```{r table}
knitr::kable(mtcars[1:5,, 1:5], caption = "A table caption")
```
If you want to make your own simple tables in R Markdown and are using R Studio, you can check out the insert_table
package. It provides a tidy graphical interface for making tables.
Achieving custom styling of the table column width is beyond the scope of knitr
, but the kableExtra
package has been written to help achieve this: https://cran.r-project.org/web/packages/kableExtra/index.html
The R Markdown cheat sheet is still the best place to learn about most the basic syntax you can use.
If you are looking for potential extensions to the formatting, the bookdown
package is also worth exploring. It provides the ability to cross-reference, create special headers and more: https://bookdown.org/yihui/bookdown/markdown-extensions-by-bookdown.html
I just added float:left
to div and it worked
Inline elements:
Block elements:
Inline-block elements:
From W3Schools:
An inline element has no line break before or after it, and it tolerates HTML elements next to it.
A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.
An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.
When you visualize this, it looks like this:
The image is taken from this page, which also talks some more about this subject.
Local fonts linking to your react js may be a failure. So, I prefer to use online css file from google to link fonts. Refer the following code,
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
or
<style>
@import url('https://fonts.googleapis.com/css?family=Roboto');
</style>
Using calendar module:
Number-to-Abbr
calendar.month_abbr[month_number]
Abbr-to-Number
list(calendar.month_abbr).index(month_abbr)
If you can use java streams, you can try the following:
Random randomizeTimestamp = new Random();
Long min = ZonedDateTime.parse("2018-01-01T00:00:00.000Z").toInstant().toEpochMilli();
Long max = ZonedDateTime.parse("2019-01-01T00:00:00.000Z").toInstant().toEpochMilli();
randomizeTimestamp.longs(generatedEventListSize, min, max).forEach(timestamp -> {
System.out.println(timestamp);
});
This will generate numbers in the given range for longs.
ALTER TABLE <table name>
ADD <new column name> <data type> NOT NULL
GO
ALTER TABLE <table name>
ADD CONSTRAINT <constraint name> DEFAULT <default value> FOR <new column name>
GO
In my case I was using s3.getSignedUrl('getObject')
when I needed to be using s3.getSignedUrl('putObject')
(because I'm using a PUT to upload my file), which is why the signatures didn't match.
You might want to try open source tinybus. With it shake detection is as easy as this.
public class MainActivity extends Activity {
private Bus mBus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
// Create a bus and attach it to activity
mBus = TinyBus.from(this).wire(new ShakeEventWire());
}
@Subscribe
public void onShakeEvent(ShakeEvent event) {
Toast.makeText(this, "Device has been shaken",
Toast.LENGTH_SHORT).show();
}
@Override
protected void onStart() {
super.onStart();
mBus.register(this);
}
@Override
protected void onStop() {
mBus.unregister(this);
super.onStop();
}
}
It uses seismic for shake detection.
If you want to provide a timeout for a particular query, then CommandTimeout is the way forward.
Its usage is:
command.CommandTimeout = 60; //The time in seconds to wait for the command to execute. The default is 30 seconds.
The distinction between TO, CC and BCC occurs only in the text headers. At the SMTP level, everybody is a recipient.
TO - There is a TO: header with this recipient's address
CC - There is a CC: header with this recipient's address
BCC - This recipient isn't mentioned in the headers at all, but is still a recipient.
If you have
TO: [email protected]
CC: [email protected]
BCC: [email protected]
You have three recipients. The headers in the email body will include only the TO: and CC:
Some more:
Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25
Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B350 Safari/8536.25
String array[]=new String[]; and String array[]=new String[]{};
No difference,these are just different ways of declaring array
String array=new String[10]{}; got error why ?
This is because you can not declare the size of the array in this format.
right way is
String array[]=new String[]{"a","b"};
Get or set the length of vectors (including lists) and factors, and of any other R object for which a method has been defined.
Get the length of each element of a list or atomic vector (is.atomic) as an integer or numeric vector.
Split Method
data = input_string
df = pd.DataFrame([x.split(';') for x in data.split('\n')])
print(df)
At least in the current versions of PHPMailers, there's a function clearReplyTos() to empty the reply-to array.
$mail->ClearReplyTos();
$mail->addReplyTo([email protected], 'EXAMPLE');
While @Eli is quite correct that there usually isn't much of a need to do it, it is possible. savefig
takes a bbox_inches
argument that can be used to selectively save only a portion of a figure to an image.
Here's a quick example:
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')
ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')
# Save the full figure...
fig.savefig('full_figure.png')
# Save just the portion _inside_ the second axis's boundaries
extent = ax2.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)
# Pad the saved area by 10% in the x-direction and 20% in the y-direction
fig.savefig('ax2_figure_expanded.png', bbox_inches=extent.expanded(1.1, 1.2))
The full figure:
Area inside the second subplot:
Area around the second subplot padded by 10% in the x-direction and 20% in the y-direction:
Mysql has this handy UPDATE INTO command ;)
edit Looks like they renamed it to REPLACE
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted
The documentation on CREATE EVENT is quite good, but it takes a while to get it right.
You have two problems, first, making the event recur, second, making it run at 13:00 daily.
This example creates a recurring event.
CREATE EVENT e_hourly
ON SCHEDULE
EVERY 1 HOUR
COMMENT 'Clears out sessions table each hour.'
DO
DELETE FROM site_activity.sessions;
When in the command-line MySQL client, you can:
SHOW EVENTS;
This lists each event with its metadata, like if it should run once only, or be recurring.
The second problem: pointing the recurring event to a specific schedule item.
By trying out different kinds of expression, we can come up with something like:
CREATE EVENT IF NOT EXISTS `session_cleaner_event`
ON SCHEDULE
EVERY 13 DAY_HOUR
COMMENT 'Clean up sessions at 13:00 daily!'
DO
DELETE FROM site_activity.sessions;
There's no way to actively detect if there's a zoom. I found a good entry here on how you can attempt to implement it.
I’ve found two ways of detecting the zoom level. One way to detect zoom level changes relies on the fact that percentage values are not zoomed. A percentage value is relative to the viewport width, and thus unaffected by page zoom. If you insert two elements, one with a position in percentages, and one with the same position in pixels, they’ll move apart when the page is zoomed. Find the ratio between the positions of both elements and you’ve got the zoom level. See test case. http://web.archive.org/web/20080723161031/http://novemberborn.net/javascript/page-zoom-ff3
You could also do it using the tools of the above post. The problem is you're more or less making educated guesses on whether or not the page has zoomed. This will work better in some browsers than other.
There's no way to tell if the page is zoomed if they load your page while zoomed.
It worked for me:
Products.find({}).then(a => console.log(a.map(p => p.toJSON())))
also if you want use getters, you should add its option also (on defining schema):
new mongoose.Schema({...}, {toJSON: {getters: true}})
In ONLINE mode the new index is built while the old index is accessible to reads and writes. any update on the old index will also get applied to the new index. An antimatter column is used to track possible conflicts between the updates and the rebuild (ie. delete of a row which was not yet copied). See Online Index Operations. When the process is completed the table is locked for a brief period and the new index replaces the old index. If the index contains LOB columns, ONLINE operations are not supported in SQL Server 2005/2008/R2.
In OFFLINE mode the table is locked upfront for any read or write, and then the new index gets built from the old index, while holding a lock on the table. No read or write operation is permitted on the table while the index is being rebuilt. Only when the operation is done is the lock on the table released and reads and writes are allowed again.
Note that in SQL Server 2012 the restriction on LOBs was lifted, see Online Index Operations for indexes containing LOB columns.
Guys regarding time taken for importing huge files most importantly it takes more time is because default setting of mysql is "autocommit = true", you must set that off before importing your file and then check how import works like a gem...
First open MySQL:
mysql -u root -p
Then, You just need to do following :
mysql>use your_db
mysql>SET autocommit=0 ; source the_sql_file.sql ; COMMIT ;
I just wanted to share my input. I had this problem so my solution is this. This will convert lower units to higher units and vice versa just supply the argument toUnit
and fromUnit
export function fileSizeConverter(size: number, fromUnit: string, toUnit: string ): number | string {
const units: string[] = ['B', 'KB', 'MB', 'GB', 'TB'];
const from = units.indexOf(fromUnit.toUpperCase());
const to = units.indexOf(toUnit.toUpperCase());
const BASE_SIZE = 1024;
let result: number | string = 0;
if (from < 0 || to < 0 ) { return result = 'Error: Incorrect units'; }
result = from < to ? size / (BASE_SIZE ** to) : size * (BASE_SIZE ** from);
return result.toFixed(2);
}
I got the idea from here
hmm, try doing CAST(' ' AS TEXT) + [myText]
Although, i am not completely sure how this will pan out.
I also suggest against using the Text datatype, use varchar instead.
If that doesn't work, try ' ' + CAST ([myText] AS VARCHAR(255))
kotlin
fun spToPx(ctx: Context, sp: Float): Float {
return sp * ctx.resources.displayMetrics.scaledDensity
}
fun pxToDp(context: Context, px: Float): Float {
return px / context.resources.displayMetrics.density
}
fun dpToPx(context: Context, dp: Float): Float {
return dp * context.resources.displayMetrics.density
}
java
public static float spToPx(Context ctx,float sp){
return sp * ctx.getResources().getDisplayMetrics().scaledDensity;
}
public static float pxToDp(final Context context, final float px) {
return px / context.getResources().getDisplayMetrics().density;
}
public static float dpToPx(final Context context, final float dp) {
return dp * context.getResources().getDisplayMetrics().density;
}
with DataFrame: df_data
>>> df_data
id name value
0 a ampha 1
1 b beta 2
2 c ce 3
I tried:
>>> getattr(df_data, 'value').isin([1]).any()
True
>>> getattr(df_data, 'value').isin(['1']).any()
True
but:
>>> 1 in getattr(df_data, 'value')
True
>>> '1' in getattr(df_data, 'value')
False
So fun :D
Yes, this is a 'new style' object. It was a feature introduced in python2.2.
New style objects have a different object model to classic objects, and some things won't work properly with old style objects, for instance, super()
, @property
and descriptors. See this article for a good description of what a new style class is.
SO link for a description of the differences: What is the difference between old style and new style classes in Python?
Assuming the title of your question is correct and you want the time:
SELECT CONVERT(char,GETDATE(),14)
Edited to include millisecond.
I'm working on a similar problem right now. We have a hierarchichal directory structure and use image ids as filenames. For example, an image with id=1234567
is placed in
..../45/67/1234567_<...>.jpg
using last 4 digits to determine where the file goes.
With a few thousand images, you could use a one-level hierarchy. Our sysadmin suggested no more than couple of thousand files in any given directory (ext3) for efficiency / backup / whatever other reasons he had in mind.
Thanks for the direction from the above two answerers. James Thompson's suggestion worked best for Windows users.
Go to where your R program is installed. This is referred to as R_Home
in the literature. Once you find it, go to the /etc subdirectory.
C:\R\R-2.10.1\etc
Select the file in this folder named Rprofile.site. I open it with VIM. You will find this is a bare-bones file with less than 20 lines of code. I inserted the following inside the code:
# my custom library path
.libPaths("C:/R/library")
(The comment added to keep track of what I did to the file.)
In R, typing the .libPaths()
function yields the first target at C:/R/Library
NOTE: there is likely more than one way to achieve this, but other methods I tried didn't work for some reason.
FIXED IT!
I was losing my mind over this one. Reset firefox, tried safe mode, removed plugins, debugged using developers tools. All were to no avail and didn't get me any further with getting my online videos back to normal viewing condition. This however did the trick perfectly.
Within Firefox or whatever flavor of Firefox you have(CyberFox being my favorite choice here), simply browse to https://get.adobe.com/flashplayer/
VERIFY FIRST that the website detected you're using FireFox and has set your download for the flash player to be for Firefox.
Don't just click download. PLEASE PLEASE PLEASE SAVE YOURSELF the migraine and ALWAYS make sure that the middle section labeled "Optional offer:" is absolutely NOT CHECKED, it will be checked by default so always UNCHECK it before proceeding to download.
After it's finished downloading, close out of Firefox. Run the downloaded setup file As Administrator. It takes only a few seconds or so to complete, so after it's done, open up Firefox again and try viewing anything that was previously throwing this error. Should be back to normal now.
Enjoy!
To place the legend outside the plot area, use loc
and bbox_to_anchor
keywords of legend()
. For example, the following code will place the legend to the right of the plot area:
legend(loc="upper left", bbox_to_anchor=(1,1))
For more info, see the legend guide
This was my solution
#include <stdlib.h>
#include <stdarg.h>
char *strconcat(int num_args, ...) {
int strsize = 0;
va_list ap;
va_start(ap, num_args);
for (int i = 0; i < num_args; i++)
strsize += strlen(va_arg(ap, char*));
char *res = malloc(strsize+1);
strsize = 0;
va_start(ap, num_args);
for (int i = 0; i < num_args; i++) {
char *s = va_arg(ap, char*);
strcpy(res+strsize, s);
strsize += strlen(s);
}
va_end(ap);
res[strsize] = '\0';
return res;
}
but you need to specify how many strings you're going to concatenate
char *str = strconcat(3, "testing ", "this ", "thing");
None of the solutions above worked for me, I had to uninstall coacoapods, then installed a specific version before everything worked for me
sudo gem uninstall cocoapods
then
sudo gem install cocoapods -v 1.7.5
now even verbose shows progress
$ pod setup --verbose
Setting up CocoaPods master repo
Cloning spec repo `master` from `https://github.com/CocoaPods/Specs.git` (branch `master`)
$ /usr/bin/git clone https://github.com/CocoaPods/Specs.git --progress -- master
Cloning into 'master'...
remote: Enumerating objects: 295, done.
remote: Counting objects: 100% (295/295), done.
remote: Compressing objects: 100% (283/283), done.
Receiving objects: 20% (744493/3722462), 132.93 MiB | 567.00 KiB/s
Guid.NewGuid() will create one
I would suggest using conda. Conda is an anconda specific package manager. If you want to know more about conda, read the conda docs.
Using conda in the command line, the command below would install scipy 0.17.
conda install scipy=0.17.0
Edit your 'my-default.ini' file (by default it comes with commented properties)as below ie.
basedir=D:/D_Drive/mysql-5.6.20-win32
datadir=D:/D_Drive/mysql-5.6.20-win32/data
port=8888
There is very good article present that dictates commands to create user, browse tables etc ie.
http://www.ntu.edu.sg/home/ehchua/programming/sql/MySQL_HowTo.html#zz-3.1
select
isnull(column,'') column, *
from Table
Where column = ''
Both other answers are correct, but I thought it worth noting that the place where I got stuck was not realizing that you'll need order by the alias and make sure that the alias is the same for both the selects... so
select 'foo'
union
select item as `foo`
from myTable
order by `foo`
notice that I'm using single quotes in the first select but backticks for the others.
That will get you the sorting you need.
With the constructor:
// create a vector with 20 integer elements
std::vector<int> arr(20);
for(int x = 0; x < 20; ++x)
arr[x] = x;
There is no way in PostgreSQL to deconstruct a scalar JSON object. Thus, as you point out,
select length(to_json('Some "text"'::TEXT) ::TEXT);
is 15,
The trick is to convert the JSON into an array of one JSON element, then extract that element using ->>
.
select length( array_to_json(array[to_json('Some "text"'::TEXT)])->>0 );
will return 11.
Just to include one more alternative, you could also use this:
find "/starting/path" -type f -regextype posix-extended -regex "^.*\.(php|html|js)$" -exec grep -EH '(document\.cookie|setcookie)' {} \;
Where:
-regextype posix-extended
tells find
what kind of regex to expect-regex "^.*\.(php|html|js)$"
tells find
the regex itself filenames must match-exec grep -EH '(document\.cookie|setcookie)' {} \;
tells find
to run the command (with its options and arguments) specified between the -exec
option and the \;
for each file it finds, where {}
represents where the file path goes in this command.
while
E
option tells grep
to use extended regex (to support the parentheses) and...H
option tells grep
to print file paths before the matches.And, given this, if you only want file paths, you may use:
find "/starting/path" -type f -regextype posix-extended -regex "^.*\.(php|html|js)$" -exec grep -EH '(document\.cookie|setcookie)' {} \; | sed -r 's/(^.*):.*$/\1/' | sort -u
Where
|
[pipe] send the output of find
to the next command after this (which is sed
, then sort
) r
option tells sed
to use extended regex.s/HI/BYE/
tells sed
to replace every First occurrence (per line) of "HI" with "BYE" and...s/(^.*):.*$/\1/
tells it to replace the regex (^.*):.*$
(meaning a group [stuff enclosed by ()
] including everything [.*
= one or more of any-character] from the beginning of the line [^
] till' the first ':' followed by anything till' the end of line [$
]) by the first group [\1
] of the replaced regex.u
tells sort to remove duplicate entries (take sort -u
as optional)....FAR from being the most elegant way. As I said, my intention is to increase the range of possibilities (and also to give more complete explanations on some tools you could use).
XML Code:
<?xml version="1.0"?>
<company>
<staff id="1001">
<firstname>yong</firstname>
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary>100000</salary>
</staff>
<staff id="2001">
<firstname>low</firstname>
<lastname>yin fong</lastname>
<nickname>fong fong</nickname>
<salary>200000</salary>
</staff>
</company>
Java Code:
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
public class ReadXMLFile {
public static void main(String argv[]) {
try {
File fXmlFile = new File("/Users/mkyong/staff.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("staff");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Staff id : "
+ eElement.getAttribute("id"));
System.out.println("First Name : "
+ eElement.getElementsByTagName("firstname")
.item(0).getTextContent());
System.out.println("Last Name : "
+ eElement.getElementsByTagName("lastname")
.item(0).getTextContent());
System.out.println("Nick Name : "
+ eElement.getElementsByTagName("nickname")
.item(0).getTextContent());
System.out.println("Salary : "
+ eElement.getElementsByTagName("salary")
.item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
----------------
Root element :company
----------------------------
Current Element :staff
Staff id : 1001
First Name : yong
Last Name : mook kim
Nick Name : mkyong
Salary : 100000
Current Element :staff
Staff id : 2001
First Name : low
Last Name : yin fong
Nick Name : fong fong
Salary : 200000
I recommended you reading this: Normalization in DOM parsing with java - how does it work?
If you deleted a branch via Source Tree
, you could easily find the SHA1 of the deleted branch by going to View -> Show Command History
.
It should have the next format:
Deleting branch ...
...
Deleted branch %NAME% (was %SHA1%)
...
Then just follow the original answer.
git branch branchName <sha1>
Using ruby 2.4 you can do the same thing using transform_values
, this feature extracted from rails to ruby.
h = {a: 1, b: 2, c: 3}
h.transform_values { |v| v * 10 }
#=> {a: 10, b: 20, c: 30}
echo. 2>EmptyFile.txt
This code sends array of integer values
Initialize array List
List<Integer> test = new ArrayList<Integer>();
Add values to array List
test.add(1);
test.add(2);
test.add(3);
Intent intent=new Intent(this, targetActivty.class);
Send the array list values to target activity
intent.putIntegerArrayListExtra("test", (ArrayList<Integer>) test);
startActivity(intent);
here you get values on targetActivty
Intent intent=getIntent();
ArrayList<String> test = intent.getStringArrayListExtra("test");
You can use this:
//The color RGB #85CC4B
let newColor = UIColor(red: CGFloat(0x85)/255
,green: CGFloat(0xCC)/255
,blue: CGFloat(0x4B)/255
,alpha: 1.0)
as System environment Variable:
Windows:
Start -> type "envi" select environment variables and add a new:
Name: spring_profiles_active
Value: dev
(or whatever yours is)
Linux: add following line to /etc/environment under PATH:
spring_profiles_active=prod
(or whatever profile is)
then also export spring_profiles_active=prod
so you have it in the runtime now.
To improve on Johnny's answer, this can now be done using the public API as follows :
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let moreRowAction = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: "More", handler:{action, indexpath in
print("MORE•ACTION");
});
moreRowAction.backgroundColor = UIColor(red: 0.298, green: 0.851, blue: 0.3922, alpha: 1.0);
let deleteRowAction = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: "Delete", handler:{action, indexpath in
print("DELETE•ACTION");
});
return [deleteRowAction, moreRowAction];
}
To make a vertical line, just use a rectangle with width of 1dp:
<shape>
<size
android:width="1dp"
android:height="16dp" />
<solid
android:color="#c8cdd2" />
</shape>
Don't use stroke
, use solid
(which is the "fill" color) to specify the color of the line.
fmt.Sprintf("%v",value);
If you know the specific type of value use the corresponding formatter for example %d
for int
More info - fmt
I use this alert
function myFunction() {_x000D_
$('#passwordsNoMatchRegister').fadeIn(1000);_x000D_
setTimeout(function() { _x000D_
$('#passwordsNoMatchRegister').fadeOut(1000); _x000D_
}, 5000);_x000D_
}
_x000D_
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<button onclick="myFunction()">Try it</button> _x000D_
_x000D_
_x000D_
<div class="alert alert-danger" id="passwordsNoMatchRegister" style="display:none;">_x000D_
<strong>Error!</strong> Looks like the passwords you entered don't match!_x000D_
</div>_x000D_
_x000D_
_x000D_
_x000D_
@Override
public boolean onTouchEvent(MotionEvent event)
{
int x = (int)event.getX();
int y = (int)event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
}
return false;
}
The three cases are so that you can react to different types of events, in this example tapping or dragging or lifting the finger again.
Solved the problem by upgrading the dependency to below version
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>
Eloquent uses the query builder internally, so you can do:
$users = User::orderBy('name', 'desc')
->groupBy('count')
->having('count', '>', 100)
->get();
In my case I missed the compile tag in the .csproj file
<Compile Include="Global.asax.cs">
<DependentUpon>Global.asax</DependentUpon>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Compile>
The accepted answer here describes what ob_start()
does - not why it is used (which was the question asked).
As stated elsewhere ob_start()
creates a buffer which output is written to.
But nobody has mentioned that it is possible to stack multiple buffers within PHP. See ob_get_level().
As to the why....
Sending HTML to the browser in larger chunks gives a performance benefit from a reduced network overhead.
Passing the data out of PHP in larger chunks gives a performance and capacity benefit by reducing the number of context switches required
Passing larger chunks of data to mod_gzip/mod_deflate gives a performance benefit in that the compression can be more efficient.
buffering the output means that you can still manipulate the HTTP headers later in the code
explicitly flushing the buffer after outputting the [head]....[/head] can allow the browser to begin marshaling other resources for the page before HTML stream completes.
Capturing the output in a buffer means that it can redirected to other functions such as email, or copied to a file as a cached representation of the content
I was looking for a solution for this same problem, to create a list of logos.
I came up with this solution that uses a bit of flexbox, which works for us since we're not worried about old browsers.
This example assumes a 100x100px box but I'm pretty sure the size could be flexible/responsive.
.img__container {
display: flex;
padding: 15px 12px;
box-sizing: border-box;
width: 100px; height: 100px;
img {
margin: auto;
max-width: 100%;
max-height: 100%;
}
}
ps.: you may need to add some prefixes or use autoprefixer.
By using shuffle-array module you can shuffle your array . Here is a simple code of it .
var shuffle = require('shuffle-array'),
//collection = [1,2,3,4,5];
collection = ["a","b","c","d","e"];
shuffle(collection);
console.log(collection);
Hope this helps.
You have to use while
since foreach
does not know about index. Below is an example code.
int counter = 0;
string line;
Console.Write("Input your search text: ");
var text = Console.ReadLine();
System.IO.StreamReader file =
new System.IO.StreamReader("SampleInput1.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains(text))
{
break;
}
counter++;
}
Console.WriteLine("Line number: {0}", counter);
file.Close();
Console.ReadLine();
I'm guessing that when you enter a value into the totals field that value expression somehow gets overwritten.
However, you can take an alternative approach: Create a field for the total value and when either one
or two
changes update that field.
<li>Total <input type="text" ng-model="total">{{total}}</li>
And change the javascript:
function TodoCtrl($scope) {
$scope.$watch('one * two', function (value) {
$scope.total = value;
});
}
Example fiddle here.
They are technically the same thing, it's actually a different notation of using the provider
function of the $provide
service.
The only difference between the service
and the factory
notation is that the service is new-ed and the factory is not. But for everything else they both look, smell and behave the same. Again, it's just a shorthand for the $provide.provider function.
// Factory
angular.module('myApp').factory('myFactory', function() {
var _myPrivateValue = 123;
return {
privateValue: function() { return _myPrivateValue; }
};
});
// Service
function MyService() {
this._myPrivateValue = 123;
}
MyService.prototype.privateValue = function() {
return this._myPrivateValue;
};
angular.module('myApp').service('MyService', MyService);
Use:
string str = "Hello";
char[] characters = str.ToCharArray();
If you have a single character string, You can also try
string str = "A";
char character = char.Parse(str);
//OR
string str = "A";
char character = str.ToCharArray()[0];
FASTER: Bitwise instead of modulus.
select * from MEN where (id&1)=0;
Random question: Do you actually use uppercase table names? Usually uppercase is reserved for keywords. (By convention)
If the two
controller is nested in One
controller.
Then you can simply call:
$scope.parentmethod();
Angular will search for parentmethod
function starting with current scope and up until it will reach the rootScope
.
I'd use the different methods based on how I wanted to reference the items.
Use foreach if you just want the current item.
Use for if you need an indexer to do relative comparisons. (I.e. how does this compare to the previous/next item?)
I have never noticed a performance difference. I'd wait until having a performance issue before worrying about it.
CREATE TABLE #ListOfIDs (IDValue INT)
DECLARE @IDs VARCHAR(50), @ID VARCHAR(5)
SET @IDs = @OriginalListOfIDs + ','
WHILE LEN(@IDs) > 1
BEGIN
SET @ID = SUBSTRING(@IDs, 0, CHARINDEX(',', @IDs));
INSERT INTO #ListOfIDs (IDValue) VALUES(@ID);
SET @IDs = REPLACE(',' + @IDs, ',' + @ID + ',', '')
END
SELECT *
FROM #ListOfIDs
Moment.js
Install moment.js
from here.
npm : $ npm i --save moment
Bower : $ bower install --save moment
Next,
var date = moment()
.add(2,'d') //replace 2 with number of days you want to add
.toDate(); //convert it to a Javascript Date Object if you like
Link Ref : http://momentjs.com/docs/#/manipulating/add/
Moment.js
is an amazing Javascript library to manage Date objects and extremely light weight at 40kb
.
Good Luck.
Check for padding attribute if the issue still exists after changing theme.
Padding Issue creating a white space on top of fragment window / app window
Once you remove the padding - top value automatically the white space is removed.
I just updated matplotlib to 1.1.0 on my system and it now allows me to save to jpg with savefig
.
To upgrade to matplotlib 1.1.0 with pip
, use this command:
pip install -U 'http://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-1.1.0/matplotlib-1.1.0.tar.gz/download'
EDIT (to respond to comment):
pylab
is simply an aggregation of the matplotlib.pyplot and numpy namespaces (as well as a few others) jinto a single namespace.
On my system, pylab
is just this:
from matplotlib.pylab import *
import matplotlib.pylab
__doc__ = matplotlib.pylab.__doc__
You can see that pylab
is just another namespace in your matplotlib installation. Therefore, it doesn't matter whether or not you import it with pylab
or with matplotlib.pyplot
.
If you are still running into problem, then I'm guessing the macosx backend doesn't support saving plots to jpg. You could try using a different backend. See here for more information.
The way you are doing it is indeed the recommended one (for Python 2.x).
The issue of whether the class is passed explicitly to super
is a matter of style rather than functionality. Passing the class to super
fits in with Python's philosophy of "explicit is better than implicit".
Position your <div>
absolutely at the bottom and don't forget to give div.A
a position: relative
- http://jsfiddle.net/TTaMx/
.A {
position: relative;
margin: 40px 0;
height: 40px;
width: 200px;
background: #eee;
}
.A:after {
content: " ";
display: block;
background: #c00;
height: 29px;
width: 100%;
position: absolute;
bottom: -29px;
}?
Remove the \bin
, and also remove the ;
at the end. After restart the cmd and run.