If you're trying to insert in to last_accessed_on
, which is a DateTime2
, then your issue is with the fact that you are converting it to a varchar
in a format that SQL doesn't understand.
If you modify your code to this, it should work, note the format of your date has been changed to: YYYY-MM-DD hh:mm:ss:
UPDATE student_queues
SET Deleted=0,
last_accessed_by='raja',
last_accessed_on=CONVERT(datetime2,'2014-07-23 09:37:00')
WHERE std_id IN ('2144-384-11564') AND reject_details='REJECT'
Or if you want to use CAST
, replace with:
CAST('2014-07-23 09:37:00.000' AS datetime2)
This is using the SQL ISO Date Format.
At https://github.com/golang/go/issues/44196 randall77 suggested
time.Now().Sub(time.Unix(0,0)).Milliseconds()
which exploits the fact that Go's time.Duration
already have Milliseconds
method.
select datename(DAY,GETDATE()) +'-'+ datename(MONTH,GETDATE()) +'- '+
datename(YEAR,GETDATE()) as 'yourcolumnname'
The correct way to get the integer value of an Enum such as DayOfWeek as a string is:
DayOfWeek.ToString("d")
I know this is old, but, in running into a vendor that inconsistently uses 5 different date formats in their APIs (and test servers with a variety of PHP versions from the 5's through the latest 7's), I decided to write a universal converter that works with a myriad of PHP versions.
This converter will take virtually any input, including any standard datetime format (including with or without milliseconds) and any Epoch Time representation (including with or without milliseconds) and convert it to virtually any other format.
To call it:
$TheDateTimeIWant=convertAnyDateTome_toMyDateTime([thedateIhave],[theformatIwant]);
Sending null for the format will make the function return the datetime in Epoch/Unix Time. Otherwise, send any format string that date() supports, as well as with ".u" for milliseconds (I handle milliseconds as well, even though date() returns zeros).
Here's the code:
<?php
function convertAnyDateTime_toMyDateTime($dttm,$dtFormat)
{
if (!isset($dttm))
{
return "";
}
$timepieces = array();
if (is_numeric($dttm))
{
$rettime=$dttm;
}
else
{
$rettime=strtotime($dttm);
if (strpos($dttm,".")>0 and strpos($dttm,"-",strpos($dttm,"."))>0)
{
$rettime=$rettime.substr($dttm,strpos($dttm,"."),strpos($dttm,"-",strpos($dttm,"."))-strpos($dttm,"."));
$timepieces[1]="";
}
else if (strpos($dttm,".")>0 and strpos($dttm,"-",strpos($dttm,"."))==0)
{
preg_match('/([0-9]+)([^0-9]+)/',substr($dttm,strpos($dttm,"."))." ",$timepieces);
$rettime=$rettime.".".$timepieces[1];
}
}
if (isset($dtFormat))
{
// RETURN as ANY date format sent
if (strpos($dtFormat,".u")>0) // Deal with milliseconds
{
$rettime=date($dtFormat,$rettime);
$rettime=substr($rettime,0,strripos($rettime,".")+1).$timepieces[1];
}
else // NO milliseconds wanted
{
$rettime=date($dtFormat,$rettime);
}
}
else
{
// RETURN Epoch Time (do nothing, we already built Epoch Time)
}
return $rettime;
}
?>
Here's some sample calls - you will note it also handles any time zone data (though as noted above, any non GMT time is returned in your time zone).
$utctime1="2018-10-30T06:10:11.2185007-07:00";
$utctime2="2018-10-30T06:10:11.2185007";
$utctime3="2018-10-30T06:10:11.2185007 PDT";
$utctime4="2018-10-30T13:10:11.2185007Z";
$utctime5="2018-10-30T13:10:11Z";
$dttm="10/30/2018 09:10:11 AM EST";
echo "<pre>";
echo "<b>Epoch Time to a standard format</b><br>";
echo "<br>Epoch Tm: 1540905011 to STD DateTime ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011","Y-m-d H:i:s")."<hr>";
echo "<br>Epoch Tm: 1540905011 to UTC ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011","c");
echo "<br>Epoch Tm: 1540905011.2185007 to UTC ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011.2185007","c")."<hr>";
echo "<b>Returned as Epoch Time (the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC), minus leap seconds.)";
echo "</b><br>";
echo "<br>UTCTime1: ".$utctime1." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime1,null);
echo "<br>UTCTime2: ".$utctime2." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime2,null);
echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,null);
echo "<br>UTCTime4: ".$utctime4." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime4,null);
echo "<br>UTCTime5: ".$utctime5." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime5,null);
echo "<br>NO MILIS: ".$dttm." ----RESULT: ".convertAnyDateTime_toMyDateTime($dttm,null);
echo "<hr>";
echo "<hr>";
echo "<b>Returned as whatever datetime format one desires</b>";
echo "<br>UTCTime1: ".$utctime1." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime1,"Y-m-d H:i:s")." Y-m-d H:i:s";
echo "<br>UTCTime2: ".$utctime2." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime2,"Y-m-d H:i:s.u")." Y-m-d H:i:s.u";
echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,"Y-m-d H:i:s.u")." Y-m-d H:i:s.u";
echo "<p><b>Returned as ISO8601</b>";
echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,"c")." ISO8601";
echo "</pre>";
Here's the output:
Epoch Tm: 1540905011 ----RESULT: 2018-10-30 09:10:11
Epoch Tm: 1540905011 to UTC ----RESULT: 2018-10-30T09:10:11-04:00
Epoch Tm: 1540905011.2185007 to UTC ----RESULT: 2018-10-30T09:10:11-04:00
Returned as Epoch Time (the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC), minus leap seconds.)
UTCTime1: 2018-10-30T06:10:11.2185007-07:00 ----RESULT: 1540905011.2185007
UTCTime2: 2018-10-30T06:10:11.2185007 ----RESULT: 1540894211.2185007
UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 1540905011.2185007
UTCTime4: 2018-10-30T13:10:11.2185007Z ----RESULT: 1540905011.2185007
UTCTime5: 2018-10-30T13:10:11Z ----RESULT: 1540905011
NO MILIS: 10/30/2018 09:10:11 AM EST ----RESULT: 1540908611
Returned as whatever datetime format one desires
UTCTime1: 2018-10-30T06:10:11.2185007-07:00 ----RESULT: 2018-10-30 09:10:11 Y-m-d H:i:s
UTCTime2: 2018-10-30T06:10:11.2185007 ----RESULT: 2018-10-30 06:10:11.2185007 Y-m-d H:i:s.u
UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 2018-10-30 09:10:11.2185007 Y-m-d H:i:s.u
Returned as ISO8601
UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 2018-10-30T09:10:11-04:00 ISO8601
The only thing not in this version is the ability to select the time zone you want the returned datetime to be in. Originally, I wrote this to change any datetime to Epoch Time, so, I didn't need time zone support. It's trivial to add though.
To convert the epoch(Unix-Time) to regular time like for the below timestamp
Ex: 1517577336206
First convert the value with the following function like below
=LEFT(A1,10) & "." & RIGHT(A1,3)
The output will be like below
Ex: 1517577336.206
Now Add the formula like below
=(((B1/60)/60)/24)+DATE(1970,1,1)
Now format the cell like below or required format(Custom format)
m/d/yyyy h:mm:ss.000
Now example time comes like
2/2/2018 13:15:36.206
The three zeros are for milliseconds
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date date = (Date)formatter.parse("12-December-2012");
long mills = date.getTime();
...and if you're using purely XOM, something like this:
String xml = "<fakeRoot>" + xml + "</fakeRoot>";
Document doc = new Builder( false ).build( xml, null );
Nodes children = doc.getRootElement().removeChildren();
for( int ix = 0; ix < children.size(); ix++ ) {
otherDocumentElement.appendChild( children.get( ix ) );
}
XOM uses fakeRoot internally to do pretty much the same, so it should be safe, if not exactly elegant.
When you close the video you just need to pause it.
$("#closeSimple").click(function() {
$("div#simpleModal").removeClass("show");
$("#videoContainer")[0].pause();
return false;
});
<video id="videoContainer" width="320" height="240" src="Davis_5109iPadFig3.m4v" controls="controls"> </video>
Also, for reference, here's the Opera documentation for scripting video controls.
You actually don't have access to filesystem (for example reading and writing local files), however, due to HTML5 File Api specification, there are some file properties that you do have access to, and the file size is one of them.
For the HTML below
<input type="file" id="myFile" />
try the following:
//binds to onchange event of your input field
$('#myFile').bind('change', function() {
//this.files[0].size gets the size of your file.
alert(this.files[0].size);
});
As it is a part of the HTML5 specification, it will only work for modern browsers (v10 required for IE) and I added here more details and links about other file information you should know: http://felipe.sabino.me/javascript/2012/01/30/javascipt-checking-the-file-size/
Old browsers support
Be aware that old browsers will return a null
value for the previous this.files
call, so accessing this.files[0]
will raise an exception and you should check for File API support before using it
In addition to the other answers, on a recent C library (Posix 2008 compliant), you could use getline. See this answer (to a related question).
Use the CAST
to the new DATE
data type in SQL Server 2008 to compare just the date portion:
IF CAST(DateField1 AS DATE) = CAST(DateField2 AS DATE)
In my "Ubuntu 16.04", I use next steps to completely remove and clean Kubernetes (installed with "apt-get"):
kubeadm reset
sudo apt-get purge kubeadm kubectl kubelet kubernetes-cni kube*
sudo apt-get autoremove
sudo rm -rf ~/.kube
And restart the computer.
I encountered this error when running my Android app on my home WiFi, then trying to run it on different WiFi without closing my simulator.
Simply closing the simulator and re-launching the app worked for me!
You can try the Anthem library.
here is the sample code to draw image on canvas-
$("#selectedImage").change(function(e) {
var URL = window.URL;
var url = URL.createObjectURL(e.target.files[0]);
img.src = url;
img.onload = function() {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, 500, 500);
}});
In the above code selectedImage is an input control which can be used to browse image on system. For more details of sample code to draw image on canvas while maintaining the aspect ratio:
http://newapputil.blogspot.in/2016/09/show-image-on-canvas-html5.html
I reference all the methods.
Encode the query twice is the fast solution.
const query = a=123&b=456;
const url = `https://example.com/test?${encodeURIComponent(encodeURIComponent(query),)}`;
const twitterSharingURL=`https://twitter.com/intent/tweet?&url=${url}`
you can use String format to include variables within strings
i use this code to include 2 variable in string:
String myString = String.format("this is my string %s %2d", variable1Name, variable2Name);
Simple way to iterate over class fields and obtain values from object:
Class<?> c = obj.getClass();
Field[] fields = c.getDeclaredFields();
Map<String, Object> temp = new HashMap<String, Object>();
for( Field field : fields ){
try {
temp.put(field.getName().toString(), field.get(obj));
} catch (IllegalArgumentException e1) {
} catch (IllegalAccessException e1) {
}
}
Properties that are database specific are:
hibernate.connection.driver_class
: JDBC driver classhibernate.connection.url
: JDBC URLhibernate.connection.username
: database userhibernate.connection.password
: database passwordhibernate.dialect
: The class name of a Hibernate org.hibernate.dialect.Dialect
which allows Hibernate to generate SQL optimized for a particular relational database. To change the database, you must:
Dialect
used by Hibernate to talk to the databaseThere are two drivers to connect to SQL Server; the open source jTDS and the Microsoft one. The driver class and the JDBC URL depend on which one you use.
The driver class name is net.sourceforge.jtds.jdbc.Driver
.
The URL format for sqlserver is:
jdbc:jtds:sqlserver://<server>[:<port>][/<database>][;<property>=<value>[;...]]
So the Hibernate configuration would look like (note that you can skip the hibernate.
prefix in the properties):
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>
<property name="connection.url">jdbc:jtds:sqlserver://<server>[:<port>][/<database>]</property>
<property name="connection.username">sa</property>
<property name="connection.password">lal</property>
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
...
</session-factory>
</hibernate-configuration>
The driver class name is com.microsoft.sqlserver.jdbc.SQLServerDriver
.
The URL format is:
jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]
So the Hibernate configuration would look like:
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="connection.url">jdbc:sqlserver://[serverName[\instanceName][:portNumber]];databaseName=<databaseName></property>
<property name="connection.username">sa</property>
<property name="connection.password">lal</property>
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
...
</session-factory>
</hibernate-configuration>
That's not possible using the built-in Array.prototype.map
. However, you could use a simple for
-loop instead, if you do not intend to map
any values:
var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] < 10) {
hasValueLessThanTen = true;
break;
}
}
Or, as suggested by @RobW
, use Array.prototype.some
to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:
var hasValueLessThanTen = myArray.some(function (val) {
return val < 10;
});
I got this when installing a library using anaconda. My version went from Python 3.* to 2.7 and a lot of my stuff stopped working. The best solution I found was to first see the most recent version available:
conda search python
Then update to the version you want:
conda install python=3.*.*
Source: http://chris35wills.github.io/conda_python_version/
Other helpful commands:
conda info
python --version
Try using additional condition in join:
SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1
INNER JOIN Table2
ON (Table1.Col1 = Table2.Col1
OR (Table1.Col1 IS NULL AND Table2.Col1 IS NULL)
)
A simple way to do it without the use of such a complicated draw statement:
//Make a backup so that we can reset our graphics object after using it.
AffineTransform backup = g2d.getTransform();
//rx is the x coordinate for rotation, ry is the y coordinate for rotation, and angle
//is the angle to rotate the image. If you want to rotate around the center of an image,
//use the image's center x and y coordinates for rx and ry.
AffineTransform a = AffineTransform.getRotateInstance(angle, rx, ry);
//Set our Graphics2D object to the transform
g2d.setTransform(a);
//Draw our image like normal
g2d.drawImage(image, x, y, null);
//Reset our graphics object so we can draw with it again.
g2d.setTransform(backup);
Sample:
var namespace = {};
namespace.module1 = (function(){
var self = {};
self.initialized = false;
self.init = function(){
setTimeout(self.onTimeout, 1000)
};
self.onTimeout = function(){
alert('onTimeout')
self.initialized = true;
};
self.init(); /* If it needs to auto-initialize, */
/* You can also call 'namespace.module1.init();' from outside the module. */
return self;
})()
You can optionally declare a local
variable, same
, like self
and assign local.onTimeout
if you want it to be private.
i had got the same error. Actually i tried to override the flutter Old SDK Package with new Updated Package. so that error occurred.
i opened flutter sdk directory with VS Code and cleaned the project
use this code in VSCode cmd
git clean -dxf
then use git pull
Container widths will drop down to 940 pixels for viewports less than 992 pixels. If you really don’t want containers larger than 940 pixels wide, then go to the Bootstrap customize page, and set @container-lg-desktop
to either @container-desktop
or hard-coded 940px
.
If you know the values are 0 or 1, you could do flipval ^= 1
.
It also doesn't hurt to watermark your images with Photoshop or even in Lightroom 3 now. Make sure the watermark is clear and in a conspicuous place on your image. That way if it's downloaded, at least you get the advertising!
You can directly make your Background Blur using "Visual Effect View with Blur" and "Visual Effect View with Blur and Vibrancy".
All you have to do for making Blur Background in iOS Application is...
Application Layout before clicking on any Button!
Application View After Clicking on Button which makes the whole application background Blur!
Well, I can't see Tony's solution...so I have to handle it myself...
If you don't need version_key, you can just:
var UserSchema = new mongoose.Schema({
nickname: String,
reg_time: {type: Date, default: Date.now}
}, {
versionKey: false // You should be aware of the outcome after set to false
});
Setting the versionKey to false means the document is no longer versioned.
This is problematic if the document contains an array of subdocuments. One of the subdocuments could be deleted, reducing the size of the array. Later on, another operation could access the subdocument in the array at it's original position.
Since the array is now smaller, it may accidentally access the wrong subdocument in the array.
The versionKey solves this by associating the document with the a versionKey, used by mongoose internally to make sure it accesses the right collection version.
More information can be found at: http://aaronheckmann.blogspot.com/2012/06/mongoose-v3-part-1-versioning.html
I had the same issue but then realised there is a table with the same name in the database. After deleting that I was able to import the file.
Instead of navigating to blank, you can do
webBrowser1.DocumentText="0";
webBrowser1.Document.OpenNew(true);
webBrowser1.Document.Write(theHTML);
webBrowser1.Refresh();
No need to wait for events or anything else. You can check the MSDN for OpenNew, while I have tested the initial DocumentText assignment in one of my projects and it works.
What can we build with NodeJS:
You can use git checkout.
I tried the accepted solution but got an error, warning: refname '<tagname>' is ambiguous'
But as the answer states, tags do behave like a pointer to a commit, so as you would with a commit hash, you can just checkout the tag. The only difference is you preface it with tags/
:
git checkout tags/<tagname>
Git can search diffs with the -S option (it's called pickaxe in the docs)
git log -S password
This will find any commit that added or removed the string password
. Here a few options:
-p
: will show the diffs. If you provide a file (-p file
), it will generate a patch for you.-G
: looks for differences whose added or removed line matches the given regexp, as opposed to -S
, which "looks for differences that introduce or remove an instance of string".--all
: searches over all branches and tags; alternatively, use --branches[=<pattern>]
or --tags[=<pattern>]
Google Drive folders can be embedded and displayed in list
and grid
views:
<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID#list" style="width:100%; height:600px; border:0;"></iframe>
<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID#grid" style="width:100%; height:600px; border:0;"></iframe>
Q: What is a folder ID (FOLDER-ID) and how can I get it?
A: Go to Google Drive >> open the folder >> look at its URL in the address bar of your browser. For example:
Folder URL: https://drive.google.com/drive/folders/0B1iqp0kGPjWsNDg5NWFlZjEtN2IwZC00NmZiLWE3MjktYTE2ZjZjNTZiMDY2
Folder ID:
0B1iqp0kGPjWsNDg5NWFlZjEtN2IwZC00NmZiLWE3MjktYTE2ZjZjNTZiMDY2
This technique works best for folders with public access. Folders that are shared only with certain Google accounts will cause trouble when you embed them this way. At the time of this edit, a message "You need permission" appears, with some buttons to help you "Request access" or "Switch accounts" (or possibly sign-in to a Google account). The Javascript in these buttons doesn't work properly inside an IFRAME
in Chrome.
Read more at https://productforums.google.com/forum/#!msg/drive/GpVgCobPL2Y/_Xt7sMc1WzoJ
I suspect you're only reporting the last error in a stack like this:
ORA-04068: existing state of packages has been discarded
ORA-04061: existing state of package body "schema.package" has been invalidated
ORA-04065: not executed, altered or dropped package body "schema.package"
ORA-06508: PL/SQL: could not find program unit being called: "schema.package"
If so, that's because your package is stateful:
The values of the variables, constants, and cursors that a package declares (in either its specification or body) comprise its package state. If a PL/SQL package declares at least one variable, constant, or cursor, then the package is stateful; otherwise, it is stateless.
When you recompile the state is lost:
If the body of an instantiated, stateful package is recompiled (either explicitly, with the "ALTER PACKAGE Statement", or implicitly), the next invocation of a subprogram in the package causes Oracle Database to discard the existing package state and raise the exception ORA-04068.
After PL/SQL raises the exception, a reference to the package causes Oracle Database to re-instantiate the package, which re-initializes it...
You can't avoid this if your package has state. I think it's fairly rare to really need a package to be stateful though, so you should revisit anything you have declared in the package, but outside a function or procedure, to see if it's really needed at that level. Since you're on 10g though, that includes constants, not just variables and cursors.
But the last paragraph from the quoted documentation means that the next time you reference the package in the same session, you won't get the error and it will work as normal (until you recompile again).
Just simply 'export' variable and 'import' in your class
export var GOOGLE_API_URL = 'https://www.googleapis.com/admin/directory/v1';
// default err string message
export var errStringMsg = 'Something went wrong';
Now use it as,
import appConstants = require('../core/AppSettings');
console.log(appConstants.errStringMsg);
console.log(appConstants.GOOGLE_API_URL);
In the current version of Sublime Text 2 (Build: 2139), you can set the syntax for all files of a certain file extension using an option in the menu bar. Open a file with the extension you want to set a default for and navigate through the following menus: View -> Syntax -> Open all with current extension as... ->[your syntax choice]
.
Updated 2012-06-28: Recent builds of Sublime Text 2 (at least since Build 2181) have allowed the syntax to be set by clicking the current syntax type in the lower right corner of the window. This will open the syntax selection menu with the option to Open all with current extension as...
at the top of the menu.
Updated 2016-04-19: As of now, this also works for Sublime Text 3.
If you're only interested in bailing if a particular argument is missing, Parameter Substitution is great:
#!/bin/bash
# usage-message.sh
: ${1?"Usage: $0 ARGUMENT"}
# Script exits here if command-line parameter absent,
#+ with following error message.
# usage-message.sh: 1: Usage: usage-message.sh ARGUMENT
DateTime? d=null;
DateTime d2;
bool success = DateTime.TryParse("some date text", out d2);
if (success) d=d2;
(There might be more elegant solutions, but why don't you simply do something as above?)
What you posted literally means "Find any divs that are inside of section divs and are the first child of their parent." The sub contains one tag that matches that description.
It is unclear to me whether you want both children of the main div or not. If so, use this:
div.section > div
If you only want the header, use this:
div.section > div:first-child
Using the >
changes the description to: "Find any divs that are the direct descendents of section divs" which is what you want.
Please note that all major browsers support this method, except IE6. If IE6 support is mission-critical, you will have to add classes to the child divs and use that, instead. Otherwise, it's not worth caring about.
You want to change it to
var list= document.getElementsByClassName("events");
console.log(list[0].id); //first console output
for (key in list){
console.log(list[key].id); //second console output
}
Use git show
, which also shows you the commit message, and defaults to the current commit when given no arguments.
That can't be done with a for
-loop, unless you use the Reflection API. However, you can use Arrays.asList
instead to accomplish the same:
List<Answer> answers = Arrays.asList(answer1, answer2, answer3);
No, Not if your website is on a remote server, i.e not on localhost.
Working fiddle:
$.ajax({
url: 'https://api.flightstats.com/flex/schedules/rest/v1/jsonp/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59',
dataType: 'JSONP',
jsonpCallback: 'callback',
type: 'GET',
success: function (data) {
console.log(data);
}
});
I had to manually set the callback to callback
, since that's all the remote service seems to support. I also changed the url to specify that I wanted jsonp.
It's good practice to give a parent to your QTimer
to use Qt's memory management system.
update()
is a QWidget function - is that what you are trying to call or not? http://qt-project.org/doc/qt-4.8/qwidget.html#update.
If number 2 does not apply, make sure that the function you are trying to trigger is declared as a slot in the header.
Finally if none of these are your issue, it would be helpful to know if you are getting any run-time connect errors.
This is a nice and neat way to send a value or object.
<!DOCTYPE html>
<html>
<body>
<h1 onclick="test('wow',this)">Click on this text!</h1>
<script>
var test = function(value,object) {
object.innerHTML= value;
};
</script>
</body>
</html>
I guess to get full browser comparability disabled
should set by the value disabled
or get removed!
Here is a small plugin that I've just made:
(function($) {
$.fn.toggleDisabled = function() {
return this.each(function() {
var $this = $(this);
if ($this.attr('disabled')) $this.removeAttr('disabled');
else $this.attr('disabled', 'disabled');
});
};
})(jQuery);
EDIT: updated the example link/code to maintaining chainability!
EDIT 2:
Based on @lonesomeday comment, here's an enhanced version:
(function($) {
$.fn.toggleDisabled = function(){
return this.each(function(){
this.disabled = !this.disabled;
});
};
})(jQuery);
Delete empty rows from Excel after your last row of data!
Some times empty rows in Excel are still considered as data, therefore trying to import them in a table with one or more non nullable columns violates the constrains of the column.
Solution: select all of the empty rows on your sheet, even those after your last row of data, and click delete rows.
Obviously, if some of your data really does vioalte any of your table's constraints, then just fix your data to match the rules of your database..
with jQuery:
$("#playerSource").attr("src", "new_src");
var audio = $("#player");
audio[0].pause();
audio[0].load();//suspends and restores all audio element
if (isAutoplay)
audio[0].play();
I think the best solutions is the mix of requests and BeautifulSoup, I just wanted to update the question so it can be kept updated.
EF Core: Using "ThenInclude" to load mutiple levels: For example:
var blogs = context.Blogs
.Include(blog => blog.Posts)
.ThenInclude(post => post.Author)
.ThenInclude(author => author.Photo)
.ToList();
I had all the correct packages and usings, but had to built first before I could get GetOwinContext()
to work.
The main difference between localStorage
and sessionStorage
is that sessionStorage
is unique per tab. If you close the tab the sessionStorage
gets deleted, localStorage
does not. Also you cannot communicate between tabs :)
Another subtle difference is that for example on Safari (8.0.3) localStorage
has a limit of 2551 k characters but sessionStorage
has unlimited storage
On Chrome (v43) both localStorage
and sessionStorage
are limited to 5101 k characters (no difference between normal / incognito mode)
On Firefox both localStorage
and sessionStorage
are limited to 5120 k characters (no difference between normal / private mode )
No difference in speed whatsoever :)
There's also a problem with Mobile Safari and Mobile Chrome, Private Mode Safari & Chrome have a maximum space of 0KB
Use jquery attr method. It works in all browsers.
var hiddenInput = document.createElement("input");
$(hiddenInput).attr({
'id':'uniqueIdentifier',
'type': 'hidden',
'value': ID,
'class': 'ListItem'
});
Or you could use folowing code:
var e = $('<input id = "uniqueIdentifier" type="hidden" value="' + ID + '" class="ListItem" />');
Use the java.lang.Math class, and specifically for absolute value and square root:, the abs()
and sqrt()
methods.
Swift 4.0 implementation :
use import in top of page by import EventKit
then
@IBAction func addtoCalendarClicked(sender: AnyObject) {
let eventStore = EKEventStore()
eventStore.requestAccess( to: EKEntityType.event, completion:{(granted, error) in
if (granted) && (error == nil) {
print("granted \(granted)")
print("error \(error)")
let event = EKEvent(eventStore: eventStore)
event.title = "Event Title"
event.startDate = Date()
event.endDate = Date()
event.notes = "Event Details Here"
event.calendar = eventStore.defaultCalendarForNewEvents
var event_id = ""
do {
try eventStore.save(event, span: .thisEvent)
event_id = event.eventIdentifier
}
catch let error as NSError {
print("json error: \(error.localizedDescription)")
}
if(event_id != ""){
print("event added !")
}
}
})
}
The best I've seen so far is HtmlCleaner:
HtmlCleaner is open-source HTML parser written in Java. HTML found on Web is usually dirty, ill-formed and unsuitable for further processing. For any serious consumption of such documents, it is necessary to first clean up the mess and bring the order to tags, attributes and ordinary text. For the given HTML document, HtmlCleaner reorders individual elements and produces well-formed XML. By default, it follows similar rules that the most of web browsers use in order to create Document Object Model. However, user may provide custom tag and rule set for tag filtering and balancing.
With HtmlCleaner you can locate any element using XPath.
For other html parsers see this SO question.
You can use a soft hyphen like so:
aaaaaaaaaaaaaaa­aaaaaaaaaaaaaaa
This will appear as
aaaaaaaaaaaaaaa-
aaaaaaaaaaaaaaa
if the containing box isn't big enough, or as
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
if it is.
Date.prototype.monthDays= function(){
var d= new Date(this.getFullYear(), this.getMonth()+1, 0);
return d.getDate();
}
If you want to insert element in std::map - use insert() function, and if you want to find element (by key) and assign some to it - use operator[].
For simplify inserting use boost::assign library, like this:
using namespace boost::assign;
// For inserting one element:
insert( function )( 0, 41 );
// For inserting several elements:
insert( function )( 0, 41 )( 0, 42 )( 0, 43 );
Thanks to @Arraxas's anwser, I customized the arrow and make the input
element auto-adaptive to the select
element, and it looks good on Chrome, Firefox of my Android mobile phone (set color:transparent
for select
and some color for option
to hide text display of the select
because the input
and .combobox div:after
cannot completely cover select
).
/* https://stackoverflow.com/questions/13694271/modify-select-so-only-the-first-one-is-gray/41941056#41941056
select option:first-child, */
.combobox select, .combobox select option { color: #000000; }
.combobox select:invalid, .combobox select option[value=""] { color:grey; }
.combobox {position:absolute; left:80px; top:6px;}
.combobox>div { position:relative; font-size:1em; }
.combobox select {
font-size:inherit; color:transparent;
padding:0; -moz-appearance:none; -webkit-appearance:none; appearance:none;
border:1px solid blueviolet;
}
.combobox input {
position:absolute;top:1px;left:0px; text-overflow:ellipsis;
box-sizing:border-box; padding:0px; margin:0px; height:calc(100% - 1px); width:calc(100% - 20px);
border:1px solid blueviolet; border-right:none; border-top:none;
}
.combobox>div:after{
position:absolute; top:0px; right:0px; height:100%; width:20px;
box-sizing:border-box; content:"?"; border:1px solid blueviolet; pointer-events:none;
display:flex; flex-direction:row; align-items:center; justify-content:center;
}
.combobox select:focus, .combobox input:focus {outline:none;}
_x000D_
<!-- mandatory benefits/social security/welfare -->
<div class="combobox"><div>
<select id=MandatoryBenefits onchange="this.nextElementSibling.value=this.value" required>
<option value="" selected>Select ...</option>
<option value="Pension">Pension %</option>
<option value="Medical">Medical %</option>
<option value="Unemployment">Unemployment %</option>
<option value="Injury">Injury %</option>
<option value="Maternity">Maternity %</option>
<option value="Serious Illness">Serious Illness %</option>
<option value="Housing Fund">Housing Fund %</option>
</select>
<input type="text" value="" onchange="this.previousElementSibling.selectedIndex=0"
oninput="this.previousElementSibling.options[0].value=this.value; this.previousElementSibling.options[0].innerHTML=this.value" />
</div></div>
_x000D_
online demo (@jsbin)
The above answers won't let you quote inside the quotes. This solution will:
sudo -su nobody umask 0000 \; mkdir -p "$targetdir"
Both the umask command and the mkdir-command runs in with the 'nobody' user.
WARNING:
git clean -f
will remove untracked files, meaning they're gone for good since they aren't stored in the repository. Make sure you really want to remove all untracked files before doing this.
Try this and see git clean -f
.
git reset --hard
will not remove untracked files, where as git-clean
will remove any files from the tracked root directory that are not under Git tracking.
Alternatively, as @Paul Betts said, you can do this (beware though - that removes all ignored files too)
git clean -df
git clean -xdf
CAUTION! This will also delete ignored filesAs of Jackson 1.6, you can use:
JsonNode node = mapper.valueToTree(map);
or
JsonNode node = mapper.convertValue(object, JsonNode.class);
Source: is there a way to serialize pojo's directly to treemodel?
If your template.html
file is just HTML and not a React component, then you can't require it in the same way you would do with a JS file.
However, if you are using Browserify — there is a transform called stringify which will allow you to require non-js files as strings. Once you have added the transform, you will be able to require HTML files and they will export as though they were just strings.
Once you have required the HTML file, you'll have to inject the HTML string into your component, using the dangerouslySetInnerHTML
prop.
var __html = require('./template.html');
var template = { __html: __html };
React.module.exports = React.createClass({
render: function() {
return(
<div dangerouslySetInnerHTML={template} />
);
}
});
This goes against a lot of what React is about though. It would be more natural to create your templates as React components with JSX, rather than as regular HTML files.
The JSX syntax makes it trivially easy to express structured data, like HTML, especially when you use stateless function components.
If your template.html
file looked something like this
<div class='foo'>
<h1>Hello</h1>
<p>Some paragraph text</p>
<button>Click</button>
</div>
Then you could convert it instead to a JSX file that looked like this.
module.exports = function(props) {
return (
<div className='foo'>
<h1>Hello</h1>
<p>Some paragraph text</p>
<button>Click</button>
</div>
);
};
Then you can require and use it without needing stringify.
var Template = require('./template');
module.exports = React.createClass({
render: function() {
var bar = 'baz';
return(
<Template foo={bar}/>
);
}
});
It maintains all of the structure of the original file, but leverages the flexibility of React's props model and allows for compile time syntax checking, unlike a regular HTML file.
This worked for my needs...
Task mytask = Task.Run(() =>
{
MyForm form = new MyForm();
form.ShowDialog();
});
This starts the from in a new thread and does not release the thread until the form is closed. Task
is in .Net 4 and later.
This topic may be old, but here's a quick fix
ul {list-style:outside none square;}
or
ul {list-style:outside none disc;}
, etc...
then add left padding to list element
ul li{line-height: 1.4;padding-bottom: 6px;}
Try:
$('#mytable').attr('offsetTop')
In Java multiple inheritance is not permitted. It was excluded from the language as a design decision, primarily to avoid circular dependencies.
Scenario1: As you have learned the following is not possible in Java:
public class Dog extends Animal, Canine{
}
Scenario 2: However the following is possible:
public class Canine extends Animal{
}
public class Dog extends Canine{
}
The difference in these two approaches is that in the second approach there is a clearly defined parent or super
class, while in the first approach the super
class is ambiguous.
Consider if both Animal
and Canine
had a method drink()
. Under the first scenario which parent method would be called if we called Dog.drink()
? Under the second scenario, we know calling Dog.drink()
would call the Canine
classes drink
method as long as Dog
had not overridden it.
The solution is in the link that you provided in your question:
datetime.combine(date.today(), time()) + timedelta(hours=1)
Full example:
from datetime import date, datetime, time, timedelta
dt = datetime.combine(date.today(), time(23, 55)) + timedelta(minutes=30)
print dt.time()
Output:
00:25:00
Use Linebreak:
<TextBlock>
<Run Text="Line1"/>
<LineBreak/>
<Run Text="Line2" FontStyle="Italic" FontSize="9"/>
<LineBreak/>
<Run Text="Line3"/>
</TextBlock>
Thanks,
RDV
There are new units that you can use:
vw
- viewport width
vh
- viewport height
#neo_main_container1
{
width: 100%; //fallback
width: 100vw;
}
Opera Mini does not support this, but you can use it in all other modern browsers.
URLImageViewHelper is an amazing library that helps you to do that.
This header is getting somehow deprecated. You can read more about it here - X-XSS-Protection
- Chrome has removed their XSS Auditor
- Firefox has not, and will not implement X-XSS-Protection
- Edge has retired their XSS filter
This means that if you do not need to support legacy browsers, it is recommended that you use Content-Security-Policy without allowing unsafe-inline scripts instead.
This is not supported by some browsers (IE if I recall), but it works in the rest:
document.getElementById("password-field").attributes["type"] = "password";
or
document.getElementById("password-field").attributes["type"] = "text";
Since 'Kranu' helpfully advises 'The only interaction with the filesystem is with loading js files . . .', that suggests doing so with error checking would at least tell you if the file does not exist - which may be sufficient for your purposes?
From a local machine, you can check whether a file does not exist by attempting to load it as an external script then checking for an error. For example:
<span>File exists? </span>
<SCRIPT>
function get_error(x){
document.getElementsByTagName('span')[0].innerHTML+=x+" does not exist.";
}
url=" (put your path/file name in here) ";
url+="?"+new Date().getTime()+Math.floor(Math.random()*1000000);
var el=document.createElement('script');
el.id="123";
el.onerror=function(){if(el.onerror)get_error(this.id)}
el.src=url;
document.body.appendChild(el);
</SCRIPT>
Some notes...
Short answer:
Context context;
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
context = recyclerView.getContext();
}
Explanation why other answers are not great:
Context
to the adapter is completely unnecessary, since RecyclerView
you can access it from inside the classContext
at ViewHolder
level means that you do it every time you bind or create a ViewHolder
. You duplicate operations.Activity
lifespan (which would be weird) then you already have a leak.If all your values are unique, you can make a reverse dictionary:
PIXO_reverse = {v: k for k, v in PIX0.items()}
Result:
>>> PIXO_reverse
{'320x240': 'QVGA', '640x480': 'VGA', '800x600': 'SVGA'}
Now you can use the same logic as before.
My answer is focused to a extended case derived from the one exposed at top.
Suppose you have group of elements from which you want to hide the child elements except first. As an example:
<html>
<div class='some-group'>
<div class='child child-0'>visible#1</div>
<div class='child child-1'>xx</div>
<div class='child child-2'>yy</div>
</div>
<div class='some-group'>
<div class='child child-0'>visible#2</div>
<div class='child child-1'>aa</div>
<div class='child child-2'>bb</div>
</div>
</html>
We want to hide all .child
elements on every group. So this will not help because will hide all .child
elements except visible#1
:
$('.child:not(:first)').hide();
The solution (in this extended case) will be:
$('.some-group').each(function(i,group){
$(group).find('.child:not(:first)').hide();
});
I had similar problem (in bash terminal command was working correctly but zsh showed command not found error)
just paste whatever you were earlier pasting in ~/.bashrc to:
~/.zshrc
I have to add in httpd.conf this line (Windows):
LoadFile "C:/Program Files (x86)/PostgreSQL/8.3/bin/libpq.dll"
A solution designed for the pipeline operator:
const addDays = days => date => {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
};
Usage:
// Without the pipeline operator...
addDays(7)(new Date());
// And with the pipeline operator...
new Date() |> addDays(7);
If you need more functionality, I suggest looking into the date-fns library.
Vertex *f=(findvertex(from));
if(!f) {
cerr << "vertex not found" << endl;
exit(1) // or return;
}
Because findVertex
can return NULL
if it can't find the vertex.
Otherwise this f->adj;
is trying to do
NULL->adj;
Which causes access violation.
Take a look at my answer here.
Answer to comment:
The FFT actually calculates the cross-correlation of the input signal with sine and cosine functions (basis functions) at a range of equally spaced frequencies. For a given FFT output, there is a corresponding frequency (F) as given by the answer I posted. The real part of the output sample is the cross-correlation of the input signal with cos(2*pi*F*t)
and the imaginary part is the cross-correlation of the input signal with sin(2*pi*F*t)
. The reason the input signal is correlated with sin
and cos
functions is to account for phase differences between the input signal and basis functions.
By taking the magnitude of the complex FFT output, you get a measure of how well the input signal correlates with sinusoids at a set of frequencies regardless of the input signal phase. If you are just analyzing frequency content of a signal, you will almost always take the magnitude or magnitude squared of the complex output of the FFT.
What Harry S says is exactly right, but
int? accom = (accomStr == "noval" ? null : (int?)Convert.ToInt32(accomStr));
would also do the trick. (We Resharper users can always spot each other in crowds...)
li a[aria-expanded="true"] span{_x000D_
color: red;_x000D_
}
_x000D_
<li class="active">_x000D_
<a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true">_x000D_
<span class="network-name">Google+</span>_x000D_
</a>_x000D_
</li>_x000D_
<li class="active">_x000D_
<a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="false">_x000D_
<span class="network-name">Google+</span>_x000D_
</a>_x000D_
</li>
_x000D_
li a[aria-expanded="true"]{_x000D_
background: yellow;_x000D_
}
_x000D_
<li class="active">_x000D_
<a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true">_x000D_
<span class="network-name">Google+</span>_x000D_
</a>_x000D_
</li>_x000D_
<li class="active">_x000D_
<a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="false">_x000D_
<span class="network-name">Google+</span>_x000D_
</a>_x000D_
</li>
_x000D_
I think the shortcut that you're looking for is:
Ctrl+Shift+R on Windows and Linux/Ubuntu
Cmd+Shift+R on Mac OS X
ref: source
If you are using ggplot2
to generate a figure, then a ggsave(file="name.eps")
will also work.
I know that its bit old Q but if u get here by searching a solution so i got a nice one via jquery
jQuery('a[target^="_new"]').click(function() {
var width = window.innerWidth * 0.66 ;
// define the height in
var height = width * window.innerHeight / window.innerWidth ;
// Ratio the hight to the width as the user screen ratio
window.open(this.href , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));
});
it will open all the <a target="_new">
in a new window
EDIT:
1st, I did some little changes in the original code now it open the new window perfectly followed the user screen ratio (for landscape desktops)
but, I would like to recommend you to use the following code that open the link in new tab if you in mobile (thanks to zvona answer in other question):
jQuery('a[target^="_new"]').click(function() {
return openWindow(this.href);
}
function openWindow(url) {
if (window.innerWidth <= 640) {
// if width is smaller then 640px, create a temporary a elm that will open the link in new tab
var a = document.createElement('a');
a.setAttribute("href", url);
a.setAttribute("target", "_blank");
var dispatch = document.createEvent("HTMLEvents");
dispatch.initEvent("click", true, true);
a.dispatchEvent(dispatch);
}
else {
var width = window.innerWidth * 0.66 ;
// define the height in
var height = width * window.innerHeight / window.innerWidth ;
// Ratio the hight to the width as the user screen ratio
window.open(url , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));
}
return false;
}
The suggested answer here doesn't work properly on android 5.0 if your XML based color state list references themed attributes.. For instance, I have an xml color state list like so:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="?colorPrimary" android:state_enabled="true"/>
<item android:alpha="0.12" android:color="?attr/colorOnSurface"/>
</selector>
Using this as my backgroundTint from xml works just fine on android 5.0 and everything else. However if I try to set this in code like this:
(Don't do this)
myButton.setSupportButtonTintList(ContextCompat.getColorStateList(myButton.getContext(), R.color.btn_tint_primary));
It actually doesn't matter if I pass the Activity or the button's context to ContextCompat.getColorStateList() method, neither will give me the proper color state list with respect to the theme the button is within. This is because using theme attributes in color state lists wasn't supported until api 23 and ContextCompat does not do anything special to resolve these. Instead you must use AppCompatResources.getColorStateList() which does its own resource parsing/theme attribute resolution on devices < API 23.
Instead, you must use this:
myButton.setSupportBackgroundTintList(AppCompatResources.getColorStateList(myButton.getContext(), R.color.btn_tint_primary));
TLDR: use AppCompatResources and not -ContextCompat- if you'll need resolved themed resources across all API versions of android.
For more information on the topic, see this article.
A possible solution:
document.getElementById("yourDatePicker").valueAsDate = new Date();
Using Moment.js:
var today = moment().format('YYYY-MM-DD');
document.getElementById("datePicker").value = today;
You need to install popperjs along with bootstrap to get rid of this error.Note that if you are using "bootstrap": "^4.4.1", and @popperjs/core v2.x combinations,bootstrap may not support popperjs version. So downgrade your version.
Option 1:
npm install popper.js@^1.12.9 --save
and Add following script between jquery and bootstrap scripts.
"node_modules/popper.js/dist/umd/popper.min.js"
,
Option 2: Add following script tag to index.html
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script
Linking with a library that defines the missing symbol (-lboost_system
) is the obvious solution, but in the particular case of Boost.System, a misfeature in the original design makes it use boost::system::generic_category()
and boost::system::system_category()
needlessly. Compiling with the flag -DBOOST_SYSTEM_NO_DEPRECATED
disables that code and lets a number of programs compile without requiring -lboost_system
(that link is of course still needed if you explicitly use some of the library's features).
Starting from Boost 1.66 and this commit, this behavior is now the default, so hopefully fewer and fewer users should need this answer.
As noticed by @AndrewMarshall, an alternative is to define BOOST_ERROR_CODE_HEADER_ONLY
which enables a header-only version of the code. This was discouraged by Boost as it can break some functionality. However, since 1.69, header-only seems to have become the default, supposedly making this question obsolete.
As Jake points out, TARGET_IPHONE_SIMULATOR
is a subset of TARGET_OS_IPHONE
.
Also, TARGET_OS_IPHONE
is a subset of TARGET_OS_MAC
.
So a better approach might be:
#ifdef _WIN64
//define something for Windows (64-bit)
#elif _WIN32
//define something for Windows (32-bit)
#elif __APPLE__
#include "TargetConditionals.h"
#if TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR
// define something for simulator
#elif TARGET_OS_IPHONE
// define something for iphone
#else
#define TARGET_OS_OSX 1
// define something for OSX
#endif
#elif __linux
// linux
#elif __unix // all unices not caught above
// Unix
#elif __posix
// POSIX
#endif
We can use $set
operator to update the nested array inside object filed update the value
db.getCollection('geolocations').update(
{
"_id" : ObjectId("5bd3013ac714ea4959f80115"),
"geolocation.country" : "United States of America"
},
{ $set:
{
"geolocation.$.country" : "USA"
}
},
false,
true
);
Windows shell, one liner:
FOR /F %%I IN ('DIR *.* /B /O:-D') DO COPY %%I <<NewDir>> & EXIT
The issue with reading lines in first pass and making changes (deleting specific lines) in the second pass is that if you file sizes are huge, you will run out of RAM. Instead, a better approach is to read lines, one by one, and write them into a separate file, eliminating the ones you don't need. I have run this approach with files as big as 12-50 GB, and the RAM usage remains almost constant. Only CPU cycles show processing in progress.
After reading all the answers but none really working for numbers only with copy and paste I came up with this solution.
parseInt
solution: fails as parseInt("2a")
is valid; onKeyup sulution:
fails on copy and paste, backspace;javascript
converts 40817810000000023511 into 40817810000000023500 because it is 53 bit language<input
name="address.line1"
value={values.address.line1}
onChange={(event: any) => {
if (isFinite(event.target.value)) {
// UPDATE YOUR STATE (i am using formik)
setFieldValue("address.line1", event.target.value);
}
}}
/>
Here's your CSS
element{
width: 200px;
height: 300px;
overflow-y: auto;
}
Npm repository is currently down. See issue #2694 on npm github
EDIT:
To use a mirror in the meanwhile:
npm set registry http://ec2-46-137-149-160.eu-west-1.compute.amazonaws.com
you can reset this later with:
npm set registry https://registry.npmjs.org/
_tmain is a macro that gets redefined depending on whether or not you compile with Unicode or ASCII. It is a Microsoft extension and isn't guaranteed to work on any other compilers.
The correct declaration is
int _tmain(int argc, _TCHAR *argv[])
If the macro UNICODE is defined, that expands to
int wmain(int argc, wchar_t *argv[])
Otherwise it expands to
int main(int argc, char *argv[])
Your definition goes for a bit of each, and (if you have UNICODE defined) will expand to
int wmain(int argc, char *argv[])
which is just plain wrong.
std::cout works with ASCII characters. You need std::wcout if you are using wide characters.
try something like this
#include <iostream>
#include <tchar.h>
#if defined(UNICODE)
#define _tcout std::wcout
#else
#define _tcout std::cout
#endif
int _tmain(int argc, _TCHAR *argv[])
{
_tcout << _T("There are ") << argc << _T(" arguments:") << std::endl;
// Loop through each argument and print its number and value
for (int i=0; i<argc; i++)
_tcout << i << _T(" ") << argv[i] << std::endl;
return 0;
}
Or you could just decide in advance whether to use wide or narrow characters. :-)
Updated 12 Nov 2013:
Changed the traditional "TCHAR" to "_TCHAR" which seems to be the latest fashion. Both work fine.
End Update
<mvc:annotation-driven />
means that you can define spring beans dependencies without actually having to specify a bunch of elements in XML or implement an interface or extend a base class. For example @Repository
to tell spring that a class is a Dao without having to extend JpaDaoSupport
or some other subclass of DaoSupport. Similarly @Controller
tells spring that the class specified contains methods that will handle Http requests without you having to implement the Controller interface or extend a subclass that implements the controller.
When spring starts up it reads its XML configuration file and looks for <bean
elements within it if it sees something like <bean class="com.example.Foo" />
and Foo was marked up with @Controller
it knows that the class is a controller and treats it as such. By default, Spring assumes that all the classes it should manage are explicitly defined in the beans.XML file.
Component scanning with <context:component-scan base-package="com.mycompany.maventestwebapp" />
is telling spring that it should search the classpath for all the classes under com.mycompany.maventestweapp and look at each class to see if it has a @Controller
, or @Repository
, or @Service
, or @Component
and if it does then Spring will register the class with the bean factory as if you had typed <bean class="..." />
in the XML configuration files.
In a typical spring MVC app you will find that there are two spring configuration files, a file that configures the application context usually started with the Spring context listener.
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
And a Spring MVC configuration file usually started with the Spring dispatcher servlet. For example.
<servlet>
<servlet-name>main</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>main</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Spring has support for hierarchical bean factories, so in the case of the Spring MVC, the dispatcher servlet context is a child of the main application context. If the servlet context was asked for a bean called "abc" it will look in the servlet context first, if it does not find it there it will look in the parent context, which is the application context.
Common beans such as data sources, JPA configuration, business services are defined in the application context while MVC specific configuration goes not the configuration file associated with the servlet.
Hope this helps.
I had this problem in Windows 7, this is what fixed it for me.
http://letsgetdugg.com/2009/04/19/recovering-a-corrupt-eclipse-workspace/
cd ~/Documents/workspace/.metalog/.plugins
rm -rf org.eclipse.core.resources
Here is a table of the different events and the levels of browser support. You need to pick an event which is supported across at least all modern browsers.
As you will see from the table, the keypress
and change
event do not have uniform support whereas the keyup
event does.
Also make sure you attach the event handler using a cross-browser-compatible method...
Not trying to take any credits here, all credit goes to @theazureshadow for his reply, but I personally had to adapt it for a table that has some <th>
instead of <td>
for it's first row's cells.
I'm just posting the modified version here in case some of you want to use @theazureshadow's solution, but like me, have some <th>
in the first <tr>
. The class "reportTable" only have to be applied to the table itself.:
table.reportTable {
border-collapse: separate;
border-spacing: 0;
}
table.reportTable td {
border: solid gray 1px;
border-style: solid none none solid;
padding: 10px;
}
table.reportTable td:last-child {
border-right: solid gray 1px;
}
table.reportTable tr:last-child td{
border-bottom: solid gray 1px;
}
table.reportTable th{
border: solid gray 1px;
border-style: solid none none solid;
padding: 10px;
}
table.reportTable th:last-child{
border-right: solid gray 1px;
border-top-right-radius: 10px;
}
table.reportTable th:first-child{
border-top-left-radius: 10px;
}
table.reportTable tr:last-child td:first-child{
border-bottom-left-radius: 10px;
}
table.reportTable tr:last-child td:last-child{
border-bottom-right-radius: 10px;
}
Feel free to adjust the paddings, radiuses, etc to fit your needs. Hope that helps people!
You not only have to add lombok.jar to the libraries, but also install it by either double-clicking the lombok jar, or from the command line run java -jar lombok.jar
. That will show you a nice installer screen. Select your Eclipse installation and install.
Afterwards, you can check if the installer has correctly modified your eclipse.ini:
-vmargs
...
-javaagent:lombok.jar
-Xbootclasspath/a:lombok.jar
If your Eclipse was already running, you have to Exit Eclipse and start it again. (File/Restart is not enough)
If you are starting Eclipse using a shortcut, make sure that either there are no command line arguments filled in, or manually add -javaagent:lombok.jar
-Xbootclasspath/a:lombok.jar
somewhere after -vmargs
.
Recent editions of Lombok also add a line to the About Eclipse screen. If Lombok is active you can find a line like 'Lombok v0.11.6 "Dashing Kakapo" is installed. http://projectlombok.org/' just above the line of buttons.
If for some reason, usually related to customized eclipse builds, you need to use the full path, you can instruct the installer on the command line to do so:
java -Dlombok.installer.fullpath -jar lombok.jar
<html>
<head>
<title>Page</title>
</head>
<body>
<a href="./">Folder directory</a>
</body>
</html>
Typedef allows items to be implicitly assigned to types they are not. Some people try to get around this with extensions; read here at IBM for an explanation of why this is a bad idea.
Edit: While strong type inference is a useful thing, I don't think (and hope we won't) see typedef
rearing it's ugly head in managed languages (ever?).
Edit 2: In C#, you can use a using statement like this at the top of a source file. It's used so you don't have to do the second item shown. The only time you see the name change is when a scope introduces a name collision between two types. The renaming is limited to one file, outside of which every variable/parameter type which used it is known by its full name.
using Path = System.IO.Path;
using System.IO;
You might not need to make any change in the routing. Just add following four methods in your customersController.cs file:
public ActionResult Index()
{
}
public ActionResult currentMonth()
{
}
public ActionResult customerById(int id)
{
}
public ActionResult customerByUsername(string userName)
{
}
Put the relevant code in the method. With the default routing supplied, you should get appropriate action result from the controller based on the action and parameters for your given urls.
Modify your default route as:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Api", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
where 1=0, This is done to check if the table exists. Don't know why 1=1 is used.
f-strings, also called “formatted string literals,” are string literals that have an f
at the beginning; and curly braces containing expressions that will be replaced with their values.
f-strings are evaluated at runtime.
So your code can be re-written as:
string1="go"
string2="now"
string3="great"
print(f"""
I will {string1} there
I will go {string2}
{string3}
""")
And this will evaluate to:
I will go there
I will go now
great
You can learn more about it here.
Use Sheets rather than Sheet and activate them sequentially:
Sub kl()
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ActiveWorkbook
Set ws = Sheets("Sheet1")
wb.Activate
ws.Select
End Sub
On modern browsers it's easy: just use the input event along with the inputType attribute:
$(document).on('input', 'input, textarea', function(e){
if (e.originalEvent.inputType == 'insertFromPaste') {
alert($(this).val());
}
});
Transient variables in Java are never serialized.
Open my sql command promt:
then enter mysql password
finally use:
ALTER USER 'username'@'ip_address' IDENTIFIED WITH mysql_native_password BY 'password';
refer:https://stackoverflow.com/a/49228443/6097074
Thanks.
Use a regex: .
Match m = Regex.Match(text, @"(.+? .+?) ");
if (m.Success) {
do_something_with(m.Groups[1].Value);
}
NOW() normally works in SQL statements and returns the date and time. Check if your database field has the correct type (datetime). Otherwise, you can always use the PHP date() function and insert:
date('Y-m-d H:i:s')
But I wouldn't recommend this.
Keep in mind that while transferring files internally on a machine i.e not network transfer, using the -z flag can have a massive difference in the time taken for the transfer.
Transfer within same machine
Case 1: With -z flag:
TAR took: 9.48345208168
Encryption took: 2.79352903366
CP took = 5.07273387909
Rsync took = 30.5113282204
Case 2: Without the -z flag:
TAR took: 10.7535531521
Encryption took: 3.0386879921
CP took = 4.85565590858
Rsync took = 4.94515299797
Yes you can, although it relies on Javascript's inherent functionality and not the jQuery library.
http://www.w3schools.com/jsref/jsref_substr.asp
The substr
function will allow you to extract certain parts of the string.
Now, if you're looking for a specific string or character to use to find what part of the string to extract, you can make use of the indexOf function as well. http://www.w3schools.com/jsref/jsref_IndexOf.asp
The question is somewhat vague though; even just link text with 'name' will achieve the desired result. What's the criteria for getting your substring, exactly?
I think the java.lang.UnsupportedOperationException
is what you are looking for.
You can use the below code to run test cases in Chrome using Selenium WebDriver:
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ChromeTest {
/**
* @param args
* @throws InterruptedException
* @throws IOException
*/
public static void main(String[] args) throws InterruptedException, IOException {
// Telling the system where to find the Chrome driver
System.setProperty(
"webdriver.chrome.driver",
"E:/chromedriver_win32/chromedriver.exe");
WebDriver webDriver = new ChromeDriver();
// Open google.com
webDriver.navigate().to("http://www.google.com");
String html = webDriver.getPageSource();
// Printing result here.
System.out.println(html);
webDriver.close();
webDriver.quit();
}
}
My 2 cents for golfers:
b="1,2,3,4".split`,`.map(x=>+x)
backquote is string litteral so we can omit the parenthesis (because of the nature of split function) but it is equivalent to split(',')
. The string is now an array, we just have to map each value with a function returning the integer of the string so x=>+x
(which is even shorter than the Number
function (5 chars instead of 6)) is equivalent to :
function(x){return parseInt(x,10)}// version from techfoobar
(x)=>{return parseInt(x)} // lambda are shorter and parseInt default is 10
(x)=>{return +x} // diff. with parseInt in SO but + is better in this case
x=>+x // no multiple args, just 1 function call
I hope it is a bit more clear.
In Postgres, you can also use the special DISTINCT ON (expression)
syntax:
SELECT DISTINCT ON (cname)
cname, wmname, avg
FROM
makerar
ORDER BY
cname, avg DESC ;
Check the permissions on your Ruby script (may not have execute permission), your theme file and directory (in case it can't read the theme or tries to create other themes in there), and the directory you're in when you run the script (in case it makes temporary files in the current directory rather then /tmp
).
Any one of them could be causing you grief.
For those of us using non-ISO standard date formats, like civilian vernacular 01/01/2001 (mm/dd/YYYY), including time in a 12hour date format with am/pm marks, the following function will return a valid Date object:
function convertDate(date) {
// # valid js Date and time object format (YYYY-MM-DDTHH:MM:SS)
var dateTimeParts = date.split(' ');
// # this assumes time format has NO SPACE between time and am/pm marks.
if (dateTimeParts[1].indexOf(' ') == -1 && dateTimeParts[2] === undefined) {
var theTime = dateTimeParts[1];
// # strip out all except numbers and colon
var ampm = theTime.replace(/[0-9:]/g, '');
// # strip out all except letters (for AM/PM)
var time = theTime.replace(/[[^a-zA-Z]/g, '');
if (ampm == 'pm') {
time = time.split(':');
// # if time is 12:00, don't add 12
if (time[0] == 12) {
time = parseInt(time[0]) + ':' + time[1] + ':00';
} else {
time = parseInt(time[0]) + 12 + ':' + time[1] + ':00';
}
} else { // if AM
time = time.split(':');
// # if AM is less than 10 o'clock, add leading zero
if (time[0] < 10) {
time = '0' + time[0] + ':' + time[1] + ':00';
} else {
time = time[0] + ':' + time[1] + ':00';
}
}
}
// # create a new date object from only the date part
var dateObj = new Date(dateTimeParts[0]);
// # add leading zero to date of the month if less than 10
var dayOfMonth = (dateObj.getDate() < 10 ? ("0" + dateObj.getDate()) : dateObj.getDate());
// # parse each date object part and put all parts together
var yearMoDay = dateObj.getFullYear() + '-' + (dateObj.getMonth() + 1) + '-' + dayOfMonth;
// # finally combine re-formatted date and re-formatted time!
var date = new Date(yearMoDay + 'T' + time);
return date;
}
Usage:
date = convertDate('11/15/2016 2:00pm');
If you're trying to just count how many of your cells in a range are not blank try this:
=COUNTA(range)
Example: (assume that it starts from A1 downwards):
---------
Something
---------
Something
---------
---------
Something
---------
---------
Something
---------
=COUNTA(A1:A6)
returns 4
since there are two blank cells in there.
You may at times need to get different values from URL.
Below example shows different ways of extracting different parts of URL
EXAMPLE: (Sample URL)
http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QueryString2=2
CODE
Response.Write("<br/> " + HttpContext.Current.Request.Url.Host);
Response.Write("<br/> " + HttpContext.Current.Request.Url.Authority);
Response.Write("<br/> " + HttpContext.Current.Request.Url.Port);
Response.Write("<br/> " + HttpContext.Current.Request.Url.AbsolutePath);
Response.Write("<br/> " + HttpContext.Current.Request.ApplicationPath);
Response.Write("<br/> " + HttpContext.Current.Request.Url.AbsoluteUri);
Response.Write("<br/> " + HttpContext.Current.Request.Url.PathAndQuery);
OUTPUT
localhost
localhost:60527
60527
/WebSite1test/Default2.aspx
/WebSite1test
http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QueryString1=2
/WebSite1test/Default2.aspx?QueryString1=1&QueryString2=2
You can copy paste above sample code & run it in asp.net web form application with different URL.
I also recommend reading ASP.Net Routing in case you may use ASP Routing then you don't need to use traditional URL with query string.
http://msdn.microsoft.com/en-us/library/cc668201%28v=vs.100%29.aspx
For windows user, Just simple stop all processes of Node.js in Task Manager
Hope it will help
Problems only surface when I am I trying to give the first loaded content an active state
Does this mean that you want to add a class to the first button?
$('.o-links').click(function(e) { // ... }).first().addClass('O_Nav_Current');
instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:
CSS:
.image-area { width: 100%; height: auto; display: none; } .image-area:first-of-type { display: block; }
JavaScript:
var $slides = $('.image-area'), $btns = $('a.o-links'); $btns.on('click', function (e) { var i = $btns.removeClass('O_Nav_Current').index(this); $(this).addClass('O_Nav_Current'); $slides.filter(':visible').fadeOut(1000, function () { $slides.eq(i).fadeIn(1000); }); e.preventDefault(); }).first().addClass('O_Nav_Current');
There is actually a nice Gem called local_time
by basecamp to do all of that on client side only, I believe:
Method 1 (using new
)
delete
your object later. (If you don't delete it, you could create a memory leak)delete
it. (i.e. you could return
an object that you created using new
) delete
d; and it should always be deleted, regardless of which control path is taken, or if exceptions are thrown.Method 2 (not using new
)
delete
it later.return
a pointer to an object on the stack)As far as which one to use; you choose the method that works best for you, given the above constraints.
Some easy cases:
delete
, (and the potential to cause memory leaks) you shouldn't use new
.new
To expand on Sparr's answer
Initialization and assignment are two distinct operations that happen to use the same operator ("=") here.
Think of it like this:
Imagine that there are 2 functions, called InitializeObject
, and AssignObject
. When the compiler sees thing = value
, it looks at the context and calls one InitializeObject
if you're making a new thing
. If you're not, it instead calls AssignObject
.
Normally this is fine as InitializeObject
and AssignObject
usually behave the same way. Except when dealing with char arrays (and a few other edge cases) in which case they behave differently. Why do this? Well that's a whole other post involving the stack vs the heap and so on and so forth.
PS: As an aside, thinking of it in this way will also help you understand copy constructors and other such things if you ever venture into C++
Paste this on your command line:
export LC_CTYPE="en_US.UTF-8"
If you use another view
make sure to use view.getContext()
instead of this
or getApplicationContext()
Try to surround the path with quotes, and remove the spaces
export PYTHONPATH="/home/user/my_project":$PYTHONPATH
And don't forget to preserve previous content suffixing by :$PYTHONPATH (which is the value of the variable)
Execute the following command to check everything is configured correctly:
echo $PYTHONPATH
Try
ps -ef | grep "KEYWORD" | awk '{print $2}'
That command should give you the PID of the processes with KEYWORD in them. In this instance, awk
is returning what is in the 2nd column from the output.
INSERT INTO vendors (
name,
phone,
addressLine1,
addressLine2,
city,
state,
postalCode,
country,
customer_id
)
SELECT
name,
phone,
addressLine1,
addressLine2,
city,
state ,
postalCode,
country,
customer_id
FROM
customers;
A write-up of jme's suggestion, using pathlib, in Python 3.
from pathlib import Path
parent = Path(r'/a/b')
son = Path(r'/a/b/c/d')
?
if parent in son.parents or parent==son:
print(son.relative_to(parent)) # returns Path object equivalent to 'c/d'
This is simple way (thanks Gson)
JsonParser parser = new JsonParser();
String retVal = parser.parse(param).getAsString();
https://gist.github.com/MustafaFerhan/25906d2be6ca109f61ce#file-evaluatejavascript-string-problem
If you don't want to pass interface state or props model you can try this
class App extends React.Component <any, any>
I had a similar problem in IntelliJ IDEA. My code was 100% correct, but after starting the Tomcat, you receive an exception. java.lang.IllegalStateException: Neither BindingResult
I just removed and added again Tomcat configuration. And it worked for me.
A picture Tomcat configuration
<a [routerLink]="['../']" [queryParams]="{name: 'ferret'}" [fragment]="nose">Ferret Nose</a>
foo://example.com:8042/over/there?name=ferret#nose
\_/ \______________/\_________/ \_________/ \__/
| | | | |
scheme authority path query fragment
For more info - https://angular.io/guide/router#query-parameters-and-fragments
You can KILL the processid.
mysql> show full processlist;
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| Id | User | Host | db | Command | Time | State | Info |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| 1193777 | TestUser12 | 192.168.1.11:3775 | www | Sleep | 25946 | | NULL |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
mysql> kill 1193777;
But:
Or you configure your mysql-server by setting a shorter timeout on wait_timeout
and interactive_timeout
mysql> show variables like "%timeout%";
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| connect_timeout | 5 |
| delayed_insert_timeout | 300 |
| innodb_lock_wait_timeout | 50 |
| interactive_timeout | 28800 |
| net_read_timeout | 30 |
| net_write_timeout | 60 |
| slave_net_timeout | 3600 |
| table_lock_wait_timeout | 50 |
| wait_timeout | 28800 |
+--------------------------+-------+
9 rows in set (0.00 sec)
Set with:
set global wait_timeout=3;
set global interactive_timeout=3;
(and also set in your configuration file, for when your server restarts)
But you're treating the symptoms instead of the underlying cause - why are the connections open? If the PHP script finished, shouldn't they close? Make sure your webserver is not using connection pooling...
For "zip" files, you can use import zipfile
and your code will be working simply with these lines:
import zipfile
import pandas as pd
with zipfile.ZipFile("Crime_Incidents_in_2013.zip") as z:
with z.open("Crime_Incidents_in_2013.csv") as f:
train = pd.read_csv(f, header=0, delimiter="\t")
print(train.head()) # print the first 5 rows
And the result will be:
X,Y,CCN,REPORT_DAT,SHIFT,METHOD,OFFENSE,BLOCK,XBLOCK,YBLOCK,WARD,ANC,DISTRICT,PSA,NEIGHBORHOOD_CLUSTER,BLOCK_GROUP,CENSUS_TRACT,VOTING_PRECINCT,XCOORD,YCOORD,LATITUDE,LONGITUDE,BID,START_DATE,END_DATE,OBJECTID
0 -77.054968548763071,38.899775938598317,0925135...
1 -76.967309569035052,38.872119553647011,1003352...
2 -76.996184958456539,38.927921847721443,1101010...
3 -76.943077541353617,38.883686046653935,1104551...
4 -76.939209158039446,38.892278093281632,1125028...
You don't need to update anything. Just download the SDK for API 25 from Android SDK Manager or by launching Android standalone SDK manager. The error is for missing platform and not for missing tool.
Use the basename
command:
basename /home/user/new/*.txt
You can convert it to char* if you don't need a modifiable string by using:
(char*) yourString.c_str();
This would be very useful when you want to publish a String variable via MQTT in arduino.
Your question is: are these not modules capable of declaring variables at global scope?
Answer: YES, they are "capable"
The only point is that references to global variables in ThisWorkbook or a Sheet module have to be fully qualified (i.e., referred to as ThisWorkbook.Global1
, e.g.)
References to global variables in a standard module have to be fully qualified only in case of ambiguity (e.g., if there is more than one standard module defining a variable with name Global1, and you mean to use it in a third module).
For instance, place in Sheet1 code
Public glob_sh1 As String
Sub test_sh1()
Debug.Print (glob_mod)
Debug.Print (ThisWorkbook.glob_this)
Debug.Print (Sheet1.glob_sh1)
End Sub
place in ThisWorkbook code
Public glob_this As String
Sub test_this()
Debug.Print (glob_mod)
Debug.Print (ThisWorkbook.glob_this)
Debug.Print (Sheet1.glob_sh1)
End Sub
and in a Standard Module code
Public glob_mod As String
Sub test_mod()
glob_mod = "glob_mod"
ThisWorkbook.glob_this = "glob_this"
Sheet1.glob_sh1 = "glob_sh1"
Debug.Print (glob_mod)
Debug.Print (ThisWorkbook.glob_this)
Debug.Print (Sheet1.glob_sh1)
End Sub
All three subs work fine.
PS1: This answer is based essentially on info from here. It is much worth reading (from the great Chip Pearson).
PS2: Your line Debug.Print ("Hello")
will give you the compile error Invalid outside procedure
.
PS3: You could (partly) check your code with Debug -> Compile VBAProject in the VB editor. All compile errors will pop.
PS4: Check also Put Excel-VBA code in module or sheet?.
PS5: You might be not able to declare a global variable in, say, Sheet1, and use it in code from other workbook (reading http://msdn.microsoft.com/en-us/library/office/gg264241%28v=office.15%29.aspx#sectionSection0; I did not test this point, so this issue is yet to be confirmed as such). But you do not mean to do that in your example, anyway.
PS6: There are several cases that lead to ambiguity in case of not fully qualifying global variables. You may tinker a little to find them. They are compile errors.
You seem to be passing the From
address as emailAddress
, which is not a proper email address. For Office365 the From
needs to be a real address on the Office365 system.
You can validate that if you hardcode your email address as the From
and your Office 365 password.
Don't leave it there though of course.
Connect to the database with the "system" user, and execute the following command:
show parameter service_name
I was having a problem with ASP.NET MVC 5 where CheckBoxFor would not check my checkboxes on server-side validation failure even though my model clearly had the value set to true. My Razor markup/code looked like:
@Html.CheckBoxFor(model => model.MyBoolValue, new { @class = "mySpecialClass" } )
To get this to work, I had to change this to:
@{
var checkboxAttributes = Model.MyBoolValue ?
(object) new { @class = "mySpecialClass", @checked = "checked" } :
(object) new { @class = "mySpecialClass" };
}
@Html.CheckBox("MyBoolValue", checkboxAttributes)
JSFiddle wraps your code in a function, so start()
is not defined in the global scope.
Moral of the story: don't use inline event bindings. Use addEventListener
/attachEvent
.
Please don't pass strings to setTimeout
and setInterval
. It's eval
in disguise.
Use a function instead, and get cozy with var
and white space:
var input = document.getElementById("input"),
add;
function start() {
add = setInterval(function() {
input.value++;
}, 1000);
}
start();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="input" />
<input type="button" onclick="clearInterval(add)" value="stop" />
<input type="button" onclick="start()" value="start" />
_x000D_
This is an example of how to unmarshall JSON responses from the Safebrowsing v4 API sbserver proxy server: https://play.golang.org/p/4rGB5da0Lt
// this example shows how to unmarshall JSON requests from the Safebrowsing v4 sbserver
package main
import (
"fmt"
"log"
"encoding/json"
)
// response from sbserver POST request
type Results struct {
Matches []Match
}
// nested within sbserver response
type Match struct {
ThreatType string
PlatformType string
ThreatEntryType string
Threat struct {
URL string
}
}
func main() {
fmt.Println("Hello, playground")
// sample POST request
// curl -X POST -H 'Content-Type: application/json'
// -d '{"threatInfo": {"threatEntries": [{"url": "http://testsafebrowsing.appspot.com/apiv4/ANY_PLATFORM/MALWARE/URL/"}]}}'
// http://127.0.0.1:8080/v4/threatMatches:find
// sample JSON response
jsonResponse := `{"matches":[{"threatType":"MALWARE","platformType":"ANY_PLATFORM","threatEntryType":"URL","threat":{"url":"http://testsafebrowsing.appspot.com/apiv4/ANY_PLATFORM/MALWARE/URL/"}}]}`
res := &Results{}
err := json.Unmarshal([]byte(jsonResponse), res)
if(err!=nil) {
log.Fatal(err)
}
fmt.Printf("%v\n",res)
fmt.Printf("\tThreat Type: %s\n",res.Matches[0].ThreatType)
fmt.Printf("\tPlatform Type: %s\n",res.Matches[0].PlatformType)
fmt.Printf("\tThreat Entry Type: %s\n",res.Matches[0].ThreatEntryType)
fmt.Printf("\tURL: %s\n",res.Matches[0].Threat.URL)
}
Please make sure that you also add a __init__.py
file in the package where all your other .ipynb files are located.
This is in addition to the nbviewer link that minrk
and syi
provided above.
I also had some similar problem and then I wrote the solution as well as a link to my public google drive folder which has a working example :)
My Stackoverflow post with step by step experimentation and Solution:
Jupyter Notebook: Import .ipynb file and access it's method in other .ipynb file giving error
Hope this will help others as well. Thanks all!
With PYTHONPATH set as in your example, you should be able to do
python -m gmbx
-m
option will make Python search for your module in paths Python usually searches modules in, including what you added to PYTHONPATH. When you run interpreter like python gmbx.py
, it looks for particular file and PYTHONPATH does not apply.
No As of now you can't do this by any command. You've to remove Manually from app.module.ts
and app.routing.module.ts
if you're using Angular 5
$("#target").on({
hover: function(){
//do on mouse hover
},
click: function(){
//do on mouse click
}
});
This is the solution from Rajesh, without the inconvenient commented by yuji, and updated for React Router 4.
The code would be like this:
<Route path="comments" render={(props) => <Comments myProp="value" {...props}/>}/>
Note that I use render
instead of component
. The reason is to avoid undesired remounting. I also pass the props
to that method, and I use the same props on the Comments component with the object spread operator (ES7 proposal).
I think you want to specify
-H "Content-Type:text/xml"
with a colon, not an equals.
You need to change the default layout type of top level QWidget object from Break layout type to other layout types (Vertical Layout, Horizontal Layout, Grid Layout, Form Layout). For example:
To something like this:
Just add autofocus
in first input or textarea.
<input type="text" name="name" id="xax" autofocus="autofocus" />
You can use customValidity
$(function(){ var elements = document.getElementsByTagName("input"); for (var i = 0; i < elements.length; i++) { elements[i].oninvalid = function(e) { e.target.setCustomValidity("This can't be left blank!"); }; } });
I think that will work on at least Chrome and FF, I'm not sure about other browsers
xmlns:android
This is start tag for define android namespace in Android. This is standerd convention define by android google developer. when you are using and layout default or custom, then must use this namespace.
Defines the Android namespace. This attribute should always be set to "
http://schemas.android.com/apk/res/android
".
From the <manifest>
element documentation.
You can try a 3rd party library like json.net There's documention on the project site. It does say it requires .net 3.5.
Otherwise there's another one called Nii.json which i believe is a port from java. I found a link to it on this blog
(Copied from this question)
In cases where I have not had control over the incoming JSON (and so cannot ensure that it includes a $type property) I have written a custom converter that just allows you to explicitly specify the concrete type:
public class Model
{
[JsonConverter(typeof(ConcreteTypeConverter<Something>))]
public ISomething TheThing { get; set; }
}
This just uses the default serializer implementation from Json.Net whilst explicitly specifying the concrete type.
An overview are available on this blog post. Source code is below:
public class ConcreteTypeConverter<TConcrete> : JsonConverter
{
public override bool CanConvert(Type objectType)
{
//assume we can convert to anything for now
return true;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
//explicitly specify the concrete type we want to create
return serializer.Deserialize<TConcrete>(reader);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
//use the default serialization - it works fine
serializer.Serialize(writer, value);
}
}
You can use ng-show on every div element in the loop. Is this what you've wanted: http://jsfiddle.net/pGwRu/2/ ?
<div class="from" ng-show="message.from">From: {{message.from.name}}</div>
public boolean getcheckboxvalue(String element)
{
WebElement webElement=driver.findElement(By.xpath(element));
return webElement.isSelected();
}
You want $_SERVER['REQUEST_URI']
. From the docs:
'REQUEST_URI'
The URI which was given in order to access this page; for instance,
'/index.html'
.
I found the following comparison helpful:
str(f1) == str(f2)
Change the following line
$(document).ready(function() {
To
jQuery.noConflict();
jQuery(document).ready(function($) {
According to PEP8, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes. You should also try to put the line break after boolean operators.
Further to this, if you're using a code style check such as pycodestyle, the next logical line needs to have different indentation to your code block.
For example:
if (abcdefghijklmnopqrstuvwxyz > some_other_long_identifier and
here_is_another_long_identifier != and_finally_another_long_name):
# ... your code here ...
pass
Unfortunately, URLEncoder.encode() does not produce valid percent-encoding (as specified in RFC 3986).
URLEncoder.encode() encodes everything just fine, except space is encoded to "+". All the Java URI encoders that I could find only expose public methods to encode the query, fragment, path parts etc. - but don't expose the "raw" encoding. This is unfortunate as fragment and query are allowed to encode space to +, so we don't want to use them. Path is encoded properly but is "normalized" first so we can't use it for 'generic' encoding either.
Best solution I could come up with:
return URLEncoder.encode(raw, "UTF-8").replaceAll("\\+", "%20");
If replaceAll()
is too slow for you, I guess the alternative is to roll your own encoder...
EDIT: I had this code in here first which doesn't encode "?", "&", "=" properly:
//don't use - doesn't properly encode "?", "&", "="
new URI(null, null, null, raw, null).toString().substring(1);
>>> import datetime
>>> # replace datetime.datetime.now() with your datetime object
>>> int(datetime.datetime.now().strftime("%s")) * 1000
1312908481000
Or the help of the time module (and without date formatting):
>>> import datetime, time
>>> # replace datetime.datetime.now() with your datetime object
>>> time.mktime(datetime.datetime.now().timetuple()) * 1000
1312908681000.0
Answered with help from: http://pleac.sourceforge.net/pleac_python/datesandtimes.html
Documentation:
I am adding this new answer because as per JDK8 documentation jcmd is suggested approach now.
It is suggested to use the latest utility, jcmd instead of the previous jstack, jinfo, and jmap utilities for enhanced diagnostics and reduced performance overhead.
Below are commands to get your properties/flags you want.
jcmd pid VM.system_properties
jcmd pid VM.flags
We need pid, for this use jcmd -l, like below
username@users-Air:~/javacode$ jcmd -l
11441 Test
6294 Test
29197 jdk.jcmd/sun.tools.jcmd.JCmd -l
Now time to use these pids to get properties/flags you want
Command: jcmd 11441 VM.system_properties
11441:
#Tue Oct 17 12:44:50 IST 2017
gopherProxySet=false
awt.toolkit=sun.lwawt.macosx.LWCToolkit
file.encoding.pkg=sun.io
java.specification.version=9
sun.cpu.isalist=
sun.jnu.encoding=UTF-8
java.class.path=.
java.vm.vendor=Oracle Corporation
sun.arch.data.model=64
java.vendor.url=http\://java.oracle.com/
user.timezone=Asia/Kolkata
java.vm.specification.version=9
os.name=Mac OS X
sun.java.launcher=SUN_STANDARD
user.country=US
sun.boot.library.path=/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/lib
sun.java.command=Test
http.nonProxyHosts=local|*.local|169.254/16|*.169.254/16
jdk.debug=release
sun.cpu.endian=little
user.home=/Users/XXXX
user.language=en
java.specification.vendor=Oracle Corporation
java.home=/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home
file.separator=/
java.vm.compressedOopsMode=Zero based
line.separator=\n
java.specification.name=Java Platform API Specification
java.vm.specification.vendor=Oracle Corporation
java.awt.graphicsenv=sun.awt.CGraphicsEnvironment
sun.management.compiler=HotSpot 64-Bit Tiered Compilers
ftp.nonProxyHosts=local|*.local|169.254/16|*.169.254/16
java.runtime.version=9+181
user.name=XXXX
path.separator=\:
os.version=10.12.6
java.runtime.name=Java(TM) SE Runtime Environment
file.encoding=UTF-8
java.vm.name=Java HotSpot(TM) 64-Bit Server VM
java.vendor.url.bug=http\://bugreport.java.com/bugreport/
java.io.tmpdir=/var/folders/dm/gd6lc90d0hg220lzw_m7krr00000gn/T/
java.version=9
user.dir=/Users/XXXX/javacode
os.arch=x86_64
java.vm.specification.name=Java Virtual Machine Specification
java.awt.printerjob=sun.lwawt.macosx.CPrinterJob
sun.os.patch.level=unknown
MyParam=2
java.library.path=/Users/XXXX/Library/Java/Extensions\:/Library/Java/Extensions\:/Network/Library/Java/Extensions\:/System/Library/Java/Extensions\:/usr/lib/java\:.
java.vm.info=mixed mode
java.vendor=Oracle Corporation
java.vm.version=9+181
sun.io.unicode.encoding=UnicodeBig
java.class.version=53.0
socksNonProxyHosts=local|*.local|169.254/16|*.169.254/16
Command : jcmd 11441 VM.flags output:
11441:
-XX:CICompilerCount=3 -XX:ConcGCThreads=1 -XX:G1ConcRefinementThreads=4 -XX:G1HeapRegionSize=1048576 -XX:InitialHeapSize=67108864 -XX:MarkStackSize=4194304 -XX:MaxHeapSize=1073741824 -XX:MaxNewSize=643825664 -XX:MinHeapDeltaBytes=1048576 -XX:NonNMethodCodeHeapSize=5830092 -XX:NonProfiledCodeHeapSize=122914074 -XX:ProfiledCodeHeapSize=122914074 -XX:ReservedCodeCacheSize=251658240 -XX:+SegmentedCodeCache -XX:-UseAOT -XX:+UseCompressedClassPointers -XX:+UseCompressedOops -XX:+UseFastUnorderedTimeStamps -XX:+UseG1GC
For more instructions of usages of jcmd, see my blog post
display: inline-block; will prevent break between the words in a list item
li {
display: inline-block;
}
For game dev use random() to generate randoms. Probably at least 5x faster than using arc4random(). Modulo bias is not an issue, especially for games, when generating randoms using the full range of random(). Be sure to seed first. Call srandomdev() in AppDelegate. Here's some helper functions:
static inline int random_range(int low, int high){ return (random()%(high-low+1))+low;}
static inline CGFloat frandom(){ return (CGFloat)random()/UINT32_C(0x7FFFFFFF);}
static inline CGFloat frandom_range(CGFloat low, CGFloat high){ return (high-low)*frandom()+low;}
This is crazily stupid, but if you use the code:
fprintf("%x", variable)
and you use the -Wall flag while compiling, then gcc will kick out a warning of that it expects an argument of 'unsigned int' while the argument is of type '____'. (If this warning doesn't appear, then your variable is of type 'unsigned int'.)
Best of luck!
Edit: As was brought up below, this only applies to compile time. Very helpful when trying to figure out why your pointers aren't behaving, but not very useful if needed during run time.
The way I do it is to do a Topological Sort, counting the number of vertices visited. If that number is less than the total number of vertices in the DAG, you have a cycle.
You can resolve this in several ways:
g++
in stead of gcc
: g++ -g -o MatSim MatSim.cpp
-lstdc++
: gcc -g -o MatSim MatSim.cpp -lstdc++
<string.h>
by <string>
This is a linker problem, not a compiler issue. The same problem is covered in the question iostream linker error – it explains what is going on.
SQL Loader helps load csv files into tables: SQL*Loader
If you want sqlplus only, then it gets a bit complicated. You need to locate your sqlloader script and csv file, then run the sqlldr command.
It's a simple "&" function.
=cell&"yourtexthere"
Example - your cell says Mickey, and you want Mickey Mouse. Mickey is in A2. In B2, type
=A2&" Mouse"
Then, copy and "paste special" for values.
B2 now reads "Mickey Mouse"
One-liner using the new method in .NET. Will always return x86 Program Files folder.
Environment.Is64BitOperatingSystem ? Environment.GetEnvironmentVariable("ProgramFiles(x86)") : Environment.GetEnvironmentVariable("ProgramFiles"))
You can have all the different styles to datetime conversion
:
https://www.w3schools.com/sql/func_sqlserver_convert.asp
This has range of values :-
CONVERT(data_type(length),expression,style)
For style values,
Choose anyone you need like I needed 106.
In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic
about following the C++ standard), you can do:
int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++
If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:
int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!
Or, better yet, use a standard container:
int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>
If you still want a proper array, you can use a constant, not a variable, when creating it:
const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)
Similarly, if you want to get the size from a function in C++11, you can use a constexpr
:
constexpr int n()
{
return 10;
}
double a[n()]; // n() is a compile time constant expression
That is not always true; it only works in Windows.
For interacting with terminal in putty, Linux shell,... it will be used for returning the cursor to the beginning of line.
following picture shows the usage of that:
Without '\r':
Data comes without '\r' to the putty terminal, it has just '\n'.
it means that data will be printed just in next line.
With '\r':
Data comes with '\r', i.e. string ends with '\r\n'. So the cursor in putty terminal not only will go to the next line but also at the beginning of line
To hide from the UI, use Format > Sheet > Hide
To hide programatically, use the Visible
property of the Worksheet
object. If you do it programatically, you can set the sheet as "very hidden", which means it cannot be unhidden through the UI.
ActiveWorkbook.Sheets("Name").Visible = xlSheetVeryHidden
' or xlSheetHidden or xlSheetVisible
You can also set the Visible property through the properties pane for the worksheet in the VBA IDE (ALT+F11).
I firstly recommend you to read Hannes Dorfmann's great article about this topic.
When new view type comes, you have to edit your adapter and you have to handle so many mess things. Your adapter should be Open for extension but Closed for modification.
You may check this two project, they can give the idea about how to handle different ViewTypes in Adapter:
Switch to PNPM: https://pnpm.js.org/
The fsevents
warnings are gone (on Linux).
Even the latest yarn (2.x) shows the warnings.
Using __doPostBack
directly is sooooo the 2000s. Anybody coding WebForms in 2018 uses GetPostBackEventReference
(More seriously though, adding this as an answer for completeness. Using the __doPostBack
directly is bad practice (single underscore prefix typically indicates a private member and double indicates a more universal private member), though it probably won't change or become obsolete at this point. We have a fully supported mechanism in ClientScriptManager.GetPostBackEventReference.)
Assuming your btnRefresh is inside our UpdatePanel and causes a postback, you can use GetPostBackEventReference like this (inspiration):
function RefreshGrid() {
<%= ClientScript.GetPostBackEventReference(btnRefresh, String.Empty) %>;
}
locals
in Rails 4.2+In Rails 4.2 I had to remove the locals
part and just use size: 30
instead. Otherwise, it wouldn't pass the local variable correctly.
For example, use this:
<%= render @users, size: 30 %>
Call Path.GetFullPath on the combined path http://msdn.microsoft.com/en-us/library/system.io.path.getfullpath.aspx
> Path.GetFullPath(Path.Combine(@"C:\blah\",@"..\bling"))
C:\bling
(I agree Path.Combine ought to do this by itself)
On Raspberry Pi I had to install php5 mysql extension.
apt-get install php5-mysql
After installing the client, the webserver should be restarted. In case you're using apache, the following should work:
sudo service apache2 restart
Oddly enough, the issue for me was I was trying to open 2012 SQL Server Integration Services on SSMS 2008 R2. When I opened the same in SSMS 2012, it connected right away.
Or Joiner from Google Guava.
Joiner joiner = Joiner.on("+");
String join = joiner.join(joinList);
You can't change the value (i.e., address of) a static array. In technical terms, the lvalue of an array is the address of its first element. Hence s == &s
. It's just a quirk of the language.
This does not directly answer your question, but have you had a look at Litmus? We tend to use it mostly for testing HTML/CSS compatibility across multiple browsers (supported by Litmus).
CommonJS modules allow two ways to define exported properties. In either case you are returning an Object/Function. Because functions are first class citizens in JavaScript they to can act just like Objects (technically they are Objects). That said your question about using the new
keywords has a simple answer: Yes. I'll illustrate...
You can either use the exports
variable provided to attach properties to it. Once required in another module those assign properties become available. Or you can assign an object to the module.exports property. In either case what is returned by require()
is a reference to the value of module.exports
.
A pseudo-code example of how a module is defined:
var theModule = {
exports: {}
};
(function(module, exports, require) {
// Your module code goes here
})(theModule, theModule.exports, theRequireFunction);
In the example above module.exports
and exports
are the same object. The cool part is that you don't see any of that in your CommonJS modules as the whole system takes care of that for you all you need to know is there is a module object with an exports property and an exports variable that points to the same thing the module.exports does.
Since you can attach a function directly to module.exports
you can essentially return a function and like any function it could be managed as a constructor (That's in italics since the only difference between a function and a constructor in JavaScript is how you intend to use it. Technically there is no difference.)
So the following is perfectly good code and I personally encourage it:
// My module
function MyObject(bar) {
this.bar = bar;
}
MyObject.prototype.foo = function foo() {
console.log(this.bar);
};
module.exports = MyObject;
// In another module:
var MyObjectOrSomeCleverName = require("./my_object.js");
var my_obj_instance = new MyObjectOrSomeCleverName("foobar");
my_obj_instance.foo(); // => "foobar"
Same thing goes for non-constructor like functions:
// My Module
exports.someFunction = function someFunction(msg) {
console.log(msg);
}
// In another module
var MyModule = require("./my_module.js");
MyModule.someFunction("foobar"); // => "foobar"
Another way is to mutate the undesired columns to NULL
, this avoids the embedded parentheses :
head(iris,2) %>% mutate_at(drop.cols, ~NULL)
# Petal.Length Petal.Width Species
# 1 1.4 0.2 setosa
# 2 1.4 0.2 setosa
Apply DataAnnotation like:
[DisplayFormat(DataFormatString = "{0:MMM dd, yyyy}")]
Two ways:
Example of #2:
int[,] arr = { { 1, 2 }, { 3, 4 } }; foreach(int a in arr) Console.Write(a);
Output will be 1234. ie. exactly the same as doing i from 0 to n, and j from 0 to n.