_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d601 | train | For others who might find this thread, check out Mailpile. I haven't used it yet, it is a python-based mail client, and I am sure it could be modified to work as a webmail app as well.
A: You could try Quotient. It's a somewhat unusual webmail system, and it definitely won't fit into the same process as CherryPy - but it is in Python ;).
A: You can build one, using email for generating and parsing mail, imaplib for reading (and managing) incoming mail from your mail server, and smtplib for sending mail to the world.
A: Looking up webmail on pypi gives Posterity.
There is very probably some way to build a webmail with very little work using Zope3 components, or some other CMS.
I guess if you are writing a webapp, you are probably using one of the popular frameworks. We would need to know which one to give a more specific answer. | unknown | |
d602 | train | Try changing
15.12.2015 00:00:00
to
2015-12-15 00:00:00
and same format for the other date also.
A: You can view SQL Server's date and time format for yourself by running this query:
SELECT
GETDATE()
As you can see the format is YYYY-MM-DD HH:MM:SS.MMM. Stick to this and you won't run into any unexpected conversion errors.
EDIT
ISO 8601 is a standard date format. From MS Docs:
The advantage in using the ISO 8601 format is that it is an international standard with unambiguous specification. Also, this format isn't affected by the SET DATEFORMAT or SET LANGUAGE setting.
For this reason I would recommend it above all other formats. Examples:
2020-02-25
20200225
2020-02-25T18:37:00
A: SELECT CONVERT(char(10), GetDate(),126)
or
select convert(varchar,getDate(),112)
or
select replace(convert(varchar, getdate(), 111), '/','-')
Test out the queries above to get the date in the desired format (replace GetDate() with your date, or dateColumn).
As others pointed out you need the format YYYY-MM-DD.
A: Even though in Europe and everywhere in the world it makes perfect sense to use the month as the second of three items in the date. In the US and in this case, apparently, SQL's date time is MM.DD.YYYY, so you're going for the 15th month and 18th month
Therefore you should use
string query "SELECT * FROM LocalHotels WHERE city='LONDON' AND start <='12.15.2015 00:00:00' AND deadline >='12.18.2015 00:00:00' ORDER BY city"
or
string query "SELECT * FROM LocalHotels WHERE city='LONDON' AND start <='2015-12-15' AND deadline >='2015-12-18' ORDER BY city" | unknown | |
d603 | train | What is the autoResizingMask of the view set to?
Try this when you initialize the table view.
self.myTable.autoresizingMask = UIViewAutoresizingFlexibleHeight;
This will cause the table view to be resized with its parent view.
A: You can't change self.view.frame. You should have a container view above self.view that holds self.myTable and all other controls you want. self.myTable and other controls should have the correct autoresizingMask.
When keyboard is shown, you resize the container view and all other views will respect their autoresizingMasks.
-(void )keyboardWillShow:(NSNotification *)notif{
int pnts=160;
CGRect rect = self.view.bounds;
rect.size.height-=pnts;
self.containerView.frame = rect;
// the following should not be needed if self.myTableView.autoresizingMask
// is at least UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleTopMargin
// but you can try adding this
self.myTableView.frame = self.containerView.bounds;
} | unknown | |
d604 | train | Welcome to the world of Angular!
To begin with, remove the <router-outlet></router-outlet> from all pages except app.component.html.
After you have done this, retest your pages. If the details page still doesn't show, look at your console for any Javascript errors and please post here :)
A: There are few issues in your code. Here is the solution:
*
*Remove the <router-outlet></router-outlet> from all pages except app.component.html
*If you need to pass name parameter in showDetails page then you need to specify that in app-routing.module.ts so instead of {path:'showDetails', component: CharDetailComponent}, you need to put {path:'showDetails/:name', component: CharDetailComponent}
After this change, ng serve your application again and you are good to go :). Hope this help you. | unknown | |
d605 | train | Try this:
context.Files.Where(x => x.Name == "test").ToList()
.ForEach( f => context.Files.Remove(f));
context.SaveChanges();
The RemoveAll may not compiled to SQL and not executed in SQL Server. | unknown | |
d606 | train | As you try to sync users, you already seem to understand that there are users for the os, and users for the hadoop platform.
Typically OS users are admin/ops people who need to manage the environment, while most platform users are engineers, analysts, and other who want to do something on the platform. This large group of users is something you typically want to sync.
As already indicated by @cricket you can integrate with LDAP/AD as explained here:
https://community.hortonworks.com/articles/105620/configuring-ranger-usersync-with-adldap-for-a-comm.html | unknown | |
d607 | train | Your are doing wrong here... your array is inside data.counterparty...
try this
var a= data.counterparty.map(x=>{
return x.name
}) | unknown | |
d608 | train | IE7 should work just fine with :active on anchors (<a>), as long as the anchor has the href attribute (source). | unknown | |
d609 | train | Ok so could make this work by redrawing the canvas in the function.
I don't really understand why the line got updated after the canvas.draw() call in the first function and why I have to redraw in the second function.
def changeLineThickness(self):
plt.setp(line, linewidth=1)
canvas.draw()
Maybe there is a faster way to do this rather than redrawing the whole canvas. | unknown | |
d610 | train | You should bring those protocol checking conditions to the beginning. You have some problems within the rules too. Try:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,NE,L]
RewriteRule ^rcp-pep-ipn /?rcp-pep-listener=IPN [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule> | unknown | |
d611 | train | You can do next thing:
*
*php artisan make:command CustomServeCommand
*Then delete all from file and use this code:
<?php
namespace App\Console\Commands;
use Illuminate\Foundation\Console\ServeCommand;
use Symfony\Component\Console\Input\InputOption;
class CustomServeCommand extends ServeCommand
{
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['host', null, InputOption::VALUE_OPTIONAL, 'The host address to serve the application on.', '0.0.0.0'],//default 127.0.0.1
['port', null, InputOption::VALUE_OPTIONAL, 'The port to serve the application on.', 8000],
];
}
}
*php artisan serve
Link to the core file.
Basically, you will extend default class and adapt method to fit your own needs. This way you can set host and port per requirements. | unknown | |
d612 | train | I too hit this roadblock. I reviewed the source code for MarkerWithLabel, and it does not support setting the ID or Class.
But you can add support by changing just 3 lines of code. Below is the modified code, with my added "ID" support. It works as normal, but if you add a .id property when creating a new MarkerWithLabel (as you did above), it will properly set the ID.
New markerswithlabel.js code — Added ID Support
/**
* @name MarkerWithLabel for V3
* @version 1.1.10 [April 8, 2014]
* @author Gary Little (inspired by code from Marc Ridey of Google).
* @copyright Copyright 2012 Gary Little [gary at luxcentral.com]
* @fileoverview MarkerWithLabel extends the Google Maps JavaScript API V3
* <code>google.maps.Marker</code> class.
* <p>
* MarkerWithLabel allows you to define markers with associated labels. As you would expect,
* if the marker is draggable, so too will be the label. In addition, a marker with a label
* responds to all mouse events in the same manner as a regular marker. It also fires mouse
* events and "property changed" events just as a regular marker would. Version 1.1 adds
* support for the raiseOnDrag feature introduced in API V3.3.
* <p>
* If you drag a marker by its label, you can cancel the drag and return the marker to its
* original position by pressing the <code>Esc</code> key. This doesn't work if you drag the marker
* itself because this feature is not (yet) supported in the <code>google.maps.Marker</code> class.
*/
/*!
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*jslint browser:true */
/*global document,google */
/**
* @param {Function} childCtor Child class.
* @param {Function} parentCtor Parent class.
* @private
*/
function inherits(childCtor, parentCtor) {
/* @constructor */
function tempCtor() {}
tempCtor.prototype = parentCtor.prototype;
childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = new tempCtor();
/* @override */
childCtor.prototype.constructor = childCtor;
}
/**
* This constructor creates a label and associates it with a marker.
* It is for the private use of the MarkerWithLabel class.
* @constructor
* @param {Marker} marker The marker with which the label is to be associated.
* @param {string} crossURL The URL of the cross image =.
* @param {string} handCursor The URL of the hand cursor.
* @private
*/
function MarkerLabel_(id, marker, crossURL, handCursorURL) {
this.marker_ = marker;
this.handCursorURL_ = marker.handCursorURL;
this.labelDiv_ = document.createElement("div");
//////////////////////////////////////////////////////////
// New - ID support
//////////////////////////////////////////////////////////
if (typeof id !== 'undefined') this.labelDiv_.id = id;
this.labelDiv_.style.cssText = "position: absolute; overflow: hidden;";
// Get the DIV for the "X" to be displayed when the marker is raised.
this.crossDiv_ = MarkerLabel_.getSharedCross(crossURL);
}
inherits(MarkerLabel_, google.maps.OverlayView);
/**
* Returns the DIV for the cross used when dragging a marker when the
* raiseOnDrag parameter set to true. One cross is shared with all markers.
* @param {string} crossURL The URL of the cross image =.
* @private
*/
MarkerLabel_.getSharedCross = function (crossURL) {
var div;
if (typeof MarkerLabel_.getSharedCross.crossDiv === "undefined") {
div = document.createElement("img");
div.style.cssText = "position: absolute; z-index: 1000002; display: none;";
// Hopefully Google never changes the standard "X" attributes:
div.style.marginLeft = "-8px";
div.style.marginTop = "-9px";
div.src = crossURL;
MarkerLabel_.getSharedCross.crossDiv = div;
}
return MarkerLabel_.getSharedCross.crossDiv;
};
/**
* Adds the DIV representing the label to the DOM. This method is called
* automatically when the marker's <code>setMap</code> method is called.
* @private
*/
MarkerLabel_.prototype.onAdd = function () {
var me = this;
var cMouseIsDown = false;
var cDraggingLabel = false;
var cSavedZIndex;
var cLatOffset, cLngOffset;
var cIgnoreClick;
var cRaiseEnabled;
var cStartPosition;
var cStartCenter;
// Constants:
var cRaiseOffset = 20;
var cDraggingCursor = "url(" + this.handCursorURL_ + ")";
// Stops all processing of an event.
//
var cAbortEvent = function (e) {
if (e.preventDefault) {
e.preventDefault();
}
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
};
var cStopBounce = function () {
me.marker_.setAnimation(null);
};
this.getPanes().overlayMouseTarget.appendChild(this.labelDiv_);
// One cross is shared with all markers, so only add it once:
if (typeof MarkerLabel_.getSharedCross.processed === "undefined") {
this.getPanes().overlayMouseTarget.appendChild(this.crossDiv_);
MarkerLabel_.getSharedCross.processed = true;
}
this.listeners_ = [
google.maps.event.addDomListener(this.labelDiv_, "mouseover", function (e) {
if (me.marker_.getDraggable() || me.marker_.getClickable()) {
this.style.cursor = "pointer";
google.maps.event.trigger(me.marker_, "mouseover", e);
}
}),
google.maps.event.addDomListener(this.labelDiv_, "mouseout", function (e) {
if ((me.marker_.getDraggable() || me.marker_.getClickable()) && !cDraggingLabel) {
this.style.cursor = me.marker_.getCursor();
google.maps.event.trigger(me.marker_, "mouseout", e);
}
}),
google.maps.event.addDomListener(this.labelDiv_, "mousedown", function (e) {
cDraggingLabel = false;
if (me.marker_.getDraggable()) {
cMouseIsDown = true;
this.style.cursor = cDraggingCursor;
}
if (me.marker_.getDraggable() || me.marker_.getClickable()) {
google.maps.event.trigger(me.marker_, "mousedown", e);
cAbortEvent(e); // Prevent map pan when starting a drag on a label
}
}),
google.maps.event.addDomListener(document, "mouseup", function (mEvent) {
var position;
if (cMouseIsDown) {
cMouseIsDown = false;
me.eventDiv_.style.cursor = "pointer";
google.maps.event.trigger(me.marker_, "mouseup", mEvent);
}
if (cDraggingLabel) {
if (cRaiseEnabled) { // Lower the marker & label
position = me.getProjection().fromLatLngToDivPixel(me.marker_.getPosition());
position.y += cRaiseOffset;
me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position));
// This is not the same bouncing style as when the marker portion is dragged,
// but it will have to do:
try { // Will fail if running Google Maps API earlier than V3.3
me.marker_.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(cStopBounce, 1406);
} catch (e) {}
}
me.crossDiv_.style.display = "none";
me.marker_.setZIndex(cSavedZIndex);
cIgnoreClick = true; // Set flag to ignore the click event reported after a label drag
cDraggingLabel = false;
mEvent.latLng = me.marker_.getPosition();
google.maps.event.trigger(me.marker_, "dragend", mEvent);
}
}),
google.maps.event.addListener(me.marker_.getMap(), "mousemove", function (mEvent) {
var position;
if (cMouseIsDown) {
if (cDraggingLabel) {
// Change the reported location from the mouse position to the marker position:
mEvent.latLng = new google.maps.LatLng(mEvent.latLng.lat() - cLatOffset, mEvent.latLng.lng() - cLngOffset);
position = me.getProjection().fromLatLngToDivPixel(mEvent.latLng);
if (cRaiseEnabled) {
me.crossDiv_.style.left = position.x + "px";
me.crossDiv_.style.top = position.y + "px";
me.crossDiv_.style.display = "";
position.y -= cRaiseOffset;
}
me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position));
if (cRaiseEnabled) { // Don't raise the veil; this hack needed to make MSIE act properly
me.eventDiv_.style.top = (position.y + cRaiseOffset) + "px";
}
google.maps.event.trigger(me.marker_, "drag", mEvent);
} else {
// Calculate offsets from the click point to the marker position:
cLatOffset = mEvent.latLng.lat() - me.marker_.getPosition().lat();
cLngOffset = mEvent.latLng.lng() - me.marker_.getPosition().lng();
cSavedZIndex = me.marker_.getZIndex();
cStartPosition = me.marker_.getPosition();
cStartCenter = me.marker_.getMap().getCenter();
cRaiseEnabled = me.marker_.get("raiseOnDrag");
cDraggingLabel = true;
me.marker_.setZIndex(1000000); // Moves the marker & label to the foreground during a drag
mEvent.latLng = me.marker_.getPosition();
google.maps.event.trigger(me.marker_, "dragstart", mEvent);
}
}
}),
google.maps.event.addDomListener(document, "keydown", function (e) {
if (cDraggingLabel) {
if (e.keyCode === 27) { // Esc key
cRaiseEnabled = false;
me.marker_.setPosition(cStartPosition);
me.marker_.getMap().setCenter(cStartCenter);
google.maps.event.trigger(document, "mouseup", e);
}
}
}),
google.maps.event.addDomListener(this.labelDiv_, "click", function (e) {
if (me.marker_.getDraggable() || me.marker_.getClickable()) {
if (cIgnoreClick) { // Ignore the click reported when a label drag ends
cIgnoreClick = false;
} else {
google.maps.event.trigger(me.marker_, "click", e);
cAbortEvent(e); // Prevent click from being passed on to map
}
}
}),
google.maps.event.addDomListener(this.labelDiv_, "dblclick", function (e) {
if (me.marker_.getDraggable() || me.marker_.getClickable()) {
google.maps.event.trigger(me.marker_, "dblclick", e);
cAbortEvent(e); // Prevent map zoom when double-clicking on a label
}
}),
google.maps.event.addListener(this.marker_, "dragstart", function (mEvent) {
if (!cDraggingLabel) {
cRaiseEnabled = this.get("raiseOnDrag");
}
}),
google.maps.event.addListener(this.marker_, "drag", function (mEvent) {
if (!cDraggingLabel) {
if (cRaiseEnabled) {
me.setPosition(cRaiseOffset);
// During a drag, the marker's z-index is temporarily set to 1000000 to
// ensure it appears above all other markers. Also set the label's z-index
// to 1000000 (plus or minus 1 depending on whether the label is supposed
// to be above or below the marker).
me.labelDiv_.style.zIndex = 1000000 + (this.get("labelInBackground") ? -1 : +1);
}
}
}),
google.maps.event.addListener(this.marker_, "dragend", function (mEvent) {
if (!cDraggingLabel) {
if (cRaiseEnabled) {
me.setPosition(0); // Also restores z-index of label
}
}
}),
google.maps.event.addListener(this.marker_, "position_changed", function () {
me.setPosition();
}),
google.maps.event.addListener(this.marker_, "zindex_changed", function () {
me.setZIndex();
}),
google.maps.event.addListener(this.marker_, "visible_changed", function () {
me.setVisible();
}),
google.maps.event.addListener(this.marker_, "labelvisible_changed", function () {
me.setVisible();
}),
google.maps.event.addListener(this.marker_, "title_changed", function () {
me.setTitle();
}),
google.maps.event.addListener(this.marker_, "labelcontent_changed", function () {
me.setContent();
}),
google.maps.event.addListener(this.marker_, "labelanchor_changed", function () {
me.setAnchor();
}),
google.maps.event.addListener(this.marker_, "labelclass_changed", function () {
me.setStyles();
}),
google.maps.event.addListener(this.marker_, "labelstyle_changed", function () {
me.setStyles();
})
];
};
/**
* Removes the DIV for the label from the DOM. It also removes all event handlers.
* This method is called automatically when the marker's <code>setMap(null)</code>
* method is called.
* @private
*/
MarkerLabel_.prototype.onRemove = function () {
var i;
this.labelDiv_.parentNode.removeChild(this.labelDiv_);
// Remove event listeners:
for (i = 0; i < this.listeners_.length; i++) {
google.maps.event.removeListener(this.listeners_[i]);
}
};
/**
* Draws the label on the map.
* @private
*/
MarkerLabel_.prototype.draw = function () {
this.setContent();
this.setTitle();
this.setStyles();
};
/**
* Sets the content of the label.
* The content can be plain text or an HTML DOM node.
* @private
*/
MarkerLabel_.prototype.setContent = function () {
var content = this.marker_.get("labelContent");
if (typeof content.nodeType === "undefined") {
this.labelDiv_.innerHTML = content;
} else {
this.labelDiv_.innerHTML = ""; // Remove current content
this.labelDiv_.appendChild(content);
}
};
/**
* Sets the content of the tool tip for the label. It is
* always set to be the same as for the marker itself.
* @private
*/
MarkerLabel_.prototype.setTitle = function () {
this.labelDiv_.title = this.marker_.getTitle() || "";
};
/**
* Sets the style of the label by setting the style sheet and applying
* other specific styles requested.
* @private
*/
MarkerLabel_.prototype.setStyles = function () {
var i, labelStyle;
// Apply style values from the style sheet defined in the labelClass parameter:
this.labelDiv_.className = this.marker_.get("labelClass");
// Clear existing inline style values:
this.labelDiv_.style.cssText = "";
// Apply style values defined in the labelStyle parameter:
labelStyle = this.marker_.get("labelStyle");
for (i in labelStyle) {
if (labelStyle.hasOwnProperty(i)) {
this.labelDiv_.style[i] = labelStyle[i];
}
}
this.setMandatoryStyles();
};
/**
* Sets the mandatory styles to the DIV representing the label as well as to the
* associated event DIV. This includes setting the DIV position, z-index, and visibility.
* @private
*/
MarkerLabel_.prototype.setMandatoryStyles = function () {
this.labelDiv_.style.position = "absolute";
this.labelDiv_.style.overflow = "hidden";
// Make sure the opacity setting causes the desired effect on MSIE:
if (typeof this.labelDiv_.style.opacity !== "undefined" && this.labelDiv_.style.opacity !== "") {
this.labelDiv_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")\"";
this.labelDiv_.style.filter = "alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")";
}
this.setAnchor();
this.setPosition(); // This also updates z-index, if necessary.
this.setVisible();
};
/**
* Sets the anchor point of the label.
* @private
*/
MarkerLabel_.prototype.setAnchor = function () {
var anchor = this.marker_.get("labelAnchor");
this.labelDiv_.style.marginLeft = -anchor.x + "px";
this.labelDiv_.style.marginTop = -anchor.y + "px";
};
/**
* Sets the position of the label. The z-index is also updated, if necessary.
* @private
*/
MarkerLabel_.prototype.setPosition = function (yOffset) {
var position = this.getProjection().fromLatLngToDivPixel(this.marker_.getPosition());
if (typeof yOffset === "undefined") {
yOffset = 0;
}
this.labelDiv_.style.left = Math.round(position.x) + "px";
this.labelDiv_.style.top = Math.round(position.y - yOffset) + "px";
this.setZIndex();
};
/**
* Sets the z-index of the label. If the marker's z-index property has not been defined, the z-index
* of the label is set to the vertical coordinate of the label. This is in keeping with the default
* stacking order for Google Maps: markers to the south are in front of markers to the north.
* @private
*/
MarkerLabel_.prototype.setZIndex = function () {
var zAdjust = (this.marker_.get("labelInBackground") ? -1 : +1);
if (typeof this.marker_.getZIndex() === "undefined") {
this.labelDiv_.style.zIndex = parseInt(this.labelDiv_.style.top, 10) + zAdjust;
} else {
this.labelDiv_.style.zIndex = this.marker_.getZIndex() + zAdjust;
}
};
/**
* Sets the visibility of the label. The label is visible only if the marker itself is
* visible (i.e., its visible property is true) and the labelVisible property is true.
* @private
*/
MarkerLabel_.prototype.setVisible = function () {
if (this.marker_.get("labelVisible")) {
this.labelDiv_.style.display = this.marker_.getVisible() ? "block" : "none";
} else {
this.labelDiv_.style.display = "none";
}
};
/**
* @name MarkerWithLabelOptions
* @class This class represents the optional parameter passed to the {@link MarkerWithLabel} constructor.
* The properties available are the same as for <code>google.maps.Marker</code> with the addition
* of the properties listed below. To change any of these additional properties after the labeled
* marker has been created, call <code>google.maps.Marker.set(propertyName, propertyValue)</code>.
* <p>
* When any of these properties changes, a property changed event is fired. The names of these
* events are derived from the name of the property and are of the form <code>propertyname_changed</code>.
* For example, if the content of the label changes, a <code>labelcontent_changed</code> event
* is fired.
* <p>
* @property {string|Node} [labelContent] The content of the label (plain text or an HTML DOM node).
* @property {Point} [labelAnchor] By default, a label is drawn with its anchor point at (0,0) so
* that its top left corner is positioned at the anchor point of the associated marker. Use this
* property to change the anchor point of the label. For example, to center a 50px-wide label
* beneath a marker, specify a <code>labelAnchor</code> of <code>google.maps.Point(25, 0)</code>.
* (Note: x-values increase to the right and y-values increase to the top.)
* @property {string} [labelClass] The name of the CSS class defining the styles for the label.
* Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>,
* <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and
* <code>marginTop</code> are ignored; these styles are for internal use only.
* @property {Object} [labelStyle] An object literal whose properties define specific CSS
* style values to be applied to the label. Style values defined here override those that may
* be defined in the <code>labelClass</code> style sheet. If this property is changed after the
* label has been created, all previously set styles (except those defined in the style sheet)
* are removed from the label before the new style values are applied.
* Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>,
* <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and
* <code>marginTop</code> are ignored; these styles are for internal use only.
* @property {boolean} [labelInBackground] A flag indicating whether a label that overlaps its
* associated marker should appear in the background (i.e., in a plane below the marker).
* The default is <code>false</code>, which causes the label to appear in the foreground.
* @property {boolean} [labelVisible] A flag indicating whether the label is to be visible.
* The default is <code>true</code>. Note that even if <code>labelVisible</code> is
* <code>true</code>, the label will <i>not</i> be visible unless the associated marker is also
* visible (i.e., unless the marker's <code>visible</code> property is <code>true</code>).
* @property {boolean} [raiseOnDrag] A flag indicating whether the label and marker are to be
* raised when the marker is dragged. The default is <code>true</code>. If a draggable marker is
* being created and a version of Google Maps API earlier than V3.3 is being used, this property
* must be set to <code>false</code>.
* @property {boolean} [optimized] A flag indicating whether rendering is to be optimized for the
* marker. <b>Important: The optimized rendering technique is not supported by MarkerWithLabel,
* so the value of this parameter is always forced to <code>false</code>.
* @property {string} [crossImage="http://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"]
* The URL of the cross image to be displayed while dragging a marker.
* @property {string} [handCursor="http://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur"]
* The URL of the cursor to be displayed while dragging a marker.
*/
/**
* Creates a MarkerWithLabel with the options specified in {@link MarkerWithLabelOptions}.
* @constructor
* @param {MarkerWithLabelOptions} [opt_options] The optional parameters.
*/
function MarkerWithLabel(opt_options) {
opt_options = opt_options || {};
opt_options.labelContent = opt_options.labelContent || "";
opt_options.labelAnchor = opt_options.labelAnchor || new google.maps.Point(0, 0);
opt_options.labelClass = opt_options.labelClass || "markerLabels";
opt_options.labelStyle = opt_options.labelStyle || {};
opt_options.labelInBackground = opt_options.labelInBackground || false;
if (typeof opt_options.labelVisible === "undefined") {
opt_options.labelVisible = true;
}
if (typeof opt_options.raiseOnDrag === "undefined") {
opt_options.raiseOnDrag = true;
}
if (typeof opt_options.clickable === "undefined") {
opt_options.clickable = true;
}
if (typeof opt_options.draggable === "undefined") {
opt_options.draggable = false;
}
if (typeof opt_options.optimized === "undefined") {
opt_options.optimized = false;
}
opt_options.crossImage = opt_options.crossImage || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png";
opt_options.handCursor = opt_options.handCursor || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur";
opt_options.optimized = false; // Optimized rendering is not supported
//////////////////////////////////////////////////////////
// New
//////////////////////////////////////////////////////////
this.label = new MarkerLabel_(opt_options.id, this, opt_options.crossImage, opt_options.handCursor); // Bind the label to the marker
// Call the parent constructor. It calls Marker.setValues to initialize, so all
// the new parameters are conveniently saved and can be accessed with get/set.
// Marker.set triggers a property changed event (called "propertyname_changed")
// that the marker label listens for in order to react to state changes.
google.maps.Marker.apply(this, arguments);
}
inherits(MarkerWithLabel, google.maps.Marker);
/**
* Overrides the standard Marker setMap function.
* @param {Map} theMap The map to which the marker is to be added.
* @private
*/
MarkerWithLabel.prototype.setMap = function (theMap) {
// Call the inherited function...
google.maps.Marker.prototype.setMap.apply(this, arguments);
// ... then deal with the label:
this.label.setMap(theMap);
};
If you would like to compress/minify/uglify the code, I recommend https://javascript-minifier.com/ | unknown | |
d613 | train | Both MySQL and HTML files can work. Your choice should depend on how simple the data is, and how much you are storing.
Some considerations:
*
*Speed. The HTML files and include() approach is going to be faster. The file system is the fastest, simplest form of data persistence.
*Horizontal scalability. If you adopt the file system approach, you are more or less tied to the disk on that machine. With a separate database engine, you have the future option of running the database on separate cluster servers on the network.
*Meta Data. Do you need to store things like time of creation, which user created the HTML, how many times it has been viewed by other users? If so, you probably only have one realistic choice - a "proper" database. This can be MySQL or perhaps one of the NoSQL solutions.
*Data Consumption. Do you show the table in its entirety to other users? Or do you show selected parts of it? Possibly even different parts to different users? This impacts how you store data - the entire table as ONE entity, or each row as an entity, or each individual cell.
*TEXT or LONGTEXT? Of course only applicable if you're going with SQL. The only way to answer this is to know how many bytes you are expecting to store per "HTML fragment". Note that your character encoding also impacts the number of bytes stored. Refer to: TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT maximum storage sizes
Also note that in MySQL, each TEXT/LONGTEXT may also result in an I/O to the disk.
As for the concern:
The HTML must be preserved in its entirety.
As long as you don't escape the HTML at any point, you should be fine. At first glance, this violates a security best practice, but if you think about it, "not escaping HTML" is exactly what you want to do. The practice of escaping HTML output only helps to eliminate HTML syntax being parsed as HTML tags (potential malicious), but in your case, you don't want HTML syntax eliminated at all - you intentionally want <td> to be parsed into an actual HTML table cell. So do not escape anything and the example you gave should never occur.
Just note: although you do not HTML-escape the output, you still should filter your inputs. In essence, this means: before writing to your DB, check that the user input is indeed HTML. To enhance your application's security, it may also be wise to define rules for what can be stored in those table cells - perhaps no <iframe> or <a> allowed, no style attributes allowed etc. Also, watch out for SQL injection - use PDO and prepared statements if you're going PHP + MySQL.
A: Live by this rule: PHP is for formatting; MySQL is for data.
PHP is for building HTML. MySQL is useful as a persistent store for data from which PHP can build HTML.
I have built several systems with Apache+PHP+MySQL. Each page is PHP-generated HTML. I do not store <html tags> in MySQL, only data.
Some of my pages perform one SELECT; many pages perform a dozen or more. The performance is just fine. I use PHP subroutines to build <table>s. I construct style variations based on the data.
Let's use blue for this might be in some database table; PHP code would add the <div> tags around it.
A: Someone is going to come up with the php to do this correctly, but here's an idea.
*
*Learning a database is a separate exercise that should not be mixed with learning anything else. Leave MySQL out of this. If you want to go back and redo the project with it as a learning exercise, after you've spent some time learning the basics, go ahead.
*What you are going to want to do is to generate your table as a separate .php fragment, and then save it to the disk under a unique name that you can use to find it again later (maybe it is a date/time, maybe a number that keeps increasing, maybe a different way). After it is saved, you can then include it into your page as well as the other pages you want to include it. Getting that unique name may be a challenge, but that is a different question (and if you look around, probably already has an answer somewhere).
*If you know .php enough, the rest should be self explanatory. If you don't, then now is an excellent time to learn. If you have further questions, you can search stack overflow or google for the answers. Chances are, the answers are out there.
*Since I do know databases, there could be an interesting discussion that the other posters are trying to have with you about how to store the data. However, that discussion will only be really useful to you once you understand what we are trying to talk about. Besides, I bet it has already been asked at least once.
So try out that plan and come back and post how you did it for future readers. Happy coding.
A: What you want to do is absolutely not Three-tier architecture like said Rick James, you are mixing data and presentation.
But like in everything, it is up what you want to do and your strategy.
*
*Let say, if you are looking to build an application with specific mould of page with a specific space for an image with a specific data at this place and you want to maintain this same architecture for years, you should separate data and presentation. Most of the time, big companies, big applications are looking for this approch. Even if I know some big companies application, we have stored some HTML code in database.
*Now, if you want to be free to change every page design quickly, you can have HTML tag in your database.
For example, Wordpress has a lot of HTML tag in its table for years and it is still maintained and used by a lot of people. Saving HTML in database? According to your needs/strategy, it does not schock me.
*And for your information, in Wordpress a HTML post is saved as LONGTEXT.
*In this approach, like Wordpress, you will not have a strong database model, it will be messy and not really relationnal.
^^
A: I don't know how many tables are you planning to store, but if you don't need to make complicated operations like sorting or filtering you could just store them in files in a folder structure, that will consume less resources than MySQL and the entire file is preserved.
If you need many tables then don't store the HTML table, store a json with the info like this:
[
[
{
"content": "Let's use blue for this.",
"color": "blue"
},
{
"content": "Let's use red for this.",
"color": "red"
}
],
[
{
"content": "Another row.",
"color": "blue"
},
{
"content": "Another row.",
"color": "red"
}
]
]
And then rebuild it when you call it. Will use less space and will be faster to transfer.
If your tables are in a fixed format, then make a table with the fields you need.
A: I would recommend thinking of your table as a kind of object. SQL tables are meant to store relational data. As such, why not represent the table in that fashion? Below is a really basic example of how you could store a table of People data in SQL.
<table>
<thead>
<th>People ID</th>
<th>First Name</th>
<th>Last Name</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>John</td>
<td>Doe</td>
</tr>
<tr>
<td>2</td>
<td>Jane</td>
<td>Doe</td>
</tr>
</tbody>
And then your SQL Table would store the encrypted string as follows (using JS):
function utf8_to_b64( str ) {
return window.btoa(unescape(encodeURIComponent( str )));
}
function b64_to_utf8( str ) {
return decodeURIComponent(escape(window.atob( str )));
}
var my_table = $('#table').html();
// Store this
var encrypted_string = utf8_to_b64(my_table);
// Decode as so
var table = b64_to_utf8(encrypted_string);
B64 encoding retrieved from here: https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding | unknown | |
d614 | train | I've looked over your program and most of it looks fine. I think your stack save/restore is fine. But, I see at least one other problem.
After every jal printf, you're doing an immediate jal fflush, so fflush will get printf's first argument [which is a string pointer] instead of a file descriptor pointer (e.g. stdout).
Under the mips ABI, the $a0-$a3 registers may be modified/destroyed by the callee. So, after printf returns $a0 can be anything.
All three programs seem to have this problem. IMO, if program 1 is working, it's just the luck of the draw (i.e.) whatever ends up in $a0 is harmless enough. That is, whatever is in it, points to a memory location that isn't a file descriptor but fflush tries to interpret it as one and lucks out.
Also, for fflush, $a0 should point to an address that is word [4 byte] aligned. If it's not, that could be the source of the bus error.
To fix this, change all fflush calls to:
lw $a0,stdout
jal fflush
That should probably work, but, depending on what the gcc assembler does, you may have to do:
la $a0,stdout
lw $a0,0($a0)
jal fflush
I've seen that the buserror appears if I try to jump back from a function For example I jump to PRINT_DOUBLE, there I jump to BREAK_LINE and there I jump to PRINT_STRING If I jump then back to BREAK_LINE all is fine, but back from BREAK_LINE to PRINT_DOUBLE I get the buserror
I've desk checked your code and [once again] seems fine. One way to debug this is to [using gdb] is to single step [with stepi] within your functions and put breakpoints after the the jal printf [or jal fflush].
Before and after each jal, note the $sp value. It must be the same. Do this for all your functions. Also, when returning from a function, note the $sp value, then the value from the lw [which goes into $ra]. They should all match the "expected"
Further, $sp must be 4 byte aligned at all times. Actually, according to a mips ABI document I've seen [possibly dated], it says that stack frames must be 8 byte aligned. That may be overkill at this point, but I mention it.
If you do lw from unaligned, that's an alignment exception, which will probably show up as SIGBUS. Further, check the $ra value [before doing the jr $ra]. It also must be the "expected" value and be 4 byte aligned.
In other words, exactly which instruction produces the exception?
Another thing you can do is to comment out some function calls. Start with the jal fflush. Then, comment out jal printf [in your sub-functions]. I note that you do a "naked" printf call at the outset, which seems fine. Keep doing this until the program stops faulting. This ought to help localize the area/call.
You didn't state whether you were running this in a simulator like spim or mars or real H/W [possibly running linux]. I suspect real H/W. But, you could verify your logic by running under a simulator [I prefer mars] and provide dummy functions for printf and fflush that just do jr $ra. Note that neither spim nor mars can link to .o files. They work purely from source, so you can only use your .s
If you're running on real H/W, gdb ought to be able to provide detailed information on the source of the exception. If not, create a C function that sets up a signal handler for SIGBUS using sigaction [see the manpage]. Then, put a breakpoint on the signal handler.
One of the arguments to the signal handler is a pointer to a siginfo_t struct that has additional information. Note that for SIGBUS, the si_code field will have a BUS_* value that may have more information.The third argument, although void * is a pointer to something that can give you the register values at the time of the exception.
In another answer I gave: mips recursion how to correctly store return address for a function another OP had a similar problem. My answer added some special stack alignment and check code that may give you some ideas. | unknown | |
d615 | train | There are multiple issues here:
*
*You cannot break a string in multiple lines the way you did.
*You're missing a ')' in the end of your swal call
*You're missing the title parameter, which is mandatory for swal
*The HTML must receive a boolean indicating that your message contains HTML code
I'm not very sure if you can create a form inside the SweetAlert, at least there are not examples in their page.
swal({background:'#ACF1F4', html:true, title:"<form method='post' id='loginform'>Username: <input id='username' name='username' style='width: 100%' ><br><br>Password:<input type='password' id='password' name='password'><br> <br></form>",
confirmButtonText: 'Submit',showCancelButton: true}) | unknown | |
d616 | train | You can add these lines:
region_lst = []
for trace in fig["data"]:
trace["name"] = trace["name"].split(",")[0]
if trace["name"] not in region_lst and trace["marker"]['symbol'] == 'circle':
trace["showlegend"] = True
region_lst.append(trace["name"])
else:
trace["showlegend"] = False
fig.update_layout(legend_title = "region")
fig.show()
Before adding the lines of code:
After adding the code:
I used this dataframe:
import plotly.express as px
df = px.data.medals_long()
fig = px.scatter(df, y="nation", x="count", color="medal", symbol="count")
A: *
*specifying color and symbol results in legend being combination of values in respective columns
*to have legend only be values in one column, change to use just color
*to represent second column as symbols, change each trace to use a list of symbols
*have synthesized data based on your description
full code
import pandas as pd
import numpy as np
import plotly.express as px
from plotly.validators.scatter.marker import SymbolValidator
eigen = [0.5, 0.7]
# simulate data
n = 1000
pca = pd.DataFrame(
{
**{f"PC{c}": np.random.uniform(1, 5, n) for c in range(1, 4, 1)},
**{
"Breed": np.random.choice([f"breed{x}" for x in range(67)], n),
"Region": np.random.choice([f"Region{x}" for x in range(10)], n),
},
}
)
# just color by Region
fig = px.scatter(
pca,
x="PC2",
y="PC1",
color="Region",
labels={"PC2": "PC2-{}%".format(eigen[1]), "PC1": "PC1-{}%".format(eigen[0])},
)
# build dict that maps as Breed to a symbol
symbol_map = {
t: s for t, s in zip(np.sort(pca["Breed"].unique()), SymbolValidator().values[2::3])
}
# for each trace update marker symbol to list of symbols that correspond to Breed
for t, s in zip(
fig.data, pca.groupby("Region")["Breed"].agg(lambda x: [symbol_map[v] for v in x])
):
t.update(marker_symbol=s)
fig | unknown | |
d617 | train | I would think this would work.
=TEXT(MIN(FILTER(1*LEFT(A2:A;10);A2:A<>"";E2:E=""));"yyyy-mm-dd")
and
=TEXT(MAX(FILTER(1*LEFT(A2:A;10);A2:A<>"";E2:E=""));"yyyy-mm-dd")
Your timestamps are coming from a system other than GoogleSheets. They need to be "forced" into numbers before they can be MIN()'d and MAX()'d. That's what 1* LEFT(... , 10) does.
Then they need to get turned back into text before they're concatenated in a text string like your plan. That's what TEXT(... ,"yyyy-mm-dd") does. | unknown | |
d618 | train | public WebServerMain(int port) {
try {
String content = " ";
String userChoice = " ";
ServerSocket ss = new ServerSocket(port);
System.out.println("Server: Initialised a socket at port " + port);
Socket conn = ss.accept();
System.out.println("Server: Awating for a client");
InputStreamReader ir = new InputStreamReader(conn.getInputStream());
PrintWriter out = new PrintWriter(conn.getOutputStream(), true);
BufferedReader userIn = new BufferedReader(ir);
userChoice = userIn.readLine();
System.out.println("Server: The choice we got is: " + userChoice);
System.out.println("Server: User have chosen GET Method");
BufferedReader in = new BufferedReader(new FileReader(
//"C:/Users/jayaprakash.j/Desktop/1.html"));//
userChoice.split(" ")[1]));
String str;
System.out.println("All good here");
while ((str = in.readLine()) != null) {
content += str;
}
in.close();
System.out.println("Server: The content is " + content);
out.println("HTTP/1.1 200 OK");
out.println("Content-Type: text/html");
out.println("Content-Length: " + content.length());
out.println();
out.println(content);
out.close();
conn.close();
} catch (IOException e) {
e.getMessage();
}
} | unknown | |
d619 | train | you can do as below
var objList = Context.sp_Temp().ToList();
var photoList = objList.Where(o=>o._int_previous == 1).ToList();
Or
you can cast the object to Class which build the object list as below
var photoList =
(from pht in objList
let x=>(sp_TempResult)pht
where x._int_previous == 1 select pht).ToList(); | unknown | |
d620 | train | It seems like the question is outdated by looking at the comments. But I'll still answer this as the use-case mentioned in this question is not just specific to autoencoders and might be helpful for some other cases.
So, when you say "train the whole network layer by layer", I would rather interpret it as "train small networks with one single layer in a sequence".
Looking at the code posted in this question, it seems that the OP has already built small networks. But both these networks do not consist of one single layer.
The second autoencoder here, takes as input the input of first autoencoder. But, it should actually take as input, the output of first autoencoder.
So then, you train the first autoencoder and collect it's predicitons after it is trained. Then you train the second autoencoder, which takes as input the output (predictions) of first autoencoder.
Now let's focus on this part: "After layer 1 is trained, it's used as input to train layer 2. The reconstruction loss should be compared with the layer 1 and not the input layer."
Since the network takes as input the output of layer 1 (autoencoder 1 in OP's case), it will be comparing it's output with this. The task is achieved.
But to achieve this, you will need to write the model.fit(...) line which is missing in the code provided in the question.
Also, just in case you want the model to calculate loss on input layer, you simply replace the y parameter in model,fit(...) to the input of autoencoder 1.
In short, you just need to decouple these autoencoders into tiny networks with one single layer and then train them as you wish. No need to use trainable = False now, or else use it as you wish. | unknown | |
d621 | train | No, because you need to tell the compiler how big you want the array to be. Remember that arrays have a fixed size after creation. So any of these are okay, to create an empty array:
String[] array = {};
String[] array = new String[0];
String[] array = new String[] {};
Admittedly an empty array is rarely useful. In many cases you'd be better off using an ArrayList<String> instead. Of course sometimes you have to use an array - in order to return a value from a method, for example.
If you want to create an array of a specific length and then initialize it later, you can specify the length:
String[] array = new String[5];
for (int i = 0; i < 5; i++) {
array[i] = String.valueOf(i); // Or whatever
}
One nice feature of empty arrays is that they're immutable - you can't change the length, and because then length is 0 there are no elements to mutate. So if you are going to regularly use an empty array of a particular type, you can just create it once:
private static final String[] EMPTY_STRING_ARRAY = {};
... and reuse that everywhere.
A: No you can't do that. It will produce compile error
you shoud write
String[] arr=new String[4]; //you should declared it sized
or
String[] arr={"asgk"};
or
String[] arr=new String[]{}; | unknown | |
d622 | train | I came up with the answer to this question while writing it...
To get a literal \ in the replace target we need to escape it not just once but twice: \\\\
Then to get a literal " we need to escape that as well \".
So to replace a literal \" with an escaped one, we need: \\\\\".
That is: string(REPLACE "\"" "\\\\\"" TARGET "${SOURCE}") | unknown | |
d623 | train | You must parse the referer. For exemple a google search query will contains: http://www.google.be/search?q=oostende+taxi&ie=UTF-8&oe=UTF-8&hl=en&client=safari
It's a real life query, yes I'm in Oostebde right now :)
See the query string. You can determine pretty easily what I was looking for.
Not all search engines are seo friendly, must major players are.
How to get the referer ? It depends on the script language you use.
A: You should use a tool like Google analytics.
A: Besides the Google Analytics, Google Webmaster Tools is also very useful. It can report a detail analysis of the search queries' impressions, clicks, CTR, position etc. | unknown | |
d624 | train | The Windows ftp.exe always returns 0, no matter what.
All you can possibly do, is to parse its output and look for errors. But that's pretty unreliable.
If you want to take this approach anyway, see
*
*how to capture error conditions in windows ftp scripts? or
*Batch command to check if FTP connection is successful.
Though, you better use some better FTP client. Sooner or later you will run into troubles with the ftp.exe anyway, as it does not support an encryption, the passive mode or recursive transfers, among many other limitations.
If you are familiar with PowerShell, use the FtpWebRequest or WebClient from a Powershell script. There are numerous examples here, for example Upload files with FTP using PowerShell.
If not, use some 3rd party command-line FTP client.
For example with WinSCP FTP client, your batch file may look like:
@echo off
winscp.com /ini=nul /log=script.log /command ^
"open ftp://USERNAME:[email protected]/" ^
"put C:\LOCAL\FILE /REMOTE/PATH/" ^
"exit"
if ERRORLEVEL 1 (
winscp.com /ini=nul /log=script2.log /command ^
"open ftp://USERNAME:[email protected]/" ^
"put C:\LOCAL\FILE /REMOTE/PATH/" ^
"exit"
)
References:
*
*Automate file transfers to FTP server;
*How do I know that script completed successfully?;
*Guide to converting Windows FTP script to WinSCP SFTP script.
WinSCP can also be used from PowerShell, if you want even more robust implementation.
(I'm the author of WinSCP) | unknown | |
d625 | train | I think I got what you're trying to accomplish. First, you can't define a hook inside a function. What you can do is trigger the effect callback after at least one of its dependencies change.
useEffect(() => {
// run code whenever deps change
}, [deps])
Though for this particular problem (from what I understood from your description), I'd go something like this:
export default function Academics() {
let [currentOption, setCurrentOption] = useState()
function handleSelectOption(i) {
return () => setCurrentOption(i)
}
function clearSelectedOption() {
return setCurrentOption()
}
return (options.map((option, i) =>
<button
onClick={handleSelectOption(i)}
className={i === currentOption ? 'option option--highlight' : 'option'}
onBlur={clearSelectedOption}
></button>
))
} | unknown | |
d626 | train | Using ave to sum freq every 4 yearly,
ans <- dat
ans$freq <- ave(dat$freq, ceiling(dat$year/4), FUN=sum)
ans[ans$year %in% seq(1896,2016,4),]
output:
year freq
1 1896 380
2 1900 1936
3 1904 1301
5 1908 4834
6 1912 4040
7 1920 4292
8 1924 5693
9 1928 5574
10 1932 3321
11 1936 7401
12 1948 7480
13 1952 9358
14 1956 6434
15 1960 9235
16 1964 9480
17 1968 10479
18 1972 11959
19 1976 10502
20 1980 8937
21 1984 11588
22 1988 14676
23 1992 16413
25 1996 16940
27 2000 17426
29 2004 17552
31 2008 17984
33 2012 17322
35 2016 18579
data:
dat <- read.table(text="year freq
1896 380
1900 1936
1904 1301
1906 1733
1908 3101
1912 4040
1920 4292
1924 5693
1928 5574
1932 3321
1936 7401
1948 7480
1952 9358
1956 6434
1960 9235
1964 9480
1968 10479
1972 11959
1976 10502
1980 8937
1984 11588
1988 14676
1992 16413
1994 3160
1996 13780
1998 3605
2000 13821
2002 4109
2004 13443
2006 4382
2008 13602
2010 4402
2012 12920
2014 4891
2016 13688", header=TRUE) | unknown | |
d627 | train | I think you are looking to loop through each person, and give them upto 10 chocolates each
Stack<Chocolate> chocolateObjects = new Stack<Chocolate>();
List<People> peopleList = new List<People>()
{
new People(),
new People(),
new People(),
};
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
foreach (var p in peopleList)
{
while (p.chocolates.Count < 10 && chocolateObjects.Count>0)
{
var a = chocolateObjects.Pop();
p.chocolates.Push(a);
}
Console.WriteLine(p.chocolates.Count());
} | unknown | |
d628 | train | You can skip any page in the ShouldSkipPage event:
[Setup]
AppName=My Program
AppVersion=1.5
DefaultDirName={pf}\My Program
[Code]
var
DirPage: TInputDirWizardPage;
OptionPage: TInputOptionWizardPage;
procedure InitializeWizard;
begin
OptionPage := CreateInputOptionPage(wpWelcome, 'Caption', 'Description',
'SubCaption', False, True);
OptionPage.Add('Option 1');
OptionPage.Add('Option 2');
DirPage := CreateInputDirPage(OptionPage.ID, 'Caption', 'Description',
'SubCaption', False, '');
DirPage.Add('Select A');
DirPage.Add('Select B');
DirPage.Add('Select C');
end;
function ShouldSkipPage(PageID: Integer): Boolean;
begin
// skip the page if your custom dir page is about to show and
// the option is not checked
Result := (PageID = DirPage.ID) and not OptionPage.Values[0];
end; | unknown | |
d629 | train | We can use DataFrame.melt to un pivot your data, then use sort_values and drop_duplicates:
df = (
df.melt(var_name='position')
.sort_values('value')
.drop_duplicates('position', ignore_index=True)
)
position value
0 bravo -1.0
1 alpha 1.0
2 delta 1.0
3 charlie NaN
Another option would be to use DataFrame.bfill over the column axis. Since you noted that:
can guarantee that each row in the original data contains exactly zero or one non-NaN values
values = df.bfill(axis=1).iloc[:, 0]
dfn = pd.DataFrame({'positions': df.columns, 'values': values})
positions values
0 alpha 1.0
1 bravo 1.0
2 charlie NaN
3 delta -1.0
A: Another way to do this. Actually, I just noticed, that it is quite similar to Erfan's first proposal:
# get the index as a column
df2= df.reset_index(drop=False)
# melt the columns keeping index as the id column
# and sort the result, so NaNs appear at the end
df3= df2.melt(id_vars=['index'])
df3.sort_values('value', ascending=True, inplace=True)
# now take the values of the first row per index
df3.groupby('index')[['variable', 'value']].agg('first')
Or shorter:
(
df.reset_index(drop=False)
.melt(id_vars=['index'])
.sort_values('value')
.groupby('index')[['variable', 'value']].agg('first')
)
The result is:
variable value
index
0 alpha 1.0
1 delta 1.0
2 alpha NaN
3 bravo -1.0 | unknown | |
d630 | train | Your question talks about .val and the "value" of elements, but none of the elements in your question is a form field, and therefore they don't have values.
If they were form fields:
I read that you can't do $(.Level1[someAttribute=value]) which makes sense as val() isn't an available DOM attribute in that sense
Right, your only option is to loop, probably via filter:
$('.Level0').each(function () {
var targetValue = $(this).val();
var matching = $(".Level1").filter(function() {
return $(this).val() === targetValue;
});
// ...use `matching` here...
});
Note that matching may have zero, or multiple, elements in it depending on how many .Level1 elements matched the value.
But because they aren't:
...you may want .text or .html instead of .val in the above, or possibly a :contains selector instead of filter. | unknown | |
d631 | train | I ended up using a UIScrollView, which implements pinch to zoom, and flick automatically (well, almost). | unknown | |
d632 | train | You should use CSS media queries. You can read more about it here: http://www.w3schools.com/css/css_rwd_mediaqueries.asp
For example:
@media only screen and (max-width: 1043px) {
section.focus {
display: block;
}
}
A: Firstly you cannot use same ID for more than one div. So change the id of one div.
And to hide the second div and show the first div:
Use CSS:
@media only screen and (max-width: 1043px) {
.focus {
display: block;
}
.notes {
display: none;
}
}
A: In response to your requirement for removing the ID attribute, try the following JavaScript. It can only do it once however, and if you are interested in performance you should consider investigating debounce/throttle for the resize handler. (http://benalman.com/code/projects/jquery-throttle-debounce/examples/debounce/)
$(window).on('resize', function() {
if($(window).width() < 1043) {
$('.notes').removeAttr('id');
$(window).off('resize');
}
});
However, the media queries answers are the correct approach to show/hide based on screen width. | unknown | |
d633 | train | I'd go for something a little less complex. You need three models:
class Home < ActiveRecord::Base
has_many :appliances
has_many :reminders, :through => :appliances
end
class Appliance < ActiveRecord::Base
belongs_to :home
has_many :reminders
end
class Reminder < ActiveRecord::Base
belongs_to :appliance
end
Notice that we're using the has_many :through relation to allow us to call home.reminders directly.
See the Document example here for more info on has_many :through: http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association
In your original example you seem to want to store various pre-defined appliances in the db for reference. I'd do it differently. Have a config file with the various makes and models that you can use to populate dropdowns on the form users use when setting up their appliance details. Then you can skip the extra models and simplify things as described above. | unknown | |
d634 | train | Solved it by removing
setlocal enabledelayedexpansion
but don't know why.
A: setlocal with or without EnableDelayedExpansion creates a new scope for variables.
It makes a copy of all variables and then all changes are made to these copies.
An endlocal leaves this scope and discard the copy and all changes are dsicarded.
For some variable manipulations you have to enable delayed expansion for some it's better to use disabled delayed expansion, but the only way to switch between them is to use setlocal.
But in your case it seems, that you don't need it at all. | unknown | |
d635 | train | The problem solved it self - I do not know why, but now everything is working properly, in the meantime Skype and some Windwos updates have been installed but I am not shure how this might affect the git system...
A: I have also encountered such problems. The solution is to start the Windows Update Service: | unknown | |
d636 | train | It's the structure dereference ("member b of object pointed to by a") in C. Objective-C is a strict superset of C.
The the usual way to access a member a is as s.a which, given the pointer, is expressed as (*p).a or can instead be accessed by the shorthand:
p->a using the structure dereference operator.
struct point
{
int* x;
int* y;
};
structure point* struct1;
As with any pointer. To change the address it points to:
struct1->x = &varX;
To change the value at the address to which it points:
*(struct1->x) = varX; | unknown | |
d637 | train | This should work:
var types = this.GetType().GetTypeInfo().Assembly.GetTypes()
.Where(t => t.GetTypeInfo().GetCustomAttribute<MyAttribute>() != null); | unknown | |
d638 | train | The .done() function of getSubCat() should call getSubSubCat().
function getSubCat(){
var selectedCategory = $("#category option:selected").val();
$.ajax({
type: "POST",
url: "subcat.php",
data: { category : selectedCategory }
}).done(function(data){
$("#subcategory").html(data);
getSubSubCat();
});
}
When you call getSubSubCat() during page load, getSubCat() hasn't finished yet (because AJAX is asynchronous), so none of its changes to the second menu have been made. | unknown | |
d639 | train | You can display 3 levels in 3 modules from the same menu, of course the second level's content will be determined by the first level selection; this will apply also to the third level.
However, please note that mod_menu used to have inadequate cache support, so by all means DO DISABLE the cache on the modules, else they won't work or will work funny (not showing the current page highlighted... changing the second menu "20" when you click on the first menu "3" ...)
A: Try the Splitmenu configuration of RocketTheme's RokNavMenu
Here's a discussion on how to accomplish that. | unknown | |
d640 | train | Thanks for all you support mates. I found the answer.
I was using ng-show to manage when i need to show the slider because of which initially the slider was hidden and giving problem.
But now i switched to ng-if which is not just hiding the slider or completely removing it from DOM and insert it when i need so that bxslider is initialised only when shown and working completely fine.
Found the difference here : what is the difference between ng-if and ng-show/ng-hide
A: The problem is that - Slides/images must be visible before slider gets initiate.
In your case possible solutions are -
Either:
*
*You can reload slider after ng-show animation complete
*Slider can be initiate after ng-show animation complete
To reload bx slider doc -
http://bxslider.com/examples/reload-slider
http://bxslider.com/examples/reload-slider-settings
Sample code:
var slider = $('.bxslider').bxSlider({
mode: 'horizontal'
});
//Inside ng-show callback
slider.reloadSlider();
Trigger event when ng-show is complete
Call a function when ng-show is triggered? | unknown | |
d641 | train | error in setting value using find function I'm a fairly inexperienced coder and have a small piece of code that is just falling over each time I run it (although I would swear it worked once and has since stopped!)
I am trying to find a value from a cell (which has a formulas to determine which value I need to find) in a range of cells elsewhere in the spreadsheet.
Originally my code was set as follows (when I think it worked) and I am getting an error message saying "Compile error: object required"
I tried to add the word Set in the appropriate place to stop that but then I get a runtime error 91 message saying object variable or with block variable not set.
My sub is in a class module set as option explicit and the code is as follows;
Dim StartRow As Integer
Dim EndRow As Integer
Set StartRow = Sheets("CHARTS").Range("T2:T9").Find(What:=Sheets("CHARTS").Range("O14").Value, LookIn:=xlValues, Lookat:=xlWhole).row
Set EndRow = Sheets("CHARTS").Range("T2:T9").Find(What:=Sheets("CHARTS").Range("O13").Value, LookIn:=xlValues, Lookat:=xlWhole).row
Any help gratefully received, I just can't see where I've gone wrong...!! | unknown | |
d642 | train | Is this the right way to call instance method on model?
Yes, if @foo is an instance of Foo
should this param4 = params[:param4] || 'N' be done in model?
You can set the last parameter variable on you model to be option like so
class Foo
def baz(param1, param2, param3, param4 = 'N')
puts 'something'
end
end
And remove the need to set it within the controller
def signup
@foo.baz(Integer(params[:param1]),
params[:param2],
params[:param3],
params[:param4])
head :ok
rescue ArgumentError => e
render_error(:bad_request, e.message)
end
Since if params[:param4] is nil it will be set to 'N' as specified within the baz method on the Foo model.
Whether or not if you should set param4 in the model is up to you:
*
*Yes, if setting the last parameter param4 to 'N' should or need to occur outside the controller, or
*No, if setting a default value for param4 is unique to the signup controller action and param4 should not have default set, since it might be used elsewhere
A: I think you should handle it in model:
class Foo
def baz(param)
param1 = Integer(params[:param1])
param2 = params[:param2]
param3 = params[:param2]
param4 = params[:param4] || 'N'
puts 'something'
end
end | unknown | |
d643 | train | Very simple you have forgotten to place parantheses after myFunction.
your code should be:
<script>
function myFunction(){
document.getElementById('but').value = "changed";
}
</script>
A: This way it work. Function needs parenthesis
function myFunction() {
document.getElementById('but').value = "changed";
}
<html>
<body>
<input type="text" id="input" onkeypress="myFunction()">
<input type="button" value="Hallo" id="but">
</body>
</html>
an alternative way is
myFunction = function () {
document.getElementById('but').value = "changed";
} | unknown | |
d644 | train | The problem is that the geocoder.geocode function is asynchronous : it doesn't block the code, the following lines are executed, but the inner callback isn't called until the server responds.
This means that you must put your console.log line inside the callback or in a function called from the callback :
geocoder.geocode({'address': address}, function(result, status){
if(status === "OK"){
map.setCenter(result[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: result[0].geometry.location
});
} else {
alert("Failed to geocode: " + status);
}
otherFunc();
});
function otherFunc(){
console.log("further down page: " + address);
}
A: Your hunch is correct. The code further down the page is executing in place before your initialize method is called. window.load is not fired until the DOM is loaded, including images:
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.
A simple fix here would be to define address right away. Its components are static on the page, there's no reason to have that happen inside the function.
var property = <?php echo json_encode(urlencode($Residential['ReAddress'])); ?>;
var zipCode = <?php echo json_encode($Residential['zipCode']); ?>;
var address = property + "," + zipCode;
function loadAddress() {
// ...
}
A: The problem is that the second <script>-element is executed right away when the browser loads the page. In your first block you add the DOM-listener for the load-event, which should call initialize(). However, that is executed later when the browser has fully loaded and built the page.
If you log the value after it has been determined in the callback to geocoder.geocode() it should print the proper value. | unknown | |
d645 | train | First attempt at a rewrite (untested, as I have no idea of your table layouts):-
SELECT DISTINCT tax.ta_id, tax.a_id, ax.status, ax.kunden_id,
IF(ax.todo_from != '0000-00-00', DATE_FORMAT(ax.todo_from, '%d.%m'), 'k. day_date') todo_from,
IF(ax.todo_until != '0000-00-00', DATE_FORMAT(ax.todo_until, '%d.%m'), 'k. day_date') todo_until,
IF((SELECT taj.city FROM suborders taj WHERE taj.a_id = tax.a_id AND taj.order_type = 'BRING' ORDER BY pos_id ASC LIMIT 1) != '',
CONCAT(
IF(Sub2.short_name != '', Sub2.short_name,tax.city),
'>',
CONCAT((
SELECT IF( Sub3.short_name != '',
Sub3.short_name,
taj.city)
FROM suborders taj
LEFT OUTER JOIN (SELECT h_id, short_name FROM locations WHERE company_id = '100') Sub3 ON Sub3.h_id = taj.h_id
WHERE taj.a_id = tax.a_id
AND taj.order_type = 'BRING'
AND taj.pos_id >= tax.pos_id
ORDER BY pos_id
ASC LIMIT 1))),
IF(Sub2.short_name != '', Sub2.short_name, tax.city)) as city,
tax.user_id, tax.day_date, tax.pos_gesamt_id, '4' as class_type
FROM suborders tax
INNER JOIN orders ax ON (ax.a_id = tax.a_id)
INNER JOIN (
SELECT DISTINCT a_id
FROM suborders taj
WHERE taj.user_id = '140'
AND taj.day_date = '2013-04-16'
AND taj.user_id = '140'
AND taj.order_type = 'BRING'
) Sub4 ON Sub4.a_id = tax.a_id
LEFT OUTER JOIN (SELECT h_id, short_name FROM locations WHERE company_id = '100') Sub2 ON Sub2.h_id = tax.h_id
WHERE tax.order_type = 'TAKE'
AND tax.user_id = '140'
AND tax.day_date = '2013-04-16'
AND tax.company_id = '100'
GROUP BY tax.ta_id
At this stage I am not sure I can go any further with this, as it is REALLY confusing me how things fit together.
The problem is you have a lot of correlated subqueries and these are slow (ie, a sub query that relies on a field from outside the query - hence MySQL has to perform that subquery for every single line). I have removed a couple of these that I can work out and replaced them with joins to subqueries (with these MySQL can perform the subquery once and then join the results to the main query)
But it is very confusing when you have correlated subqueries within queries, and you have reused alias names between different tables and subqueries.
The query can be greatly improved in performance if I can work out what it is meant to be doing!
Further you also have used GROUP BY on the main query without any aggregate columns. This is sometimes done instead of a DISTINCT, but you have a DISTINCT as well. | unknown | |
d646 | train | Setting a layout manager to buttonPanel1
buttonPanel1.setLayout(new BoxLayout(buttonPanel1, BoxLayout.PAGE_AXIS));
buttonPanel1.add(Box.createVerticalGlue());
Does not change the layout manager to other panels which use FlowLayout by default.
It does effect the button size. Print out
System.out.println(Button.getSize()); //use button, not Button
Now change the layout manager of buttonPanel1
buttonPanel1.setLayout(new BorderLayout());
and change the code to add the button to the panel :
buttonPanel1.add(Button, BorderLayout.CENTER);
and print again.
The layout manager changes the initial size of the button. The FlowLayout manager of the other 3 panels, does not change the size. | unknown | |
d647 | train | If I recall correctly it all depends on how your [OperationContract] is defined. you may have to use Message Contracts to get your desired behavior. Take a look at http://msdn.microsoft.com/en-us/library/ms730255.aspx
A: // The Model Object
[Serializable]
[XmlRoot("OutputItem")]
[DataContractAttribute]
public class MyObject
{
[XmlElement("ItemName")]
[DataMemberAttribute]
public string Name { get; set; }
[XmlArray("DummyItems")]
[XmlArrayItem("DummyItem", typeof(MyItemField))]
public List<Fields> DummyItem { get; set; }
}
// The Class that implement the contract
[DataContract]
public class ConsumptionService : IAnyContract
{
public MyObject GetItemXML(string id)
{
MyObject mo = new MyObject();
//do some stuff to populate mi
MyObject mo;
}
} | unknown | |
d648 | train | I'm not 100% sure about this without seeing more code.
It doesn't register the exception handler at the top of the stack but it uses a trick to insert the exception handling where the EXCEPTION_REGISTRATION structure is defined. So for example (maybe in your case it's implemented a bit differently):
void function3(EXCEPTION_REGISTRATION& handler)
{
SetHandler(handler);
//Do other stuff
}
void function2(EXCEPTION_REGISTRATION& handler)
{
__try
{
//Do something
function3(handler);
}
__except(expression)
{
//...
}
}
void function()
{
EXCEPTION_REGISTRATION handler;
//..Init handler
function2(handler)
}
When you call SetHandler it will insert the exception handling like it was in the scope of function. So in this case at the moment you call SetHandler it will appear as if there is a __try __except block in function.
Therefor if there's an exception inside function3 the handler in function will first be called and if that handler doesn't handle it, the handler installed by SetHandler will be called. | unknown | |
d649 | train | You should increment the $num variable by doing $num++; once inside the loop, then print it where you need it with <?php echo $num; ?> without using <?php echo $num+1; ?> - as doing so will only increment it as you echo it - not add one to each iteration.
<?php
$num = 0;
foreach($listings as $list):
$num++; // Increment $num for each iteration
?>
<li>
<div class="checkbox">
<input type="checkbox" class="css-checkbox" value="<?php echo $list['title'];?>" id="visit<?php echo $num;?>" name="treatment<?php echo $num;?>">
<label for="visit<?php echo $num;?>" class="css-label"><?php echo $list['title']?> <strong><?php echo $list['price'];?><span>£</span></strong></label>
</div>
</li>
<?php endforeach; ?>
If your $listings is numeric indexed, you can use the key of each element in the array instead by doing
foreach($listings as $num=>$list):
?>
<li>
<div class="checkbox">
<input type="checkbox" class="css-checkbox" value="<?php echo $list['title'];?>" id="visit<?php echo $num;?>" name="treatment<?php echo $num;?>">
<label for="visit<?php echo $num;?>" class="css-label"><?php echo $list['title']?> <strong><?php echo $list['price'];?><span>£</span></strong></label>
</div>
</li>
<?php endforeach; ?>
A: The problem is you did not set the value of $num variable you just only print or echo it inside the html tags. You need to add or increment the $num variable inside the loop like this.
<?php $num++; ?>
or
<?php $num = $num+1; ?> | unknown | |
d650 | train | letterGrade isn't declared properly, do:
let letterGrade = ' '
This declares the letterGrade variable.
A: You haven't declared the lettergrade variable. To do this, replace letterGrade; with let letterGrade;
In your code, this will look like:
function getHandleValue(idName) {
const value = parseInt(document.getElementById(idName).value);
console.log(value);
return value;
}
function getTotal() {
//console.log("app js starts loading")
let english = getHandleValue('english');
let math = getHandleValue('math');
let physics = getHandleValue('physics');
let computer = getHandleValue('computer');
let science = getHandleValue('science');
//console.log("app js ends loading")
let total = english + math + physics + computer + science;
document.getElementById('total').innerHTML = total;
return total;
}
function getAverage() {
// option 1
// const total = parseInt(document.getElementById('total').innerHTML);
// const average = total / 5;
// document.getElementById('average').innerHTML = average;
// option 2
const average = getTotal() / 5;
document.getElementById('average').innerHTML = average;
}
function letterGrade() {
let letterGrade;
if (grade >= 90 && grade <= 100)
letterGrade = 'A';
else if (grade >= 80 && grade <= 89)
letterGrade = 'B';
else if (grade >= 70 && grade <= 79)
letterGrade = 'C';
else if (grade >= 60 && grade <= 69)
letterGrade = 'D';
else if (grade > 1 && grade <= 59)
letterGrade = 'F';
let average = letterGrade;
document.getElementById('Grade').innerHTML = Grade;
}
A: Problems
I assume comments and answers have already stated, that the function letterGrade() doesn't use the correct variable letterGrade but instead uses an undefined variable Grade. Also, the variable grade is neither defined nor is it passed as a parameter or is within scope. Figure I is a breakdown of letterGrade().
Figure I
function letterGrade() {
/**
* ISSUE 1 * Naming a Variable
* Do not name a variable with the same name as the function in which it
* resides within
* ISSUE 2 * Declaring or Defining a Variable
* Use identifier var (not recommended), let, or const
* ex. let letter;
*/
letterGrade;
/**
* ISSUE 3 * Declaring or Defining Variables
* grade isn't declared
* ex. let grade;
* grade isn't defined
* ex. let grade = 0;
* grade isn't a parameter
* ex. function letterGrade(grade) {...
* grade isn't within scope
* ex. let grade = 0;
* function letterGrade() {...
*/
if (grade >= 90 && grade <= 100)
letterGrade = 'A';
else if (grade >= 80 && grade <= 89)
letterGrade = 'B';
else if (grade >= 70 && grade <= 79)
letterGrade = 'C';
else if (grade >= 60 && grade <= 69)
letterGrade = 'D';
else if (grade > 1 && grade <= 59)
letterGrade = 'F';
/**
* ISSUE 4 * Passing by Value
* average is never used. If average is a reference to the value calculated
* by function getAverage(), then...
* - getAverage() should return that value,
* - then that value must be defined outside of getAverage()
* - or passed as a parameter of letterGrade() (recommennded).
* ex. ..::OUTSIDE OF letterGrade()::..
* function getAverage() {
* ...
* return average;
* }
* // Option A
* let average = getAverage()
* letterGrade(average)
* // Option B (recommended)
* letterGrade(getAverage)
*
* ..::INSIDE OF letterGrade()::..
* function letterGrade(average) {
* let grade = typeof average === "number" ? grade : 0;
* ...
* }
* Even if average was to be used, it would be useless as the value of
* letterGrade, there's no point in reassigning it to another variable
* unless it's to create a copy of another variable declared or defined
* outside of the function.
*/
let average = letterGrade;
/**
* ISSUE 5 * Defining or Declaring Variables
* Grade variable has the same problem as ISSUE 3
*/
document.getElementById('Grade').innerHTML = Grade;
}
Solutions
Provided are two examples (Example A and Example B) that require familiarity with a few methods, properties, events, and techniques, please refer to Appendix located at the end of this answer. Both examples have step-by-step details commented within the source.
Example A
Example A is a working example that comprises of:
*
*a <form> tag
*an <input type="range">
*two <output> tags
*an event handler getGrade(e)
*a functional letterGrade(score)
/**
* Reference <form>
* Bind the "input" event to <form>
*/
const grade = document.forms.grade;
grade.oninput = getGrade;
/**
* Event handler passes (e)vent object by default
* Reference the tag the user is currently typing into
* Reference all form controls (<fieldset>, <input>, <output>)
* Reference both <output>
* If the tag the user is currently using is NOT <form>
* AND the tag is #score...
* Assign the value of the currently used <input> as the
* value of the first <output>
* Next pass the same value to letterGrade(score) and assign
* it's value to the second <output>
*/
function getGrade(e) {
const dataIN = e.target;
const io = this.elements;
const number = io.number;
const letter = io.letter;
if (dataIN !== this && dataIN.id === "score") {
number.value = dataIN.value;
letter.value = letterGrade(dataIN.value);
}
}
/**
* Convert a given number in the range of 0 to 100 to a
* letter grade in the range of "A" to "F".
* @param {Number} score - A number in the range of 0 to 100
* @returns {String} - A letter in the range of "A" to "F"
* @default {String} - A "" if the @param is out of the
* range of 0 to 100
*/
function letterGrade(score) {
if (score >= 0 && score < 60) return "F";
if (score >= 60 && score < 70) return "D";
if (score >= 70 && score < 80) return "C";
if (score >= 80 && score < 90) return "B";
if (score >= 90 && score < 101) return "A";
return "";
}
label {
display: flex;
align-items: center;
margin: 0.5rem 0;
}
input {
cursor: pointer;
}
<form id="grade">
<label for="score">Set Score: </label>
<label>
0
<input id="score" type="range" min="0" max="100" value="0">
100
</label>
<label>Score: <output id="number"></output></label>
<label>Grade: <output id="letter"></output></label>
</form>
Note the pattern of the flow control statements in Example A:
if (CONDITION) return LETTER;
if (CONDITION) return LETTER;
if (CONDITION) return LETTER;
if (CONDITION) return LETTER;
if (CONDITION) return LETTER;
return "";
If a CONDITION is true then a LETTER is returned. Whenever a value (LETTER) is returned, the function will terminate, so for example the third CONDITION is true, then the third LETTER is returned, the function ends, and the rest of the function doesn't execute. This technique is called a short circuit
Example B
Example B is a working example comprising of:
*
*a <form>
*five <input type="number">
*two <output>
*an event handler calc(e)
*a terse version of letterGrade(avg) that uses ternary expressions
/**
* Reference <form>
* Bind the "input" event to <form>
*/
const ga = document.forms.ga;
ga.oninput = calc;
/**
* Event handler passes the (e)vent object by default
* Reference the tag the user is entering text into
* Reference all form controls (<fieldset>, <input>, <output>)
* Collect all tags with [name="subject"] into an array
* Reference the <output>
* If the <input> that the user is currently using is NOT <form>...
* AND if it is [name="subject"]...
* convert the value of each <input> of the >subs< array into a
* number, then use .reduce() to get the sum of all of them (>total<)
* Next divide >total< by the .length of >subs<
* Then get the letter grade determined by the given >average<
* Then display the quotient as the value of the first <output>
* Finally, display the letter grade as the value of the second <output>
*/
function calc(e) {
const dataIN = e.target;
const io = this.elements;
const subs = Array.from(io.subject);
const avg = io.avg;
const grd = io.grd;
if (dataIN !== this && dataIN.name === "subject") {
const total = subs.reduce((sum, add) => +sum + parseInt(add.value), 0);
const average = total / subs.length;
const letter = grade(average);
avg.value = average;
grd.value = letter;
}
}
/**
* Given a number in the range of 0 to 100 return The letter grade equivalent.
* @param {Number} avg - A number in the range of 0 to 100
* @returns {String} - A letter grade "A" to "F"
* @default {String} - If avg ts not within the range of 0 to 100,
* a "" is returned
*/
function grade(avg) {
return avg >= 0 && avg < 60 ? "F" :
avg >= 60 && avg < 70 ? "D" :
avg >= 70 && avg < 80 ? "C" :
avg >= 80 && avg < 90 ? "B" :
avg >= 90 && avg < 101 ? "A" : "";
}
:root {
font: 300 ch2/1.15 "Segoe UI"
}
fieldset {
display: flex;
flex-flow: column nowrap;
width: 50vw;
max-width: 60ch;
margin: auto;
}
legend {
font-weight: 500;
font-size: 1.15rem;
}
label {
display: flex;
justify-content: space-between;
align-items: center;
margin: 0.25rem 1rem;
}
.last+label {
margin-top: 1.25rem;
}
input,
output {
display: inline-block;
width: 6ch;
font: inherit;
line-height: normal;
text-align: center;
}
output {
text-align: left;
}
<form id="ga">
<fieldset>
<legend>Subjects</legend>
<label>English: <input id="eng" name="subject" type="number" min="0" max="100" value="0"></label>
<label>Math: <input id="mat" name="subject" type="number" min="0" max="100" value="0"></label>
<label>History: <input id="his" name="subject" type="number" min="0" max="100" value="0"></label>
<label>Science: <input id="sci" name="subject" type="number" min="0" max="100" value="0"></label>
<label class="last">Art: <input id="art" name="subject" type="number" min="0" max="100" value="0"></label>
<label>Average: <output id="avg"></output></label>
<label>Grade: <output id="grd"></output></label>
</fieldset>
</form>
Appendix
*
*Events
*Event Delegation
*Inline Event Handlers are Garbage
*HTMLFormElement Interface
*HTMLFormControlsCollection Interface
*List of Form Controls
*Scope and Closures
A: NOTES
*
*This is a fully working example of how you can go about calculating the grades in a generic way without having to use ids for each subject input.
*By building it this way, you can add more subjects without changing the calculation logic.
*Also if you do not put a value for a subject than it will not be used in the calculations.
HTML
<div>
<section><label>Total:</label><span id="total">0</span></section>
<section><label>Average:</label><span id="average">0</span></section>
<section><label>Grade:</label><span id="grade">-</span></section>
</div>
<br />
<form onsubmit="return false;">
<label>English:</label><input type="number" min="0" max="100" step="1" name="english" value="0" /><br />
<label>Math:</label><input type="number" min="0" max="100" step="1" name="math" value="0" /><br />
<label>Physics:</label><input type="number" min="0" max="100" step="1" name="physics" value="0" /><br />
<label>Computer:</label><input type="number" min="0" max="100" step="1" name="computer" value="0" /><br />
<label>Science:</label><input type="number" min="0" max="100" step="1" name="science" value="0" /><br />
<br />
<button onclick="calculateGrades(this)">Calculate Grade</button>
</form>
CSS
label {
display: inline-block;
width: 4rem;
margin-right: 2rem;
padding: 0.25rem 1rem;
}
JS
const totalElement = document.getElementById("total");
const averageElement = document.getElementById("average");
const gradeElement = document.getElementById("grade");
// Calculate the grades function
function calculateGrades(btn) {
// find inputs
const form = btn.closest("form");
const inputs = form.getElementsByTagName("input");
// define variables
let total = 0;
let used = 0;
let average = 0;
// loop over inputs
for (const input of inputs) {
// if value = 0, then do not use in calculation
if (input.value == 0) continue;
// convert input to number and add it to total
total += Number( input.value );
// increment number of subjects used
used++;
}
// calculate average grade
average = total / used;
// display the values
totalElement.innerText = total;
averageElement.innerText = average;
// get letter grade
letterGrade( average );
}
// Calculate the grade letter function
function letterGrade(value) {
// define variables
let letterGrade = null;
// if there is no value return
if ( !value ) return letterGrade;
// determine letter from value
switch (true) {
case value >= 90:
letterGrade = "A";
break;
case value >= 80:
letterGrade = "B";
break;
case value >= 70:
letterGrade = "C";
break;
case value >= 60:
letterGrade = "D";
break;
default:
letterGrade = "F";
break;
}
// display the grade letter
gradeElement.innerText = letterGrade;
} | unknown | |
d651 | train | You can try to launch the same activity but changing the content view (into onCreate) for each situation. Something like:
if (isLocked()) {
setContentView(R.layout.locker_activity);
} else {
setContentView(R.layout.settings_activity);
}
A: You can use just one activity as launcher and use Fragments to load what you want. Something like this:
public class LauncherActivity extends FragmentActivity {
super.onCreate(savedInstanceState);
Fragment fragment;
if (isLocked()) {
fragment = new LockerFragment();
}
else {
fragment = new SettingsFragmentFragment();
}
getFragmentManager().beginTransaction().add(R.id.container_id,fragment).commit();
} | unknown | |
d652 | train | The method I used was to create a subclass of UIViewController that I used as the root view of 3 child view controllers. Notable properties of the root controller were:
*
*viewControllers - an NSArray of view controllers that I switched between
*selectedIndex - index of the selected view controller that was set to 0 on viewLoad. This is nonatomic, so when the setSelectedIndex was called it did all the logic to put that child view controller in place.
*selectedViewController - a readonly property so that other classes could determine what was currently being shown
In the setSelectedIndex method you need to use logic similar to:
[self addChildViewController: selectedViewController];
[[self view] addSubview: [selectedViewController view]];
[[self view] setNeedsDisplay];
This worked really well, but because I wanted to use a single navigation controller for the entire application, I decided to use a different approach.
I forgot to mention you will want to clear child view controllers every time you add one, so that you don't stack up a ton of them and waste memory. Before the block above call:
for (UIViewController *viewController in [self childViewControllers])
[viewController removeFromParentViewController]; | unknown | |
d653 | train | This is pretty straightforward using rolling joins with data.table:
require(data.table) ## >= 1.9.2
setkey(setDT(d1), x) ## convert to data.table, set key for the column to join on
setkey(setDT(d2), x) ## same as above
d2[d1, roll=-Inf]
# x z y
# 1: 4 200 10
# 2: 6 200 20
# 3: 7 300 30
A: Input data:
d1 <- data.frame(x=c(4,6,7), y=c(10,20,30))
d2 <- data.frame(x=c(3,6,9), z=c(100,200,300))
You basically wish to extend d1 by a new column. So let's copy it.
d3 <- d1
Next I assume that d2$x is sorted nondecreasingly and thatmax(d1$x) <= max(d2$x).
d3$z <- sapply(d1$x, function(x) d2$z[which(x <= d2$x)[1]])
Which reads: for each x in d1$x, get the smallest value from d2$x which is not smaller than x.
Under these assumptions, the above may also be written as (& should be a bit faster):
d3$z <- sapply(d1$x, function(x) d2$z[which.max(x <= d2$x)])
In result we get:
d3
## x y z
## 1 4 10 200
## 2 6 20 200
## 3 7 30 300
EDIT1: Inspired by @MatthewLundberg's cut-based solution, here's another one using findInterval:
d3$z <- d2$z[findInterval(d1$x, d2$x+1)+1]
EDIT2: (Benchmark)
Exemplary data:
set.seed(123)
d1 <- data.frame(x=sort(sample(1:10000, 1000)), y=sort(sample(1:10000, 1000)))
d2 <- data.frame(x=sort(c(sample(1:10000, 999), 10000)), z=sort(sample(1:10000, 1000)))
Results:
microbenchmark::microbenchmark(
{d3 <- d1; d3$z <- d2$z[findInterval(d1$x, d2$x+1)+1] },
{d3 <- d1; d3$z <- sapply(d1$x, function(x) d2$z[which(x <= d2$x)[1]]) },
{d3 <- d1; d3$z <- sapply(d1$x, function(x) d2$z[which.max(x <= d2$x)]) },
{d1$x2 <- d2$x[as.numeric(cut(d1$x, c(-Inf, d2$x, Inf)))]; merge(d1, d2, by.x='x2', by.y='x')},
{d1a <- d1; setkey(setDT(d1a), x); d2a <- d2; setkey(setDT(d2a), x); d2a[d1a, roll=-Inf] }
)
## Unit: microseconds
## expr min lq median uq max neval
## findInterval 221.102 1357.558 1394.246 1429.767 17810.55 100
## which 66311.738 70619.518 85170.175 87674.762 220613.09 100
## which.max 69832.069 73225.755 83347.842 89549.326 118266.20 100
## cut 8095.411 8347.841 8498.486 8798.226 25531.58 100
## data.table 1668.998 1774.442 1878.028 1954.583 17974.10 100
A: cut can be used to find the appropriate matches in d2$x for the values in d1$x.
The computation to find the matches with cut is as follows:
as.numeric(cut(d1$x, c(-Inf, d2$x, Inf)))
## [1] 2 2 3
These are the values:
d2$x[as.numeric(cut(d1$x, c(-Inf, d2$x, Inf)))]
[1] 6 6 9
These can be added to d1 and the merge performed:
d1$x2 <- d2$x[as.numeric(cut(d1$x, c(-Inf, d2$x, Inf)))]
merge(d1, d2, by.x='x2', by.y='x')
## x2 x y z
## 1 6 4 10 200
## 2 6 6 20 200
## 3 9 7 30 300
The added column may then be removed, if desired.
A: Try: sapply(d1$x,function(y) d2$z[d2$x > y][which.min(abs(y - d2$x[d2$x > y]))]) | unknown | |
d654 | train | I just put "global" properties of CSS in their own stylesheet all together. So for instance: put in tr, td, input, table, etc in their own stylesheet and the rest of custom .classes and #divs in their own.
This simplifies it the best and keeps it organized.
A: Global CSS rules can go on a file (i.e. global-style.css) - these will apply to all pages.
Specific CSS rules can go a separate file (i.e. login-style.css) - on this second file, you can override the default look-feel of the global CSS if desired.
You would only include the second file in the HTML files you need the different look-feel (from the global one)
A: I use one line per rule notation now, try to keep it organized and easy to read. It minimizes scrolling and it is easier to sort the rules that way. | unknown | |
d655 | train | Try this
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_gravity="center"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<ImageView
android:id="@+id/imgInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:src="@drawable/ic_message" />
<ImageView
android:id="@+id/imgLogout"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:layout_marginStart="290dp"
android:src="@drawable/ic_message" />
</LinearLayout>
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal|center_vertical"
android:layout_marginTop="10dp"
android:src="@drawable/kid_goku" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal"
android:paddingStart="120dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_gravity="center_horizontal|center_vertical"
android:src="@drawable/kid_goku" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingStart="20dp"
android:text="name"
android:textColor="@color/white"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/machineLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
</LinearLayout>
<android.support.design.widget.FloatingActionButton
android:id="@+id/search"
android:layout_width="46dp"
android:layout_height="wrap_content"
android:layout_above="@+id/addNew"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_margin="@dimen/fab_margin"
app:srcCompat="@drawable/ic_message" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/addNew"
android:layout_width="46dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
app:srcCompat="@drawable/ic_message" />
</RelativeLayout>
OUTPUT
A: Use CoordinatorLayout as root view.
And Also add app:layout_anchorGravity="bottom|right|end(specify as you need)" in FloatingActionButton | unknown | |
d656 | train | That's because stream controllers allow only 1 Subscription (or 1 listener) , you could use the [StreamController<List<UserModel>>.broadcast()][1] constructor instead of StreamController>().
A: I ended up moving the StreamBuilder to the parent widget above the PageView() which fixed the problem. | unknown | |
d657 | train | Value of shouldDisplayRightZone depends on value of pointOverLeftZone, pointOverRightZone so you should make it an independent state and wrap into an useEffect and update whenever there are changes in pointOverLeftZone, pointOverRightZone
const [shouldDisplayRightZone, setShouldDisplayRightZone] = useState(
pointOverLeftZone || pointOverRightZone
);
useEffect(() => {
setShouldDisplayRightZone(pointOverLeftZone || pointOverRightZone);
}, [pointOverLeftZone, pointOverRightZone]);
Forked codesandbox
A: import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [pointOverLeftZone, setPointOverLeftZone] = useState(false);
const [pointOverRightZone] = useState(false);
const shouldDisplayRightZone = pointOverLeftZone || pointOverRightZone;
return (
<div className="App">
<div
className="zone light-cyan"
onPointerOver={() => setPointOverLeftZone(true)}
>
<p>Point over here to display the right zone</p>
</div>
{shouldDisplayRightZone && (
<div
className="zone light-yellow"
onPointerOut={() => setPointOverLeftZone(false)}
>
<p>
Once open the right zone, both zones should activate the display of
this right zone, but the bug is here: when you mouse the move here
it dissapear
</p>
</div>
)}
</div>
);
}
Something like this?
A: import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [pointOverLeftZone, setPointOverLeftZone] = useState(false);
const [pointOverRightZone, setPointOverRightZone] = useState(false);
const [flag, setFlag] = useState(true);
const [int, setIni] = useState(false);
const shouldDisplayRightZone = pointOverLeftZone || pointOverRightZone;
return (
<div className="App">
{flag === true ? (
<div
className="zone light-cyan"
onPointerOver={() => {
if (!pointOverLeftZone) {
setPointOverLeftZone(true);
}
}}
>
<p>Point over here to display the right zone</p>
</div>
) : (
<div>
<div>right zone open</div>
<p>
Once open the right zone, both zones should activate the display of
this right zone, but the bug is here: when you mouse the move here
it dissapear
</p>
</div>
)}
{shouldDisplayRightZone && (
<div
className="zone light-yellow"
onPointerOver={() => {
if (!pointOverRightZone) {
setFlag(false);
setPointOverRightZone(true);
}
}}
onPointerOut={() => {
if (pointOverRightZone) setPointOverRightZone(false);
}}
>
<p>
Once open the right zone, both zones should activate the display of
this right zone, but the bug is here: when you mouse the move here
it dissapear
</p>
</div>
)}
</div>
);
}
i have changed the code in sandbox you can check it there.Let me know if it works | unknown | |
d658 | train | First of all, do not use 'row' and 'container' on the same <div>.
'row' should always be a child of 'container'.
Second, define 3 <div>'s with 'col-md-4 col-sm-4' inside a <div class="row">.
Repeat.
A: maybe i was not clear enough.
i inserted 6 columns into one row.
each one of them has the class "col-md-4" so i accepted 2 lines with 3 columns.
my problem was that the the bottom line rose slightly on top line.
i succeeded to solve it by giving the attribute margin-bottom:30px;
thank you for answering me. | unknown | |
d659 | train | You can enable TCP keepalive for JDBC - either be setting directive or by adding "ENABLE=BROKEN" into connection string.
*
*Usually Cisco/Juniper cuts off TCP connection when it is inactive for more that on hour.
*While Linux kernel starts sending keepalive probes after two hours(tcp_keepalive_time). So if you decide to turn tcp keepalive on, you will also need root, to change this kernel tunable to lower value(10-15 minutes)
*Moreover HikariCP should not keep open any connection for longer than 30 minutes - by default.
So if your FW, Linux kernel and HikariCP all use default settings, then this error should not occur in your system.
See HikariCP official documentation
maxLifetime:
This property controls the maximum lifetime of a connection in the
pool. An in-use connection will never be retired, only when it is
closed will it then be removed. On a connection-by-connection basis,
minor negative attenuation is applied to avoid mass-extinction in the
pool. We strongly recommend setting this value, and it should be
several seconds shorter than any database or infrastructure imposed
connection time limit. A value of 0 indicates no maximum lifetime
(infinite lifetime), subject of course to the idleTimeout setting. The
minimum allowed value is 30000ms (30 seconds). Default: 1800000 (30
minutes)
A: I have added the below configuration for hickaricp in configuration file and it is
working fine.
## Database Connection Pool
play.db.pool = hikaricp
play.db.prototype.hikaricp.connectionTimeout=120000
play.db.prototype.hikaricp.idleTimeout=15000
play.db.prototype.hikaricp.leakDetectionThreshold=120000
play.db.prototype.hikaricp.validationTimeout=10000
play.db.prototype.hikaricp.maxLifetime=120000 | unknown | |
d660 | train | simply this is whats happening
when the code first run
const MyComponent = (props) => {
const onClickHandler = (somearg) => (e) => {
console.log(`somearg passed successfully is ${somearg}`)
};
return (
<div onClick={onClickHandler('some args')}>
</div>
);
};
*
*When it sees onClick={onClickHandler(1)} it will run the
code inside the onClick
*Then onClickHandler is a function and we pass an argument as 1 and execute it, now it will return a another function with replaced values as below.
(e) => {
console.log(`somearg passed successfully is 1`); // see args gets replaced with the value.
}
*so now when we click on the div above function will be called.
to make sure this is what exactly happening see the below Demo
const MyComponent = (props) => {
const onClickHandler = (somearg) => (e) => {
console.log(`somearg passed successfully is ${somearg}`, new Date().getTime())
};
return (
<div onClick={onClickHandler(new Date().getTime())}>
div
</div>
);
};
and you will see the times are different, which means clicked time and function created time is different.
So if you are put a one function inside onClick as it will gets executed with the code executing, and will not respond to you clicks
const MyComponent = (props) => {
const onClickHandler = (e) => {
console.log(`somearg passed successfully is`, new Date().getTime())
};
return (
<div onClick={onClickHandler(new Date().getTime())}>
div
</div>
);
};
A: The pattern you're referring to is called "currying". I'll explain why that pattern can be useful later in the answer, but first let's try to understand exactly what's happening.
As you've already identified, the onClickHandler function returns a new function, it doesn't actually add much outside of that. Now what this means is that when the component renders, onClickHandler will be called immediately. So writing this:
<div onClick={onClickHandler('test')}>
Will end up returning this:
<div onClick={(e) => {console.log(`somearg passed successfully is ${somearg}`)}}>
This is why here you're allowed to call the function in the JSX, even though (like you pointed out) you can't do that most other times. The reason is because it's the returned function that will actually handle the click.
Now lets talk more about why this pattern is useful. somearg is vague, but we'll stick with it for now until we get to the other benefits.
"currying" uses a closure to sort of "freeze" the value of somearg for use by the returned function. Looking at the above example of the returned function, somearg would appear to not exist. However, with a closure, somearg will not only be available, but will also retain the value of 'test'.
So why use this pattern?
This pattern allows you to reuse functions in ways otherwise not possible. Consider a usecase where we have 2 div's that should be clickable. They should both do the same thing, but it may be helpful to be able to distinguish which div was clicked in order to complete that operation.
For simplicity, lets just say we have two div's, and when clicked we want each to log their order.
Here's how you might do that without currying:
const Example = () => {
const onClickHandler1 = (e) => {
console.log("I am the 1 div.");
};
const onClickHandler2 = (e) => {
console.log("I am the 2 div.");
};
return (
<div>
<div onClick={onClickHandler1}>1</div>
<div onClick={onClickHandler2}>2</div>
</div>
);
}
ReactDOM.render(<Example />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
The above works just fine, but our two functions have a lot of shared functionality. It seems unnecessary to have both. So one solution would be to use currying:
const Example = () => {
// Converted to longer form so its possible to console.log in the first function
// It still operates identically to the short-hand form.
const onClickHandler = (order) => {
console.log("called with " + order);
return (e) => console.log("I am the " + order + " div.");
};
return (
<div>
<div onClick={onClickHandler(1)}>1</div>
<div onClick={onClickHandler(2)}>2</div>
</div>
);
}
ReactDOM.render(<Example />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
As you can see in the above example, onClickHandler gets called twice as soon as the component renders. But the first time, order is "frozen" or "closed over" with the value of 1, and the second has the value of 2.
This was a very simple example, but imagine you are looping over a dynamic set of data that should each return a clickable element. You could then pass an index or and id or some other variable to identify the element.
Ultimately, this is just a pattern for function reuse. There are other ways to accomplish the same level of abstraction like using inline functions, but this is just for the sake of explaining currying and how it may be used. | unknown | |
d661 | train | Here is some minimal code to implement the monitor code in python.
Note :
*
*I adapted this from the PubSub class in redis-py. See client.py
*This does not parse the response, but that should be simple enough
*Doesn't do any sort of error handling
import redis
class Monitor():
def __init__(self, connection_pool):
self.connection_pool = connection_pool
self.connection = None
def __del__(self):
try:
self.reset()
except:
pass
def reset(self):
if self.connection:
self.connection_pool.release(self.connection)
self.connection = None
def monitor(self):
if self.connection is None:
self.connection = self.connection_pool.get_connection(
'monitor', None)
self.connection.send_command("monitor")
return self.listen()
def parse_response(self):
return self.connection.read_response()
def listen(self):
while True:
yield self.parse_response()
if __name__ == '__main__':
pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
monitor = Monitor(pool)
commands = monitor.monitor()
for c in commands :
print(c)
A: Now, the redis library already included the monitor support itself.
https://github.com/andymccurdy/redis-py/blob/master/redis/client.py#L3422 | unknown | |
d662 | train | I don't know much about reactjs or fire base. But what you need to do is before you send the email create a unique id for every user when the submit the sign up form. In the email you genarate you need to add a button(link) to click if user need to get registered to the site. that link should redirect to your site with the id you have saved
ex
https://yoursite.com/signup-action?id=QSE$#@$WDVVDsfdsfew543
now when user click this you can get the id from the url and check if it is in the database and who is the user and can update the table to activate the user. That is how you know that the user has clicked the email.. then ask the user to log in | unknown | |
d663 | train | Here is code snippet for you ,
try {
URL url = new URL("your url goes here");
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,"Demo.xml");
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
progressDialog.setMax(totalSize);
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Else these link can help you,
1)Read remote XML in android
2)Download remote XML and store it in android | unknown | |
d664 | train | There's a 3rd alternative which is even shorter - using the ternary conditional operator :
return a != null ? a : getA();
EDIT: I assumed a is a local variable, and therefore doesn't have to be assigned if it's null. If, on the other hand, it's an instance variable used as a cache (to avoid calling getA() multiple times), you need to assign the result of getA() to a, in which case I'd use your second alternative, since it's shorter, and thus clearer (you can still use the ternary conditional operator with assignment - return a != null ? a : (a = getA()); - but I find that less clear).
A: I prefer the second choice as there is only one return statement, and this can help debugging (you only need to put in one breakpoint rather than two). Also you're arguably duplicating code in the first choice.
But in this instance I'd prefer using the ternary conditional:
return a == null ? getA() : a;
A: I prefer the second option, The best practice is have only one return statement in a method. That will be the more readable code.
A: The second is more concise, and could be better because of this, but this is a subjective matter and no-one can give you a particularly objective answer. Whatever you like or fits into your teams coding standards is the answer.
As has been pointed out, there is a shorter way to do this:
return a!=null ? a : getA();
but again, it entirely depends on what you and your team prefer. Personally I prefer the second way you showed to this, as it is more readable (in my opinion).
A: I'm assuming for a second that a is a class member and that getA() is a method that creates an instance of a.
The best solution should be to push this logic in the called method. In other words, rather than have:
void someFunction() {
// logic
if(a==null) {
a=getA();
}
return a;
}
A getA() {
// creation logic of instance A
return newAInstance;
}
You should have:
void someFunction() {
// logic
return getA();
}
A getA() {
if(a == null) {
// creation logic of instance A
}
return a;
}
The cost of the method call is minimal and worth not having to deal with when a will be instantiated. | unknown | |
d665 | train | If the upgrade was successful without any errors. Then this kind of issue may related to the configuration.
You could try re-running the configuration wizard for the team project to fix the issue. How to please refer this tutorial: Configure features after an upgrade | unknown | |
d666 | train | Try this
string connStr = "Enter Your connection String Here";
string SQL = "Enter Your SELECT Here";
SqlDataAdapter adapter = new SqlDataAdapter(SQL, connStr);
DataTable ds = new DataSet();
adapter.Fill(ds);
ds.WriteXml("FileName", XmlWriteMode.WriteSchema); | unknown | |
d667 | train | You need a custom executor. When you call execute(), it uses a default executor that runs all tasks serially. If you call executeOnExecutor() you can specify an executor. The default one is serial, there's also THREAD_POOL_EXECUTOR which will run tasks in parallel. If you want a priority queue, you'll need to write your own that keeps a priority queue of tasks and executes them serially based on priority. | unknown | |
d668 | train | In the end we just droped the mscep.dll approach and used curl to directly send POST with needed parameters to ...certsrv/certfnsh.asp page. Then we parsed the returned HTML and obtained the link for certificate download.
Not a nice solution, but worked for us. | unknown | |
d669 | train | You will have to maintain inner state with currently played video, and as soon as video is over, you will have to set next video in state which will re render the component again and start with next video. Below code should work.
import React from "react";
import ReactDOM from "react-dom";
import YouTube from '@u-wave/react-youtube';
import "./styles.css";
let videoIdList=["AOMpxsiUg2Q","XM-HJT8_esM","AOMpxsiUg2Q"];
class App extends React.Component {
constructor(props){
super(props);
this.state = {};
this.i = 0;
}
componentDidMount() {
this.setState({videoId: videoIdList[this.i]});
}
render() {
const opts = {
height: '390',
width: '640',
playerVars: { // https://developers.google.com/youtube/player_parameters
autoplay: 1
}
};
return (
<YouTube
video={this.state.videoId}
opts={opts}
onReady={this._onReady}
onEnd={this._onEnd}
/>
);
}
_onEnd = () => {
this.setState({videoId: videoIdList[++this.i]});
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
You can check working code here -
https://codesandbox.io/s/7yk0vrzr36 | unknown | |
d670 | train | Yes, but you don't provide many details of what you mean by "deploy". I suppose you mean using scp? If so, you must copy your Jenkins public key to an authorized keys file, and make sure that your security group rules allow CloudBees' build machines to talk to your EC2 instance. | unknown | |
d671 | train | A slight problem with the way you are setting things up is that the height of the element itself and the height of the background image (before you have sized it) are the same, and its drawing the gray for 6px from the top (the default direction for a linear-gradient) and the rest is transparent.
This snippet slightly simplifies what is going on.
It 'draws'a background image in the gray color, setting its width to 88% and its height to 6px and its position to bottom left. It sets it to not repeat on either axis.
body {
background: red;
}
.skeleton-6euk0cm7tfi:empty {
height: 100px;
background-color: #ffffff;
border-radius: 0px 0px 0px 0px;
background-image: linear-gradient( #676b6f, #676b6f);
background-repeat: no-repeat;
background-size: 88px 6px;
background-position: left bottom;
}
<
<div class="skeleton-6euk0cm7tfi"></div> | unknown | |
d672 | train | here start is a class method.
By your current approach, you can use it in the following way
MyClass.start '8080'
But if you want to use it on instance of class then use the following code
class MyClass
def initialize
self.class.reset
end
def self.reset
...
end
def start(port)
...
end
end
test = MyClass.new
test.start '8080'
A: You are using start as a Class variable, the method names preceded with self-keyword make those methods as Class methods. So if you really want to not change your class then you should call it like this:
MyClass.start '8080'
Else you can remove the self from your reset and start methods and make them as Instance methods and use them as:
test = MyClass.new
test.start '8082' | unknown | |
d673 | train | urls = root.xpath('//div[1]/header/div[3]/nav/ul/li/a/@href')
These HREFs aren't full URLs; they're essentially just pathnames (i.e. /foo/bar/thing.html).
When you click on one of these links in a browser, the browser is smart enough to prepend the current page's scheme and hostname (i.e. https://host.something.com) to these paths, making a full URL.
But your code isn't doing that; you're trying to use the raw HREF value.
Later on in your program you use urljoin() which solves this issue, but you aren't doing that in the for l in l1: loop. Why not? | unknown | |
d674 | train | This is because font awesome requires the FontAwesome font-family to be applied to icon elements, in order to source and render the icons correctly.
Your styles are likely overwriting this FontAwesome behaviour.
One way to fix this would be to ensure font awesome's .fas class still correctly applies the required FontAwesome font to .fas elements. You could do this by updating your CSS:
<style>
* {
font-family: "Open Sans", sans-serif;
}
.fas {
font-family:FontAwesome;
}
</style>
Or, if your browser supports the :not CSS3 selector:
<style>
*:not(.fas) {
font-family: "Open Sans", sans-serif;
}
</style>
A: If you are using Font Awesome 5 You can use this
.fab
{
font-family: 'Font Awesome 5 Brands' !important;
}
.fas, .far, .fa
{
font-family: 'Font Awesome 5 Free' !important;
} | unknown | |
d675 | train | I'm afraid your reference imlementation for strcmp() is both inaccurate and irrelevant:
*
*it is inaccurate because it compares characters using the char type instead of the unsigned char type as specified in the C11 Standard:
7.24.4 Comparison functions
The sign of a nonzero value returned by the comparison functions memcmp, strcmp, and strncmp is determined by the sign of the difference between the values of the first pair of characters (both interpreted as unsigned char) that differ in the objects being compared.
*It is irrelevant because the actual implementation used by modern compilers is much more sophisticated, expanded inline using hand-coded assembly language.
Any generic implementation is likely to be less optimal, especially if coded to remain portable across platforms.
Here are a few directions to explore if your program's bottleneck is comparing strings.
*
*Analyze your algorithms, try and find ways to reduce the number of comparisons: for example if you search for a string in an array, sorting that array and using a binary search with drastically reduce the number of comparisons.
*If your strings are tokens used in many different places, allocate unique copies of these tokens and use those as scalar values. The strings will be equal if and only if the pointers are equal. I use this trick in compilers and interpreters all the time with a hash table.
*If your strings have the same known length, you can use memcmp() instead of strcmp(). memcmp() is simpler than strcmp() and can be implemented even more efficiently in places where the strings are known to be properly aligned.
EDIT: with the extra information provided, you could use a structure like this for your strings:
typedef struct string_t {
size_t len;
size_t hash; // optional
char str[]; // flexible array, use [1] for pre-c99 compilers
} string_t;
You allocate this structure this way:
string_t *create_str(const char *s) {
size_t len = strlen(s);
string_t *str = malloc(sizeof(*str) + len + 1;
str->len = len;
str->hash = hash_str(s, len);
memcpy(str->str, s, len + 1);
return str;
}
If you can use these str things for all your strings, you can greatly improve the efficiency of the matching by first comparing the lengths or the hashes. You can still pass the str member to your library function, it is properly null terminated. | unknown | |
d676 | train | First of all create a more specific fetch request to get a distinct result type
let request = NSFetchRequest<Numbers>(entityName: "Numbers")
A comma separated list is not possible because the type of userNumbers is numeric.
You can map the result to an array of Int16 with
do {
let result = try context.fetch(request) // the type is [Numbers]
let numberArray = result.map{$0.userNumbers}
print(numberArray)
} | unknown | |
d677 | train | You can use the DataFrame.explode method, followed by groupby and size:
I am going to just use a simple .str.split instead of your function, as I don't know where word_tokenize comes from.
In [1]: import pandas as pd
In [2]: df = pd.DataFrame({'title': ['Hello World', 'Foo Bar'], 'date': ['2021-01-12T20:00', '2021-02-10T22:00']})
In [3]: df['words'] = df['title'].apply(lambda s: process_title(str(s)))
In [4]: df
Out[4]:
title date words
0 Hello World 2021-01-12T20:00 [Hello, World]
1 Foo Bar 2021-02-10T22:00 [Foo, Bar]
In [5]: exploded = df.explode('words')
In [6]: exploded
Out[6]:
title date words
0 Hello World 2021-01-12T20:00 Hello
0 Hello World 2021-01-12T20:00 World
1 Foo Bar 2021-02-10T22:00 Foo
1 Foo Bar 2021-02-10T22:00 Bar
In [7]: exploded.groupby(['date', 'words']).size()
Out[7]:
date words
2021-01-12T20:00 Hello 1
World 1
2021-02-10T22:00 Bar 1
Foo 1
dtype: int64 | unknown | |
d678 | train | informatica only solution -
*
*Create an exp transformation with three ports.
in_out_Heading1
in_out_Heading2
out_date_trunc=TRUNC(in_out_Heading2)
*Next, use an agg transformation with below ports.
in_out_Heading1 --group by port
in_Heading2
in_date_trunc --group by port
out_Heading2=MAX(in_Heading2)
And then connect out_Heading2 and in_out_Heading1 to your final target.
A: You can group by extracted date value, so need a conversion such as the one below
SELECT heading1, MAX(heading2)
FROM t
GROUP BY heading1, TRUNC(heading2)
the above SELECT statement is based on the Oracle database, you can replace TRUNC(heading2) depending on your current DBMS. The data type of heading2 is presumed to be TIMESTAMP | unknown | |
d679 | train | This is a common problem when setting up SSL for a web site. This issue is that your web pages are being requested using HTTPS but the page itself is requesting resources using HTTP.
Start Google Chrome (or similar). Load your web site page. Press F-12 to open the debugger. Press F-5 to refresh the page. Note any lines that look like the following:
Mixed Content: The page at 'https://mywebsite.com/' was loaded over
HTTPS, but requested an insecure image
'http://mywebsite.com/images/homepage_top.png'. This content should
also be served over HTTPS.
You will then need to edit the HTML content (or page generator such as PHP) to correctly use HTTPS instead of HTTP. | unknown | |
d680 | train | there was a bug recently in the js sdk when you set the response type server-side (to get the code & refresh_token), so you may have to redownload oauth.js if you use a static version.
I guess your jquery code is server side (because of the nodejs tag and the use of a code), but i had an error "no transport" that i fixed with a new XMLHttpRequest. Here is my full test:
var jsdom = require('jsdom').jsdom;
var win = jsdom().createWindow();
var $ = require('jquery')(win);
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
$.support.cors = true;
$.ajaxSettings.xhr = function () {
return new XMLHttpRequest;
}
$.ajax("https://oauth.io/auth/access_token", {
type: "post",
data: {
code: process.argv[2],
key: 'xxxxxxxxxxxx',
secret: 'yyyyyyyyyyyy' },
success: function (data) {
console.log("result", data);
},
error: function() {
console.error(arguments);
}
});
and my result looks like:
{ access_token: 'xxxxxxxxxxx',
request:
{ url: '{{instance_url}}',
required: [ 'instance_url' ],
headers: { Authorization: 'Bearer {{token}}' } },
refresh_token: 'yyyyyyyyyyyyy',
id: 'https://login.salesforce.com/id/00Db0000000ZbGGEA0/005b0000000SSGXAA4',
instance_url: 'https://eu2.salesforce.com',
signature: 'zzzzzzzzzzzzz',
state: 'random_string',
provider: 'salesforce' } | unknown | |
d681 | train | Add an event to your balloon class, handle the click in your balloon class and pass the arguments up to whoever attaches to your event.
In your balloon class:
public partial class ApplicationBalloon : UserControl
{
public event EventHandler<RoutedEventArgs> BalloonClicked;
private void OnButtonClicked(object sender, RoutedEventArgs e)
{
if (BalloonClicked != null)
BalloonClicked(sender, e);
}
}
You can now add a handler to your main form attached to BalloonClicked.
A: Just access it with:
Application.Current.MainWindow
And cast it to whatever your main window type is. | unknown | |
d682 | train | Create a basic splash screen without a cordova-plugin-splashscreen plugin. In this example the splash screen is removed using afterEnter view event. The idea is simple, show a fixed overlay container over a rest of the content.
Add this DIV to your HTML page. Inside that DIV you have logo and input fields.
<div id="custom-splashscreen">
<div class="item item-image">
<img src="http://3.bp.blogspot.com/-fGX23IjV0xs/VcRc4TLU_fI/AAAAAAAAAKk/ys3cyQz6fQc/s1600/download.jpg">
</div>
<div class="card">
<div class="item item-text-wrap">
<div class="list">
<label class="item item-input">
<input type="text" placeholder="First Name">
</label>
<label class="item item-input">
<input type="text" placeholder="Last Name">
</label>
<label class="item item-input">
<textarea placeholder="Comments"></textarea>
</label>
</div>
</div>
</div>
</div>
Add this to css/style.css. Customize CSS depending on what you want to achieve.
#custom-splashscreen {
display: flex;
flex-direction: column;
justify-content: center;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 100;
background-color: #771313;
}
#custom-splashscreen .item-image {
display: block;
margin: 0 auto;
width: 50%;
height: auto;
background-color: #771313;
}
Add this to your controller if you want that splash screen disappear after a specified number of seconds. Considering that you have input fields I guess you do not want splash screen to disappears. In controller you can put whatever you want. For example, a splash screen will be removed after a user clicks on the button.
$scope.$on('$ionicView.afterEnter', function() {
setTimeout(function() {
document.getElementById("custom-splashscreen").style.display = "none";
}, 3000);
})
Splash screen should look like this. As you can see it have logo and input fields.
P.S. For the purposes of development add CORS plugin to Chrome and enable it while you work on app. | unknown | |
d683 | train | It depends on your DB2 platform and version. Timestamps in DB2 used to all have 6 digit precision for the fractional seconds portion. In string form, "YYYY-MM-DD-HH:MM:SS.000000"
However, DB2 LUW 10.5 and DB2 for IBM i 7.2 support from 0 to 12 digits of precision for the fraction seconds portion. In string form, you could have from "YYYY-MM-DD-HH:MM:SS" to "YYYY-MM-DD-HH:MM:SS.000000000000".
The default precision is 6, so if you specify a timestamp without a precision (length), you get the six digit precision. Otherwise you may specify a precision from o to 12.
create table mytable (
ts0 timestamp(0)
, ts6 timestamp
, ts6_also timestamp(6)
, ts12 timestamp(12)
);
Note however, that while the external (not exactly a string) format the DBMS surfaces could vary from 19 to 32 bytes. The internal format the TS is stored in may not. On DB2 for IBM i at least the internal storage format of TS field takes between 7 and 13 bytes depending on precision.
*
*timestamp(0) -> 7 bytes
*timestamp(6) -> 10 bytes (default)
*timestamp(12) -> 13 bytes
A: Since you refer to 10 as the length, I'm going to assume you're looking in SYSIBM.SYSCOLUMNS (or another equivalent table in the catalog.
The LENGTH column in the catalog refers to the internal length of the field. You can calculate this using the following formula:
FLOOR( ((p+1)/2) + x )
*
*p is the precision of the timestamp (the number of places after the decimal [the microseconds])
*x is 7 for a timestamp without a timezone, or 9 if it has a timezone (if supported by your platform)
If you are comparing the to a field in the SQLCA, that field will be the length of a character representation of the timestamp. See this Information Center article for an explanation between the two fields.
If you truly want to change the scale of your timestamp field, then you can use the following statement. x should be an integer for the number of places after the decimal in the seconds position.
The number of allowed decimals varies by platform and version. If you're on an older version, you can likely not change the scale, which is set at 6. However, some of the newer platforms (like z/OS 10+, LUW 9.7+), will allow you to set the scale to a number between 0 and 12 (inclusive).
ALTER TABLE SESSION.TSTAMP_TEST
ALTER COLUMN tstamp
SET DATA TYPE TIMESTAMP(x); | unknown | |
d684 | train | Make sure the package.json for your library includes the main field (see https://docs.npmjs.com/files/package.json#main), which should be the transpiled .js file that has your module in it.
I created a component library using https://github.com/flauc/angular2-generator and was able to get it to work.
Also, here's an excellent example of creating a component library using the Angular CLI: See https://github.com/nsmolenskii/ng-demo-lib and https://github.com/nsmolenskii/ng-demo-app. | unknown | |
d685 | train | Shamelessly copying from a user note on the documentation page:
$buffer = fopen('php://temp', 'r+');
fputcsv($buffer, $data);
rewind($buffer);
$csv = fgets($buffer);
fclose($buffer);
// Perform any data massaging you want here
echo $csv;
All of this should look familiar, except maybe php://temp.
A: $output = fopen('php://output', 'w');
fputcsv($output, $line);
fclose($output);
Or try one of the other supported wrappers, like php://memory if you don't want to output directly. | unknown | |
d686 | train | INSERT INTO Destination(Col)
SELECT COUNT(1) FROM Source;
A: You can use triggers to automatically update comments tables based on likes table.
The following in an Insert After Trigger which will increment the value of total_likes of the corresponding comment_id by one in comments table when an insert in performed in likes table.
You have to give initial value of total_likes for comments as zero when inserting in comments table.
CREATE TRIGGER update_likes AFTER INSERT ON likes
FOR EACH ROW
UPDATE comments
SET total_likes = total_likes+1
WHERE comment_id = NEW.comment_id;
A: If you want a query that resolve this.
I suggest some like this:
select comment_id,uploader,
(select count(*) from likes l where L.COMMENT_ID =CM.COMMENT_ID ) nlikes
from commments cm; | unknown | |
d687 | train | You can implement a class inherited from EventHandler. For this class you can implement any additional behavior you want. For instance, you can create a collection which will hold object-event maps and you can implement a method which searches for a given pair or pattern.
A: you can do this assuming you have access to source of class. Beware this way you are giving away the control of when to call all delegates to client of your class which is not a good idea. If you are not looking for the list of eventhandler but just want to know if event is subscribed.Probably you can use the other method which only tells whether click event is subscribed by anyone.
class MyButton
{
delegate void ClickHandler(object o ,EventArgs e);
public event ClickHandler Click;
......
public List<ClickHandler> ClickHandlerList
{
get
{
return ClickHandler.GetInovationList().Cast<ClickHandler>().ToList();
}
}
public bool IsClickEventSubcribed
{
get
{
return ClickHandler.GetInovationList().Cast<ClickHandler>().Any();
}
}
}
A: If the purpose of this is to stop sending signals to event listeners, wouldn't it be easier just wrap the sending by the check?
if (NotifyingEnabled)
{
SomeEvent.Raise(this);
} | unknown | |
d688 | train | Try treating the path as a raw string literal, by putting an "r" before the quote immediately before ${EXECDIR}:
${firefox_binary}= Evaluate ....FirefoxBinary(r'${EXECDIR}${/}Firefox...')
This should work because the robot variables are substituted before the string is passed to python, so the python interpreter only ever sees the complete string.
If you are unfamiliar with python raw string literals, see this question:
What exactly do “u” and “r” string flags do in Python, and what are raw string literals? | unknown | |
d689 | train | Looks like you have a mix of CentOS and RedHat bits. Delete whatever you added. CentOS is easy (examples below). For RedHat if you aren't a registered machine you'll want to use the DVD ISO as source (baseurl=file:///media) or maybe attach to a public EPEL.
Here's a CentOS /etc/yum.conf.
[main]
cachedir=/var/cache/yum/$basearch/$releasever
keepcache=0
debuglevel=2
logfile=/var/log/yum.log
exactarch=1
obsoletes=1
gpgcheck=1
plugins=1
installonly_limit=5
bugtracker_url=http://bugs.centos.org/set_project.php?project_id=16&ref=http://bugs.centos.org/bug_report_page.php?category=yum distroverpkg=centos-release
And then you should have a few repos that already exist in /etc/yum.repos.d (base/debuginfo/media/vault). Hers's /etc/yum.repos.d/CentOS-Base.repo
[base]
name=CentOS-$releasever - Base
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os
#baseurl=http://mirror.centos.org/centos/$releasever/os/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6
#released updates
[updates]
name=CentOS-$releasever - Updates
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates
#baseurl=http://mirror.centos.org/centos/$releasever/updates/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6
#additional packages that may be useful
[extras]
name=CentOS-$releasever - Extras
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras
#baseurl=http://mirror.centos.org/centos/$releasever/extras/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6
#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-$releasever - Plus
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus
#baseurl=http://mirror.centos.org/centos/$releasever/centosplus/$basearch/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6
#contrib - packages by Centos Users
[contrib]
name=CentOS-$releasever - Contrib
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=contrib
#baseurl=http://mirror.centos.org/centos/$releasever/contrib/$basearch/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6 | unknown | |
d690 | train | Not 100% sure, but you might want to connect the output of the AnalyserNode to the destination node. You may want to stick a GainNode with a gain of 0 in between, just in case you don't really want the audio from the AnalyserNode to be played out. | unknown | |
d691 | train | Move your deslectRowAtIndexPath message call below the assignment of your row variable:
NSInteger row = [[self tableView].indexPathForSelectedRow row];
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES]; | unknown | |
d692 | train | Use getTitle():
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.<manuLayout>, menu);
MenuItem menuItem = menu.findItem(R.id.do_it);
String title = menuItem.getTitle();
return true;
} | unknown | |
d693 | train | As of Riverpod 0.14.0, the way we work with StateNotifier is a bit different.
Now, state is the default property exposed, so to listen to the state, simply:
final counterModel = useProvider(provider);
To access any functions, etc. on your StateNotifier, access the notifier:
final counterModel = useProvider(provider.notifier);
And now when we create StateNotifierProviders, we include the type of the state of the StateNotifier:
final provider = StateNotifierProvider<CounterNotifier, CounterModel>((ref) => CounterNotifier());
See more on the changes from 0.13.0 -> 0.14.0 here. | unknown | |
d694 | train | I agree it would be nice if one of the columns were dropped. Of course, then there is the question of what to name the remaining column.
Anyway, here is a workaround. Simply rename one of the columns so that the joined column(s) have the same name:
In [23]: df1 = pd.DataFrame({'imp_type':[1,2,3], 'value':['abc','def','ghi']})
In [27]: df2 = pd.DataFrame({'id':[1,2,3], 'value2':[123,345,567]})
In [28]: df2.columns = ['imp_type','value2']
In [29]: df1.merge(df2, on='imp_type')
Out[29]:
imp_type value value2
0 1 abc 123
1 2 def 345
2 3 ghi 567
Renaming the columns is a bit of a pain, especially (as DSM points out) compared to .drop('id', 1). However, if you can arrange for the joined columns to have the same name from the very beginning, then df1.merge(df2, on='imp_type') would be easiest. | unknown | |
d695 | train | You may find this useful, full algorithm description is here. They grid out the probes uniformly, informing this choice (e.g. normal centering on a reputed high energy arm) is also possible (but this might invalidate a few bounds I am not sure). | unknown | |
d696 | train | You can get current file path as either absolute or relative using groovyScript macro:
_editor variable is available inside the script. This variable is bound to the current editor. The _editor is an instance of EditorImpl
which holds a reference to the VirtualFile that represents the
currently opened file.
Therefore, the following script gets the full path of currently opened file.
groovyScript("_editor.getVirtualFile().getPath()")
Or if you want to get the path relative to the project's root:
groovyScript("_editor.getVirtualFile().getPath().replace(_editor.getProject().getBaseDir().getPath(), \"\")")
see:
Current file path in Live Template | unknown | |
d697 | train | There are a lot of ways to do this:
*
*Write a string into .txt file and upload the file to a storage container on Azure Portal.
*Generate a long lifetime SAS token on Azure Portal:
and use blob rest API to upload it to a blob, you can do it directly in postman:
Result:
*Use Azure Logic App to do this. Let me know if you have any more questions.
Let me know if you have any more questions. | unknown | |
d698 | train | If you really want every piece of data, you're going to be retrieving the same number of rows, no matter how you do it. Best to get it all in one query.
SELECT schedule.id, overrides.id, locations.id, locations.name
FROM schedule
JOIN overrides ON overrides.schedule_id = schedule.id
JOIN locations ON locations.override_id = overrides.id
ORDER BY schedule.id, overrides.id, locations.id
By ordering the results like this, you can iterate through the result set and move on to the next schedule whenever the scheduleid changes, and the next location when the locationid changes.
Edit: a possible example of how to turn this data into a 3-dimensional array -
$last_schedule = 0;
$last_override = 0;
$schedules = array();
while ($row = mysql_fetch_array($query_result))
{
$schedule_id = $row[0];
$override_id = $row[1];
$location_id = $row[2];
$location_name = $row[3];
if ($schedule_id != $last_schedule)
{
$schedules[$schedule_id] = array();
}
if ($override_id != $last_override)
{
$schedules[$schedule_id][$override_id] = array();
}
$schedules[$schedule_id][$override_id][$location_id] = $location_name;
$last_schedule = $schedule_id;
$last_override = $override_id;
}
Quite primitive, I imagine your code will look different, but hopefully it makes some sense. | unknown | |
d699 | train | Have you tried using the offset*classes?
http://twitter.github.io/bootstrap/scaffolding.html | unknown | |
d700 | train | Since they are distinguished by spaces and your strings themselves have spaces using the extracted text will probably not be too helpful. I would have to see the full pdf to know if this would work but try:
From tabula import read_pdf
df = read_pdf("grocery2.pdf")
Then you can do any dataframe operations to extract different values ie.
df1 = df[['UPC', 'Product Description']] | unknown |