It's already been answered a few times, but Python is a strongly typed language:
>>> x = 3
>>> y = '4'
>>> print(x+y)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
The following in JavaScript:
var x = 3
var y = '4'
alert(x + y) //Produces "34"
That's the difference between weak typing and strong typing. Weak types automatically try to convert from one type to another, depending on context (e.g. Perl). Strong types never convert implicitly.
Your confusion lies in a misunderstanding of how Python binds values to names (commonly referred to as variables).
In Python, names have no types, so you can do things like:
bob = 1
bob = "bob"
bob = "An Ex-Parrot!"
And names can be bound to anything:
>>> def spam():
... print("Spam, spam, spam, spam")
...
>>> spam_on_eggs = spam
>>> spam_on_eggs()
Spam, spam, spam, spam
For further reading:
https://en.wikipedia.org/wiki/Dynamic_dispatch
and the slightly related but more advanced:
You need to pass in a Comparator instance to the sort method otherwise the elements will be sorted in their natural order.
For more information check Collections.sort(List, Comparator)
Reading datefunc a working example of automatic datetime completion would be:
sqlite> CREATE TABLE 'test' (
...> 'id' INTEGER PRIMARY KEY,
...> 'dt1' DATETIME NOT NULL DEFAULT (datetime(CURRENT_TIMESTAMP, 'localtime')),
...> 'dt2' DATETIME NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now', 'localtime')),
...> 'dt3' DATETIME NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%f', 'now', 'localtime'))
...> );
Let's insert some rows in a way that initiates automatic datetime completion:
sqlite> INSERT INTO 'test' ('id') VALUES (null);
sqlite> INSERT INTO 'test' ('id') VALUES (null);
The stored data clearly shows that the first two are the same but not the third function:
sqlite> SELECT * FROM 'test';
1|2017-09-26 09:10:08|2017-09-26 09:10:08|2017-09-26 09:10:08.053
2|2017-09-26 09:10:56|2017-09-26 09:10:56|2017-09-26 09:10:56.894
Pay attention that SQLite functions are surrounded in parenthesis! How difficult was this to show it in one example?
Have fun!
On .Net 4.0:
System.Net.WebUtility.HtmlDecode()
No need to include assembly for a C# project
You can use...
document.getElementById('theForm').submit();
...but don't replace the innerHTML
. You could hide the form and then insert a processing... span
which will appear in its place.
var form = document.getElementById('theForm');
form.style.display = 'none';
var processing = document.createElement('span');
processing.appendChild(document.createTextNode('processing ...'));
form.parentNode.insertBefore(processing, form);
In case anyone else is wondering, you can use is_
to generate foo IS NULL
:
>>> from sqlalchemy.sql import column >>> print column('foo').is_(None) foo IS NULL >>> print column('foo').isnot(None) foo IS NOT NULL
In Oracle database we can achieve like this.
CREATE TABLE Student(
StudentID Number(38, 0) not null,
DepartmentID Number(38, 0) not null,
PRIMARY KEY (StudentID, DepartmentID)
);
PyCharm cell mode
Run Cell
and Run Cell and go to next
A cell is delimited by ##
Ref https://plugins.jetbrains.com/plugin/7858-pycharm-cell-mode
For Spark 2+ you can also use when using scala
spark.conf.getAll; //spark as spark session
You can authenticate and log the user in as stated here: https://docs.djangoproject.com/en/dev/topics/auth/default/#how-to-log-a-user-in
This will give you access to the User object from which you can get the username and then do a HttpResponseRedirect to the custom URL.
I'm afraid that's not possible. the rgba
format you know is the only one.
found this site supply a CDN for
nosniff
http headermime type
by ext nameand this site:
NOTE: RawGit has reached the end of its useful life
Accordig to this: https://bugs.mysql.com/bug.php?id=54784 casting as char should do the trick:
SELECT report_id, computer_id, MAX(CAST(date_entered AS CHAR))
FROM reports
GROUP BY report_id, computer_id
There are numerous examples that show how to do this with a private CoreTelephony call: _CTServerConnectionSetVibratorState
, but it's really not a sensible course of action since your app will get rejected for abusing the vibrate feature like that. Just don't do it.
<style type="text/css">
table {
border:1px solid black;
}
</style>
date_default_timezone_set('Asia/Kolkata');
$curDateTime = date("Y-m-d H:i:s");
$myDate = date("Y-m-d H:i:s", strtotime("2018-06-26 16:15:33"));
if($myDate < $curDateTime){
echo "active";exit;
}else{
echo "inactive";exit;
}
Improving the @Derek Springer
post with fill length function:
public static String getFileWithDate(String fileName, String fileSaperator, String dateFormat) {
String FileNamePrefix = fileName.substring(0, fileName.lastIndexOf(fileSaperator));
String FileNameSuffix = fileName.substring(fileName.lastIndexOf(fileSaperator)+1, fileName.length());
//System.out.println("File= Prefix~Suffix:"+FileNamePrefix +"~"+FileNameSuffix);
String newFileName = new SimpleDateFormat("'"+FileNamePrefix+"_'"+dateFormat+"'"+fileSaperator+FileNameSuffix+"'").format(new Date());
System.out.println("New File:"+newFileName);
return newFileName;
}
Using the funciton and its Output:
String fileSaperator = ".", format = "yyyyMMMdd_HHmm";
getFileWithDate("Text1.txt", fileSaperator, format);
getFileWithDate("Text1.doc", fileSaperator, format);
getFileWithDate("Text1.txt.json", fileSaperator, format);
Output:
Old File:Text1.txt New File:Text1_2020Nov11_1807.txt
Old File:Text1.doc New File:Text1_2020Nov11_1807.doc
Old File:Text1.txt.json New File:Text1.txt_2020Nov11_1807.json
In angularjs moment="^1.3.0"
moment('15-01-1979', 'DD-MM-YYYY').subtract(1,'days').format(); //14-01-1979
or
moment('15-01-1979', 'DD-MM-YYYY').add(1,'days').format(); //16-01-1979
``
After :
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
You can add (with standard C99 compound literal support) :
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int)) < 0)
error("setsockopt(SO_REUSEADDR) failed");
Or :
int enable = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
error("setsockopt(SO_REUSEADDR) failed");
There should be an easier way to do this, but, depending on what you're trying to do, the best route might be to convert to a regular Python datetime object:
datetime64Obj = np.datetime64('2002-07-04T02:55:41-0700')
print datetime64Obj.astype(object).year
# 2002
print datetime64Obj.astype(object).day
# 4
Based on comments below, this seems to only work in Python 2.7.x and Python 3.6+
With ES6, this is possible in exactly the manner you have described; a detailed description can be found in the documentation.
Default parameters in JavaScript can be implemented in mainly two ways:
function myfunc(a, b)
{
// use this if you specifically want to know if b was passed
if (b === undefined) {
// b was not passed
}
// use this if you know that a truthy value comparison will be enough
if (b) {
// b was passed and has truthy value
} else {
// b was not passed or has falsy value
}
// use this to set b to a default value (using truthy comparison)
b = b || "default value";
}
The expression b || "default value"
evaluates the value AND existence of b
and returns the value of "default value"
if b
either doesn't exist or is falsy.
Alternative declaration:
function myfunc(a)
{
var b;
// use this to determine whether b was passed or not
if (arguments.length == 1) {
// b was not passed
} else {
b = arguments[1]; // take second argument
}
}
The special "array" arguments
is available inside the function; it contains all the arguments, starting from index 0
to N - 1
(where N
is the number of arguments passed).
This is typically used to support an unknown number of optional parameters (of the same type); however, stating the expected arguments is preferred!
Although undefined
is not writable since ES5, some browsers are known to not enforce this. There are two alternatives you could use if you're worried about this:
b === void 0;
typeof b === 'undefined'; // also works for undeclared variables
Here's a Perl script which will edit the files in-place:
perl -i.bak -lpe 's/\s+/,/g' files*
Consecutive whitespace is converted to a single comma.
Each input file is moved to .bak
These command-line options are used:
-i.bak
edit in-place and make .bak copies
-p
loop around every line of the input file, automatically print the line
-l
removes newlines before processing, and adds them back in afterwards
-e
execute the perl code
Here is a good solution for responsive design or unknown dimensions in general if you don't need to support IE8 and lower.
.centered-axis-x {
position: absolute;
left: 50%;
transform: translate(-50%, 0);
}
.outer {
position: relative; /* or absolute */
/* unnecessary styling properties */
margin: 5%;
width: 80%;
height: 500px;
border: 1px solid red;
}
.inner {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
/* unnecessary styling properties */
max-width: 50%;
text-align: center;
border: 1px solid blue;
}
_x000D_
<div class="outer">
<div class="inner">I'm always centered<br/>doesn't matter how much text, height or width i have.<br/>The dimensions or my parent are irrelevant as well</div>
</div>
_x000D_
The clue is, that left: 50%
is relative to the parent while the translate
transform is relative to the elements width/height.
This way you have a perfectly centered element, with a flexible width on both child and parent. Bonus: this works even if the child is bigger than the parent.
You can also center it vertically with this (and again, width and height of parent and child can be totally flexible (and/or unknown)):
.centered-axis-xy {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
Keep in mind that you might need transform
vendor prefixed as well. For example -webkit-transform: translate(-50%,-50%);
It seems System.gc()
do not work on Art Android 6.0.1 Nexus 5x, So I use Runtime.getRuntime().gc();
instead.
According to the latest doc you can do the following-
Add a day
moment().add(1, 'days').calendar();
Add Year
moment().add(1, 'years').calendar();
Add Month
moment().add(1, 'months').calendar();
I prefer the other methods already posted, but some people like to use:
case "$HOST" in
user1|node*)
echo "yes";;
*)
echo "no";;
esac
Edit:
I've added your alternates to the case statement above
In your edited version you have too many brackets. It should look like this:
if [[ $HOST == user1 || $HOST == node* ]];
unoconv, it's a python tool worked in UNIX. While I use Java to invoke the shell in UNIX, it works perfect for me. My source code : UnoconvTool.java. Both JODConverter and unoconv are said to use open office/libre office.
docx4j/docxreport, POI, PDFBox are good but they are missing some formats in conversion.
how about:
scope.$watch(function() {
return {
a: thing-one,
b: thing-two,
c: red-fish,
d: blue-fish
};
}, listener...);
A) The main GUI thread will run endlessly on the call to Application.Run, so your while loop will never be reached
B) You would never want to have an endless loop like that (the while(true) loop) - it would simply freeze the thread. Not really sure what you're trying to achieve there.
I would create and show the "main" (initial) form in the Main method (as Visual Studio does for you by default). Then in your button handler, create the other form and show it as well as hiding the main form (not closing it). Then, ensure that the main form is shown again when that form is closed via an event. Example:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 otherForm = new Form2();
otherForm.FormClosed += new FormClosedEventHandler(otherForm_FormClosed);
this.Hide();
otherForm.Show();
}
void otherForm_FormClosed(object sender, FormClosedEventArgs e)
{
this.Show();
}
}
You are looking for JavaScript's String
method substring
e.g.
'Hiya how are you'.substring(0,8);
Which returns the string starting at the first character and finishing before the 9th character - i.e. 'Hiya how'.
The "use strict" Directive
The "use strict" directive is new in JavaScript 1.8.5 (ECMAScript version 5).
It is not a statement, but a literal expression, ignored by earlier versions of JavaScript.
The purpose of "use strict" is to indicate that the code should be executed in "strict mode".
With strict mode, you can not, for example, use undeclared variables.
Why Strict Mode?
Strict mode makes it easier to write "secure" JavaScript.
Strict mode changes previously accepted "bad syntax" into real errors.
As an example, in normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.
In normal JavaScript, a developer will not receive any error feedback assigning values to non-writable properties.
In strict mode, any assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object, will throw an error.
Please refer to http://www.w3schools.com/js/js_strict.asp to know more
Below a script that I used to remove all data from an SQL Server database
------------------------------------------------------------
/* Use database */
-------------------------------------------------------------
use somedatabase;
GO
------------------------------------------------------------------
/* Script to delete an repopulate the base [init database] */
------------------------------------------------------------------
-------------------------------------------------------------
/* Procedure delete all constraints */
-------------------------------------------------------------
IF EXISTS (SELECT name
FROM sysobjects
WHERE name = 'sp_DeleteAllConstraints' AND type = 'P')
DROP PROCEDURE dbo.sp_DeleteAllConstraints
GO
CREATE PROCEDURE sp_DeleteAllConstraints
AS
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
EXEC sp_MSForEachTable 'ALTER TABLE ? DISABLE TRIGGER ALL'
GO
-----------------------------------------------------
/* Procedure delete all data from the database */
-----------------------------------------------------
IF EXISTS (SELECT name
FROM sysobjects
WHERE name = 'sp_DeleteAllData' AND type = 'P')
DROP PROCEDURE dbo.sp_DeleteAllData
GO
CREATE PROCEDURE sp_DeleteAllData
AS
EXEC sp_MSForEachTable 'DELETE FROM ?'
GO
-----------------------------------------------
/* Procedure enable all constraints */
-----------------------------------------------
IF EXISTS (SELECT name
FROM sysobjects
WHERE name = 'sp_EnableAllConstraints' AND type = 'P')
DROP PROCEDURE dbo.sp_EnableAllConstraints
GO
-- ....
-- ....
-- ....
I had a problem where I had to many columns to visually inspect on the screen so a short list comp that filters and returns the offending columns is
nan_cols = [i for i in df.columns if df[i].isnull().any()]
if that's helpful to anyone
Display GIF file in android
Add the following dependency in your build.gradle file.
implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.0'
In the layout - activity_xxxxx.xml
file add the GifImageview
as below.
<pl.droidsonroids.gif.GifImageView
android:id="@+id/CorrWrong"
android:layout_width="100dp"
android:layout_height="75dp"/>
In your Java file , u can access the gif as below.
GifImageView emoji;
emoji = (GifImageView)findViewById(R.id.CorrWrong);
Code like "a => b" means, for an associative array (some languages, like Perl, if I remember correctly, call those "hash"), that 'a' is a key, and 'b' a value.
You might want to take a look at the documentations of, at least:
Here, you are having an array, called $user_list
, and you will iterate over it, getting, for each line, the key of the line in $user
, and the corresponding value in $pass
.
For instance, this code:
$user_list = array(
'user1' => 'password1',
'user2' => 'password2',
);
foreach ($user_list as $user => $pass)
{
var_dump("user = $user and password = $pass");
}
Will get you this output:
string 'user = user1 and password = password1' (length=37)
string 'user = user2 and password = password2' (length=37)
(I'm using var_dump
to generate a nice output, that facilitates debuging; to get a normal output, you'd use echo
)
"Equal or greater" is the other way arround: "greater or equals", which is written, in PHP, like this; ">="
The Same thing for most languages derived from C: C++, JAVA, PHP, ...
As a piece of advice: If you are just starting with PHP, you should definitely spend some time (maybe a couple of hours, maybe even half a day or even a whole day) going through some parts of the manual :-)
It'd help you much!
var arrLength = arr.length;
if(arrLength > maxNumber){
arr.splice( 0, arrLength - maxNumber);
}
This soultion works better in an dynamic environment like p5js. I put this inside the draw call and it clamps the length of the array dynamically.
The problem with:
arr.slice(0,5)
...is that it only takes a fixed number of items off the array per draw frame, which won't be able to keep the array size constant if your user can add multiple items.
The problem with:
if (arr.length > 4) arr.length = 4;
...is that it takes items off the end of the array, so which won't cycle through the array if you are also adding to the end with push().
you can have those "static"-like classes. but i suppose, that something really important is missing: in php you don't have an app-cycle, so you won't get a real static (or singleton) in your whole application...
see Singleton in PHP
I had this problem too and couldn't solve it without using VBA.
In my case I had a table with numbers that I wanted to be formatted and a corresponding table next to it with the desired formatting values.
i.e. While column F contains the values I want to format, the desired formatting for each cell is captured in column Z, expressed as "RED", "AMBER" or "GREEN."
Quick solution below. Manually select the range to which to apply the conditional formatting and then run the macro.
Sub ConditionalFormatting()
For Each Cell In Selection.Cells
With Cell
'clean
.FormatConditions.Delete
'green rule
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=$Z" & Cell.Row & "=""GREEN"""
.FormatConditions(.FormatConditions.Count).SetFirstPriority
With .FormatConditions(1).Font
.Color = -11489280
.TintAndShade = 0
End With
.FormatConditions(1).StopIfTrue = False
'amber rule
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=$Z" & Cell.Row & "=""AMBER"""
.FormatConditions(.FormatConditions.Count).SetFirstPriority
With .FormatConditions(1).Font
.ThemeColor = xlThemeColorAccent6
.TintAndShade = -0.249946592608417
End With
.FormatConditions(1).StopIfTrue = False
'red rule
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=$Z" & Cell.Row & "=""RED"""
.FormatConditions(.FormatConditions.Count).SetFirstPriority
With .FormatConditions(1).Font
.Color = -16776961
.TintAndShade = 0
End With
.FormatConditions(1).StopIfTrue = False
End With
Next Cell
End Sub
I faced the same problem and now found a way to solve it. First you have to delete the database of the user that you wish to drop. Then the user can be easily deleted.
I created an user named "msf" and struggled a while to delete the user and recreate it. I followed the below steps and Got succeeded.
1) Drop the database
dropdb msf
2) drop the user
dropuser msf
Now I got the user successfully dropped.
It's very simple ;-)
First you must create two drawable file one for old api version and another one for newest version, Of course! if you create the drawable file for newest api version android studio suggest you to create old one automatically. and finally set this drawable to your background view.
Sample drawable for new api version (res/drawable-v21/ripple.xml):
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="?android:colorControlHighlight">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/colorPrimary" />
<corners android:radius="@dimen/round_corner" />
</shape>
</item>
</ripple>
Sample drawable for old api version (res/drawable/ripple.xml)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@color/colorPrimary" />
<corners android:radius="@dimen/round_corner" />
</shape>
For more info about ripple drawable just visit this: https://developer.android.com/reference/android/graphics/drawable/RippleDrawable.html
Environment.GetSystemVariable("%SystemDrive%"); will provide the drive OS installed, and you can set filters to savedialog Obtain file path of C# save dialog box
If you use UPPER(text)
, the like '%lah%'
will always return zero results. Use '%LAH%'
.
Assuming you can get a Stream, FileStream or MemoryStream for instance, you can do this:
Stream file = [Some Code that Gets you a stream];
var filename = [The name of the file you want to user to download/see];
if (file != null && file.CanRead)
{
context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
context.Response.ContentType = "application/octet-stream";
context.Response.ClearContent();
file.CopyTo(context.Response.OutputStream);
}
Thats a copy and paste from some of my working code, so the content type might not be what youre looking for, but writing the stream to the response is the trick on the last line.
Personally, what I've done in the past is give them a common class id and used that to select them. It may not be ideal as they have a class specified that may not exist, but it makes the selection a hell of a lot easier. Just make sure you're unique in your classnames.
i.e. for the example above I'd use your selection by class. Better still would be to change the class name from bold to 'tcol1', so you don't get any accidental inclusions into the jQuery results. If bold does actually refer to a CSS class, you can always specify both in the class property - i.e. 'class="tcol1 bold"'.
In summary, if you can't select by Name, either use a complicated jQuery selector and accept any related performance hit or use Class selectors.
You can always limit the jQuery scope by including the table name i.e. $('#tableID > .bold')
That should restrict jQuery from searching the "world".
Its could still be classed as a complicated selector, but it quickly constrains any searching to within the table with the ID of '#tableID', so keeps the processing to a minimum.
An alternative of this if you're looking for more than 1 element within #table1 would be to look this up separately and then pass it to jQuery as this limits the scope, but saves a bit of processing to look it up each time.
var tbl = $('#tableID');
var boldElements = $('.bold',tbl);
var rows = $('tr',tbl);
if (rows.length) {
var row1 = rows[0];
var firstRowCells = $('td',row1);
}
Take a look at the documentation for HttpServletRequest
.
In order to build the URL in your example you will need to use:
getScheme()
getServerName()
getServerPort()
getContextPath()
Here is a method that will return your example:
public static String getURLWithContextPath(HttpServletRequest request) {
return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
}
Attributes are also data members and properties of a class. They are Variables declared inside class.
I used some of the work above to create this tech. I improved it a bit and thought I would share my work. Hope this helps.
function scrollErrorMessageToTop() {
var flash_error = jQuery('#flash_error');
var flash_position = flash_error.position();
function lockErrorMessageToTop() {
var place_holder = jQuery("#place_holder");
if (jQuery(this).scrollTop() > flash_position.top && flash_error.attr("position") != "fixed") {
flash_error.css({
'position': 'fixed',
'top': "0px",
"width": flash_error.width(),
"z-index": "1"
});
place_holder.css("display", "");
} else {
flash_error.css('position', '');
place_holder.css("display", "none");
}
}
if (flash_error.length > 0) {
lockErrorMessageToTop();
jQuery("#flash_error").after(jQuery("<div id='place_holder'>"));
var place_holder = jQuery("#place_holder");
place_holder.css({
"height": flash_error.height(),
"display": "none"
});
jQuery(window).scroll(function(e) {
lockErrorMessageToTop();
});
}
}
scrollErrorMessageToTop();?
This is a little bit more dynamic of a way to do the scroll. It does need some work and I will at some point turn this into a pluging but but this is what I came up with after hour of work.
I would strongly recommend field access and NOT annotations on the getters (property access) if you want to do anything more in the setters than just setting the value (e.g. Encryption or calculation).
The problem with the property access is that the setters are also called when the object is loaded. This has worked for me fine for many month until we wanted to introduce encryption. In our use case we wanted to encrypt a field in the setter and decrypt it in the getter. The problem now with property access was that when Hibernate loaded the object it was also calling the setter to populate the field and thus was encrypting the encrypted value again. This post also mentions this: Java Hibernate: Different property set function behavior depending on who is calling it
This has cause me headaches until I remembered the difference between field access and property access. Now I have moved all my annotations from property access to field access and it works fine now.
Some numpy functions for how to control the rounding: rint, floor,trunc, ceil. depending how u wish to round the floats, up, down, or to the nearest int.
>>> x = np.array([[1.0,2.3],[1.3,2.9]])
>>> x
array([[ 1. , 2.3],
[ 1.3, 2.9]])
>>> y = np.trunc(x)
>>> y
array([[ 1., 2.],
[ 1., 2.]])
>>> z = np.ceil(x)
>>> z
array([[ 1., 3.],
[ 2., 3.]])
>>> t = np.floor(x)
>>> t
array([[ 1., 2.],
[ 1., 2.]])
>>> a = np.rint(x)
>>> a
array([[ 1., 2.],
[ 1., 3.]])
To make one of this in to int, or one of the other types in numpy, astype (as answered by BrenBern):
a.astype(int)
array([[1, 2],
[1, 3]])
>>> y.astype(int)
array([[1, 2],
[1, 2]])
I have encountered this problem and i solved mentioned problem by adding -DprofileIdEnabled=true
parameter while running mvn cli command.
Please run your mvn cli command as : mvn clean install -Pdev1 -DprofileIdEnabled=true
.
In addition to this solution, you don't need to remove activeByDefault settings in your POM mentioned as previouses answer.
I hope this answer solve your problem.
You may use Reflection to set the UseDefaultCredentials
-Property from Code to "true"
System.Reflection.PropertyInfo pInfo = System.Net.WebRequest.DefaultWebProxy.GetType().GetProperty("WebProxy",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
((System.Net.WebProxy)pInfo.GetValue(System.Net.WebRequest.DefaultWebProxy, null)).UseDefaultCredentials = true;
In my case, the content type response headers was Content-Type: text/plain. So, I've read the data from Buffer like:
let data = [];
stream.on('data', (chunk) => {
console.log(Buffer.from(chunk).toString())
data.push(Buffer.from(chunk).toString())
});
One more way/syntax to do it is: git log -S "word"
Like this you can search for example git log -S "with whitespaces and stuff @/#ü !"
The following shows an example of a shared class library shared.[h,cpp] and a main.cpp module using the library. It's a very simple example and the makefile could be made much better. But it works and may help you:
shared.h defines the class:
class myclass {
int myx;
public:
myclass() { myx=0; }
void setx(int newx);
int getx();
};
shared.cpp defines the getx/setx functions:
#include "shared.h"
void myclass::setx(int newx) { myx = newx; }
int myclass::getx() { return myx; }
main.cpp uses the class,
#include <iostream>
#include "shared.h"
using namespace std;
int main(int argc, char *argv[])
{
myclass m;
cout << m.getx() << endl;
m.setx(10);
cout << m.getx() << endl;
}
and the makefile that generates libshared.so and links main with the shared library:
main: libshared.so main.o
$(CXX) -o main main.o -L. -lshared
libshared.so: shared.cpp
$(CXX) -fPIC -c shared.cpp -o shared.o
$(CXX) -shared -Wl,-soname,libshared.so -o libshared.so shared.o
clean:
$rm *.o *.so
To actual run 'main' and link with libshared.so you will probably need to specify the load path (or put it in /usr/local/lib or similar).
The following specifies the current directory as the search path for libraries and runs main (bash syntax):
export LD_LIBRARY_PATH=.
./main
To see that the program is linked with libshared.so you can try ldd:
LD_LIBRARY_PATH=. ldd main
Prints on my machine:
~/prj/test/shared$ LD_LIBRARY_PATH=. ldd main
linux-gate.so.1 => (0xb7f88000)
libshared.so => ./libshared.so (0xb7f85000)
libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb7e74000)
libm.so.6 => /lib/libm.so.6 (0xb7e4e000)
libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0xb7e41000)
libc.so.6 => /lib/libc.so.6 (0xb7cfa000)
/lib/ld-linux.so.2 (0xb7f89000)
As it is already explained in other answers, const
in C merely means that a variable is read-only. It is still a run-time value. However, you can use an enum
as a real constant in C:
enum { NUM_TYPES = 4 };
static int types[NUM_TYPES] = {
1, 2, 3, 4
};
Following works. I have it working for me with .NET 3.5 SP1
// Create the list of columns
String[] szColumns = new String[data.Columns.Count];
for (int index = 0; index < data.Columns.Count; index++)
{
szColumns[index] = data.Columns[index].ColumnName;
}
// Get the distinct records
data = data.DefaultView.ToTable(true, szColumns);
Q:Can't bind to 'pSelectableRow' since it isn't a known property of 'tr'.
A:you need to configure the primeng tabulemodule in ngmodule
In Other ways to get difference between date;
import dateutil.parser
import datetime
last_sent_date = "" # date string
timeDifference = current_date - dateutil.parser.parse(last_sent_date)
time_difference_in_minutes = (int(timeDifference.days) * 24 * 60) + int((timeDifference.seconds) / 60)
So get output in Min.
Thanks
You've done it correctly, you only need to clear your floats. Simply add
overflow: auto;
to your container class.
Try details: use any option..
MessageBox.Show("your message",
"window title",
MessageBoxButtons.OK,
MessageBoxIcon.Warning // for Warning
//MessageBoxIcon.Error // for Error
//MessageBoxIcon.Information // for Information
//MessageBoxIcon.Question // for Question
);
A little improvement to Matthew's answer could be a lookahead instead of the last capturing group:
.replace(/(\w+)(\d+)(?=\w+)/, "$1!NEW_ID!");
Or you could split on the decimal and join with your new id like this:
.split(/\d+/).join("!NEW_ID!");
Example/Benchmark here: https://codepen.io/jogai/full/oyNXBX
You need both a value and a field to assign it to. The value is TableField + 1
, so the assignment is:
SET TableField = TableField + 1
sudo apt-get install zlib1g:i386 fixed the Gradle issue on Android 2.1.1 on Xubuntu 16.04.
I think one of the solutions is to use DateTime.ParseExact or DateTime.TryParseExact
DateTime.ParseExact(dateString, format, provider);
source: http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx
If you don't want to use the url helper, you can get the same results by using the following variable:
$this->config->config['base_url']
It will return the base url for you with no extra steps required.
Simply include permissions integer in octal (works for both python 2 and python3):
os.chmod(path, 0o444)
I had the same problem. I had to follow these steps to resolve the issue:
1. Make sure you have the following dependencies:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson-version}</version> // 2.4.3
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version> // 2.4.3
</dependency>
2. Create the following filter:
public class CORSFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String origin = request.getHeader("origin");
origin = (origin == null || origin.equals("")) ? "null" : origin;
response.addHeader("Access-Control-Allow-Origin", origin);
response.addHeader("Access-Control-Allow-Methods", "POST, GET, PUT, UPDATE, DELETE, OPTIONS");
response.addHeader("Access-Control-Allow-Credentials", "true");
response.addHeader("Access-Control-Allow-Headers",
"Authorization, origin, content-type, accept, x-requested-with");
filterChain.doFilter(request, response);
}
}
3. Apply the above filter for the requests in web.xml
<filter>
<filter-name>corsFilter</filter-name>
<filter-class>com.your.package.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>corsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
I hope this is useful to somebody.
to attach to a GUID:
SqlDataSource1.SelectParameters.Add("userId", System.Data.DbType.Guid, userID);
All the other solutions suggested here, as well as most other JavaScript libraries that do HTML entity encoding/decoding, make several mistakes:
htmlDecode('≼')
should return '?'
(i.e. '\u227C'
).htmlEncode('')
should return something like 𝌆
or 𝌆
. If an implementation returns two separate entities instead (e.g. ��
or ��
), it is broken.htmlDecode('𝌆')
should return ''
and not '?'
(i.e. '\uD306'
).htmlDecode('€')
should return '€'
(i.e. '\u20AC'
).htmlDecode('&amp;')
should return '&'
, not &
.For a robust solution that avoids all these issues, use a library I wrote called he for this. From its README:
he (for “HTML entities”) is a robust HTML entity encoder/decoder written in JavaScript. It supports all standardized named character references as per HTML, handles ambiguous ampersands and other edge cases just like a browser would, has an extensive test suite, and — contrary to many other JavaScript solutions — he handles astral Unicode symbols just fine. An online demo is available.
%cd%
will give you the path of the directory from where the script is running.
Just run:
echo %cd%
You can either use .remove() on option elements:
.remove() : Remove the set of matched elements from the DOM.
$('#models option').remove(); or $('#models').remove('option');
or use .empty() on select:
.empty() : Remove all child nodes of the set of matched elements from the DOM.
$('#models').empty();
however to repopulate deleted options, you need to store the option while deleting.
You can also achieve the same using show/hide:
$("#models option").hide();
and later on to show them:
$("#models option").show();
If you're on Linux, or have cygwin available on Windows, you can run the input XML through a simple sed script that will replace <Active>True</Active>
with <Active>true</Active>
, like so:
cat <your XML file> | sed 'sX<Active>True</Active>X<Active>true</Active>X' | xmllint --schema -
If you're not, you can still use a non-validating xslt pocessor (xalan, saxon etc.) to run a simple xslt transformation on the input, and only then pipe it to xmllint.
What the xsl should contain something like below, for the example you listed above (the xslt processor should be 2.0 capable):
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<xsl:for-each select="XML">
<xsl:for-each select="Active">
<xsl:value-of select=" replace(current(), 'True','true')"/>
</xsl:for-each>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
As long as you clearly reference the other commit from the empty commit it should be fine. Something like:
Commit message errata for [commit sha1]
[new commit message]
As others have pointed out, this is often preferable to force pushing a corrected commit.
If you want to make sure that last row does not wrap and thus size the way you want it, have a look at
td {
white-space: nowrap;
}
If your lists are a and b, you can do:
map(int.__sub__, a, b)
But you probably shouldn't. No one will know what it means.
You are setting it't type
as submit
. That means that browser should post your <form>
data to the server.
In fact a tag has no type attribute according to w3schools.
So remote type
attribute and it should work for you.
Other possible solution:
tv.setText(Integer.toString(a1)); // where a1 - int value
Those are different APIs to access a MySQL backend
So it depends on what kind of code you want to produce. If you prefer object-oriented layers or plain functions...
My advice would be
Also my feeling, the mysql API would probably being deleted in future releases of PHP
.
Took me a while to find a solution for React Native so I'll put it here:
First install the buffer
package:
npm install --save buffer
Then user the node method:
const { Buffer } = require('buffer');
const length = Buffer.byteLength(string, 'utf-8');
aggfunc=pd.Series.nunique
will only count unique values for a series - in this case count the unique values for a column. But this doesn't quite reflect as an alternative to aggfunc='count'
For simple counting, it better to use aggfunc=pd.Series.count
In Python, you can do it the same way we do it with mobile application
web.open('https://web.whatsapp.com/send?phone='+phone_no+'&text='+message)
This will prepopulate the text for given mobile number(Enter the phone_no as CountryCode and the number eg +918888888888) Then using pyautogui you can press enter onto whatsapp.web
Working code :
def sendwhatmsg(phone_no, message, time_hour, time_min):
'''Sends whatsapp message to a particulal number at given time'''
if time_hour == 0:
time_hour = 24
callsec = (time_hour*3600)+(time_min*60)
curr = time.localtime()
currhr = curr.tm_hour
currmin = curr.tm_min
currsec = curr.tm_sec
currtotsec = (currhr*3600)+(currmin*60)+(currsec)
lefttm = callsec-currtotsec
if lefttm <= 0:
lefttm = 86400+lefttm
if lefttm < 60:
raise Exception("Call time must be greater than one minute")
else:
sleeptm = lefttm-60
time.sleep(sleeptm)
web.open('https://web.whatsapp.com/send?phone='+phone_no+'&text='+message)
time.sleep(60)
pg.press('enter')
I've taken this from this repository - Github repo
If you are looking for the folder such as brushes, curves, etc. you can try:
/home/<username>/.gimp-2.8
This folder will contain all the gimp folders
.
Good Luck.
Here's a version using template literals. It maps
over the data creating new arrays of strings build from the template literals, and then adds them to the document with insertAdjacentHTML
:
let data = [_x000D_
['Title', 'Artist', 'Duration', 'Created'],_x000D_
['hello', 'me', '2', '2019'],_x000D_
['ola', 'me', '3', '2018'],_x000D_
['Bob', 'them', '4.3', '2006']_x000D_
];_x000D_
_x000D_
function getCells(data, type) {_x000D_
return data.map(cell => `<${type}>${cell}</${type}>`).join('');_x000D_
}_x000D_
_x000D_
function createBody(data) {_x000D_
return data.map(row => `<tr>${getCells(row, 'td')}</tr>`).join('');_x000D_
}_x000D_
_x000D_
function createTable(data) {_x000D_
const [headings, ...rows] = data;_x000D_
return `_x000D_
<table>_x000D_
<thead>${getCells(headings, 'th')}</thead>_x000D_
<tbody>${createBody(rows)}</tbody>_x000D_
</table>_x000D_
`;_x000D_
}_x000D_
_x000D_
document.body.insertAdjacentHTML('beforeend', createTable(data));
_x000D_
table { border-collapse: collapse; }_x000D_
tr { border: 1px solid #dfdfdf; }_x000D_
th, td { padding: 2px 5px 2px 5px;}
_x000D_
These are all interesting but what if you have a version number and you don't know the size of any one segment in string from and you want to drop the last segment. Something like 20.0.1.300 and I want to end up with 20.0.1 without the 300 on the end. I have this so far:
str('20.0.1.300'.split('.')[:3])
which returns in list form as:
['20', '0', '1']
How do I get it back to into a single string separated by periods
20.0.1
Use the which function:
A <- c('a','a','b','b','b')
B <- c(1,0,1,1,0)
d <- data.frame(A, B)
r <- with(d, which(B==0, arr.ind=TRUE))
newd <- d[-r, ]
To store the third line into a variable, use below syntax:
variable=`echo "$1" | sed '3q;d' urfile`
To store the changed line into a variable, use below syntax:
variable=echo 'overflow' | sed -e "s/over/"OVER"/g"
output:OVERflow
Very elegant solution you can achieve by using chain of Promises:
app.put('url', (req, res) => {
const modelId = req.body.model_id;
const newName = req.body.name;
MyModel.findById(modelId).then((model) => {
return Object.assign(model, {name: newName});
}).then((model) => {
return model.save();
}).then((updatedModel) => {
res.json({
msg: 'model updated',
updatedModel
});
}).catch((err) => {
res.send(err);
});
});
RecyclerViews are fine to put in ScrollViews so long as they aren't scrolling themselves. In this case, it makes sense to make it a fixed height.
The proper solution is to use wrap_content
on the RecyclerView height and then implement a custom LinearLayoutManager that can properly handle the wrapping.
Copy this LinearLayoutManager into your project: https://github.com/serso/android-linear-layout-manager/blob/master/lib/src/main/java/org/solovyev/android/views/llm/LinearLayoutManager.java
Then wrap the RecyclerView:
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
And set it up like so:
RecyclerView list = (RecyclerView)findViewById(R.id.list);
list.setHasFixedSize(true);
list.setLayoutManager(new com.example.myapp.LinearLayoutManager(list.getContext()));
list.setAdapter(new MyViewAdapter(data));
Edit: This can cause complications with scrolling because the RecyclerView can steal the ScrollView's touch events. My solution was just to ditch the RecyclerView in all and go with a LinearLayout, programmatically inflate subviews, and add them to the layout.
Above answers have enough description for the asked question.
Adding to that, Tensorflow has optimised the operation of applying the activation function then calculating cost using its own activation followed by cost functions. Hence it is a good practice to use: tf.nn.softmax_cross_entropy()
over tf.nn.softmax(); tf.nn.cross_entropy()
You can find prominent difference between them in a resource intensive model.
The pattern matches all non-digit characters. This will restrict you to non-negative integers, but for your example it will be more than sufficient.
string input = "0, 10, 20, 30, 100, 200";
Regex.Split(input, @"\D+");
The parameters to main
represent the command line parameters provided to the program when it was started. The argc
parameter represents the number of command line arguments, and char *argv[]
is an array of strings (character pointers) representing the individual arguments provided on the command line.
You just need to use single quotes:
$ echo "$TEST"
test
$ echo '$TEST'
$TEST
Inside single quotes special characters are not special any more, they are just normal characters.
I was facing the same issue, fixed by doing this in MainActivity
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
And In Fragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (view == null) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_example, container, false);
init();
}
getActivity().setTitle("Choose Fragment");
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.example_menu, menu);
}
I made an update of the actual answer.
This seems to be working on firefox and chrome: http://jsfiddle.net/gatsbimantico/QJeB7/1/embedded/result/
.x{
columns: 5em;
-webkit-columns: 5em; /* Safari and Chrome */
-moz-columns: 5em; /* Firefox */
}
.x li{
float:left;
break-inside: avoid-column;
-webkit-column-break-inside: avoid; /* Safari and Chrome */
}
Note: The float property seems to be the one making the block behaviour.
If you are using a self-hosted version of GitLab then you may consider running this command.
grep gitlab /opt/gitlab/version-manifest.txt
With EF or LINQ to SQL:
var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();
With LINQ to Objects I suggest to use morelinq extension MaxBy
(get morelinq from nuget):
var item = items.MaxBy(i => i.Value);
I had a similar problem... I resolved it like this (i'm not an git expert so i don't know if it is a right solution, but it worked for me):
git pull origin master --allow-unrelated-histories
git merge origin origin/master
git rm README.md
git commit -m 'removed readme.md'
git push origin master
The final version taking care of all previous complaints (ports, logical url, relative url, existing absolute url...etc.) considering the current handler is the page:
public static string ConvertToAbsoluteUrl(string url)
{
if (!IsAbsoluteUrl(url))
{
if (HttpContext.Current != null && HttpContext.Current.Request != null && HttpContext.Current.Handler is System.Web.UI.Page)
{
var originalUrl = HttpContext.Current.Request.Url;
return string.Format("{0}://{1}{2}{3}", originalUrl.Scheme, originalUrl.Host, !originalUrl.IsDefaultPort ? (":" + originalUrl.Port) : string.Empty, ((System.Web.UI.Page)HttpContext.Current.Handler).ResolveUrl(url));
}
throw new Exception("Invalid context!");
}
else
return url;
}
private static bool IsAbsoluteUrl(string url)
{
Uri result;
return Uri.TryCreate(url, UriKind.Absolute, out result);
}
Once the array size is fixed while running the program ,it's size can't be changed further. So better go for ArrayList while dealing with dynamic arrays.
If you need this for several words or elements, but can't apply it to a whole TD or similar, the Span tag can be used.
<span style="white-space: nowrap">Text to break together</span>
or
<span class=nobr>Text to break together</span>
If you use the class version, remember to set up the CSS as detailed in the accepted answer.
Your regex ^[0-9]
matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $
to the end:
^[0-9]*$
This accepts any number of digits, including none. To accept one or more digits, change the *
to +
. To accept exactly one digit, just remove the *
.
UPDATE: You mixed up the arguments to IsMatch
. The pattern should be the second argument, not the first:
if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))
CAUTION: In JavaScript, \d
is equivalent to [0-9]
, but in .NET, \d
by default matches any Unicode decimal digit, including exotic fare like ? (Myanmar 2) and ? (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9]
(or supply the RegexOptions.ECMAScript flag).
style="text-align:center;margin-top:0;" cz-shortcut-listen="true"
paste this at your body tag!
this will remove the top margin
"I actually tried to had a normal objective discusssion over pros and cons of 1., using framework over pure javascript and 2., jquery vs. others, since jQuery seems to be easiest to work with with quickest learning curve."
Using any framework because you don't want to actually learn the underlying language is absolutely wrong not only for JavaScript, but for any other programming language.
"Is there any reason (besides browser sniffing and personal "hate" against John Resig) why jQuery is wrong?"
Most of the hate agains it comes from the exaggerated fanboyism which pollutes forums with "use jQuery" as an answer for every single JavaScript question and the overuse which produces code in which simple statements such as declaring a variable are done through library calls.
Nevertheless, there are also some legit technical issues such as the shared guilt in producing illegible code and overhead. Of course those two are aggravated by the lack of developer proficiency rather than the library itself.
updated:
startdate = "20.03.2014";
var new_date = moment(startdate, "DD-MM-YYYY").add(5,'days');
alert(new_date)
You can stash
(save the changes in temporary box) then, back to master
branch HEAD.
$ git add .
$ git stash
$ git checkout master
Jump Over Commits Back and Forth:
Go to a specific commit-sha
.
$ git checkout <commit-sha>
If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.
# checkout a new branch, add, commit, push
$ git checkout -b <branch-name>
$ git add .
$ git commit -m 'Commit message'
$ git push origin HEAD # push the current branch to remote
$ git checkout master # back to master branch now
If you have changes in the specific commit and don't want to keep the changes, you can do stash
or reset
then checkout to master
(or, any other branch).
# stash
$ git add -A
$ git stash
$ git checkout master
# reset
$ git reset --hard HEAD
$ git checkout master
After checking out a specific commit if you have no uncommitted change(s) then, just back to master
or other
branch.
$ git status # see the changes
$ git checkout master
# or, shortcut
$ git checkout - # back to the previous state
In my case
In Control Panel -> System -> Advanced system settings -> Environment Variables
there is no JDK_HOME
OR JAVA_HOME
SO
I added an entry named: JDK_HOME pointing to: C:\Program Files\Java\jdk1.8.0_25\ (you have to point this to your JDK instalation path)
And all seems to work fine now
To do this, you simple need to add a border-top
or border-bottom
to your <hr/>
tag as the following:
<hr style="border-top: 2px dotted navy" />
with any line type or color you want
auto p = boost::filesystem::path("test/folder/file.txt");
std::cout << p.parent_path() << '\n'; // test/folder
std::cout << p.parent_path().filename() << '\n'; // folder
std::cout << p.filename() << '\n'; // file.txt
You may need p.parent_path().filename()
to get name of parent folder.
Constructor is basicaly used for initialising the variables at the time of creation of object
"Scripting language" is one of those fuzzy concepts which can mean many things. Usually it refers to the fact that there exists a one step process taking you from the source code to execution.
For example in Perl you do: perl my_source.pl
Given the above criteria PHP is a scripting language (even though you can have a "compilation" process for example when using the Zend Encoder to "protect" the source code).
PS. Often (but not always) scripting languages are interpreted. Also often (but again, not always) scripting languages are dynamically typed.
OK, if your objective is to find out what you can fix to make it faster, that's a little different goal. Measuring the time that functions take is a good way to find out if what you did made a difference, but to find out what to do you need a different technique. This is what I recommend, and I know you can do it on iPhones.
Edit: Reviewers suggested I elaborate the answer, so I'm trying to think of a brief way to say it.
Your overall program takes enough clock time to bother you. Suppose that's N seconds.
You're assuming you can speed it up. The only way you can do that is by making it not do something it's doing in that time, accounting for m seconds.
You don't initially know what that thing is. You can guess, as all programmers do, but it could easily be something else. Whatever it is, here's how you can find it:
Since that thing, whatever it is, accounts for fraction m/N of the time, that means if you pause it at random the probability is m/N that you will catch it in the act of doing that thing. Of course it might be doing something else, but pause it and see what it's doing.
Now do it again. If you see it doing that same thing again, you can be more suspicious.
Do it 10 times, or 20. Now if you see it doing some particular thing (no matter how you describe it) on multiple pauses, that you can get rid of, you know two things. You know very roughly what fraction of time it takes, but you know very exactly what to fix.
If you also want to know very exactly how much time will be saved, that's easy. Measure it before, fix it, and measure it after. If you're really disappointed, back out the fix.
Do you see how this is different from measuring? It's finding, not measuring. Most profiling is based on measuring as exactly as possible how much time is taken, as if that's important, and hand-waves the problem of identifying what needs to be fixed. Profiling does not find every problem, but this method does find every problem, and it's the problems you don't find that hurt you.
Use CreateDirectory (char *DirName, SECURITY_ATTRIBUTES Attribs);
If the function succeeds it returns non-zero otherwise NULL
.
I was experiencing the same but this was solved by running with specific python 3.6 as below:
python3.6 manage.py runserver
An alternative that can be more flexible:
Example: To enter the text XYZ at the beginning of the line
:%norm IXYZ
What's happening here?
%
== Execute on every linenorm
== Execute the following keys in normal modeI
== Insert at beginning of lineXYZ
== The text you want to enterThen you hit Enter, and it executes.
Specific to your request:
:%norm Ivendor_
You can also choose a particular range:
:2,4norm Ivendor_
Or execute over a selected visual range:
:'<,'>norm Ivendor_
Just use Array.from()
method to convert it to an Array
:
myMap : Map<string, boolean>;
for(let key of Array.from( myMap.keys()) ) {
console.log(key);
}
Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.
That option could be useful when copying very large files over a potentially unstable connection.
Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.
Classic mode (the only mode in IIS6 and below) is a mode where IIS only works with ISAPI extensions and ISAPI filters directly. In fact, in this mode, ASP.NET is just an ISAPI extension (aspnet_isapi.dll) and an ISAPI filter (aspnet_filter.dll). IIS just treats ASP.NET as an external plugin implemented in ISAPI and works with it like a black box (and only when it's needs to give out the request to ASP.NET). In this mode, ASP.NET is not much different from PHP or other technologies for IIS.
Integrated mode, on the other hand, is a new mode in IIS7 where IIS pipeline is tightly integrated (i.e. is just the same) as ASP.NET request pipeline. ASP.NET can see every request it wants to and manipulate things along the way. ASP.NET is no longer treated as an external plugin. It's completely blended and integrated in IIS. In this mode, ASP.NET HttpModule
s basically have nearly as much power as an ISAPI filter would have had and ASP.NET HttpHandler
s can have nearly equivalent capability as an ISAPI extension could have. In this mode, ASP.NET is basically a part of IIS.
From book Mahout in Action, and I think it explains the difference very well:
Classification algorithms are related to, but still quite different from, clustering algorithms such as the k-means algorithm.
Classification algorithms are a form of supervised learning, as opposed to unsupervised learning, which happens with clustering algorithms.
A supervised learning algorithm is one that’s given examples that contain the desired value of a target variable. Unsupervised algorithms aren’t given the desired answer, but instead must find something plausible on their own.
Sample code block for strong password:
(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?=\\S+$).{6,18}
This is changed in Java 6 update 18.
Assuming that we have more than 1 GB of physical memory (quite common these days), it's always 1/4th of your physical memory for the server vm.
In honeycomb, API level 11, it is possible, We can use setScalaX and setScaleY with pivot point
I have explained it here
Zooming a view completely
Pinch Zoom to view completely
The problem solved when I don't use any declaration like var, let or const
$products=R::findAll('products');
$string = rtrim(implode(',', $products), ',');
echo $string;
You can do it by using a constructor, like this:
struct Date
{
int day;
int month;
int year;
Date()
{
day=0;
month=0;
year=0;
}
};
or like this:
struct Date
{
int day;
int month;
int year;
Date():day(0),
month(0),
year(0){}
};
In your case bar.c is undefined,and its value depends on the compiler (while a and b were set to true).
SELECT name,COUNT(*) as count
FROM tablename
GROUP BY name
ORDER BY count DESC;
I'm having a hard time figuring out what exactly you're looking for here, so hope I'm not way off base.
I'm assuming what you mean is that when a keyup event occurs on the input with class "start" you want to get the values of all the inputs in neighbouring <td>s:
$('.start').keyup(function() {
var otherInputs = $(this).parents('td').siblings().find('input');
for(var i = 0; i < otherInputs.length; i++) {
alert($(otherInputs[i]).val());
}
return false;
});
Suppose that you have defined the positions and sizes of the rectangles like this:
My C++ implementation is like this:
class Vector2D
{
public:
Vector2D(int x, int y) : x(x), y(y) {}
~Vector2D(){}
int x, y;
};
bool DoRectanglesOverlap( const Vector2D & Pos1,
const Vector2D & Size1,
const Vector2D & Pos2,
const Vector2D & Size2)
{
if ((Pos1.x < Pos2.x + Size2.x) &&
(Pos1.y < Pos2.y + Size2.y) &&
(Pos2.x < Pos1.x + Size1.x) &&
(Pos2.y < Pos1.y + Size1.y))
{
return true;
}
return false;
}
An example function call according to the given figure above:
DoRectanglesOverlap(Vector2D(3, 7),
Vector2D(8, 5),
Vector2D(6, 4),
Vector2D(9, 4));
The comparisons inside the if
block will look like below:
if ((Pos1.x < Pos2.x + Size2.x) &&
(Pos1.y < Pos2.y + Size2.y) &&
(Pos2.x < Pos1.x + Size1.x) &&
(Pos2.y < Pos1.y + Size1.y))
?
if (( 3 < 6 + 9 ) &&
( 7 < 4 + 4 ) &&
( 6 < 3 + 8 ) &&
( 4 < 7 + 5 ))
Extra ( ) brackets may create problems in else if flow. This also creates Syntax error (missing operator) in query expression.
You can direct use the shortcut by pressing Ctrl+Shift+O
A solution using retype()
from hablar to coerce factors to character or numeric type depending on feasability. I'd use dplyr
for applying max to each column.
Code
library(dplyr)
library(hablar)
# Retype() simplifies each columns type, e.g. always removes factors
d <- d %>% retype()
# Check max for each column
d %>% summarise_all(max)
Result
Not the new column types.
v1 v2 v3 v4
<dbl> <chr> <dbl> <chr>
1 0.974 j 1.09 J
Data
# Sample data borrowed from @joran
d <- data.frame(v1 = runif(10), v2 = letters[1:10],
v3 = rnorm(10), v4 = LETTERS[1:10],stringsAsFactors = TRUE)
Your PersonSheets has a property int Id
, Id
isn't in the post, so modelbinding fails. Make Id nullable (int?) or send atleast Id = 0 with the POst .
I don't know what to tell you, but the same problem occured with jQuery table sorting and SEARCH. When there is nothing left in the table, where you are searching a string for example, you get this error too. Even in Google Analytics this error occurs often.
There is one open source project which can do that and much more.
7.Bits().ToString(); // 7 b
8.Bits().ToString(); // 1 B
(.5).Kilobytes().Humanize(); // 512 B
(1000).Kilobytes().ToString(); // 1000 KB
(1024).Kilobytes().Humanize(); // 1 MB
(.5).Gigabytes().Humanize(); // 512 MB
(1024).Gigabytes().ToString(); // 1 TB
Diffuse is also very good. It even lets you easily adjust how lines are matched up, by defining match-points.
You can also rotate the ImageView
using a RotateAnimation
:
RotateAnimation rotateAnimation = new RotateAnimation(from, to,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
rotateAnimation.setInterpolator(new LinearInterpolator());
rotateAnimation.setDuration(ANIMATION_DURATION);
rotateAnimation.setFillAfter(true);
imageView.startAnimation(rotateAnimation);
You can use the built-in FolderBrowserDialog class for this. Don't mind that it's in the System.Windows.Forms
namespace.
using (var dialog = new System.Windows.Forms.FolderBrowserDialog())
{
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
}
If you want the window to be modal over some WPF window, see the question How to use a FolderBrowserDialog from a WPF application.
EDIT: If you want something a bit more fancy than the plain, ugly Windows Forms FolderBrowserDialog, there are some alternatives that allow you to use the Vista dialog instead:
Third-party libraries, such as Ookii dialogs (.NET 4.5+)
The Windows API Code Pack-Shell:
using Microsoft.WindowsAPICodePack.Dialogs;
...
var dialog = new CommonOpenFileDialog();
dialog.IsFolderPicker = true;
CommonFileDialogResult result = dialog.ShowDialog();
Note that this dialog is not available on operating systems older than Windows Vista, so be sure to check CommonFileDialog.IsPlatformSupported
first.
This is a more generic solution, that can be use for any Enum object, so be free of used.
static public List<Object> constFromEnumToList(Class enumType) {
List<Object> nueva = new ArrayList<Object>();
if (enumType.isEnum()) {
try {
Class<?> cls = Class.forName(enumType.getCanonicalName());
Object[] consts = cls.getEnumConstants();
nueva.addAll(Arrays.asList(consts));
} catch (ClassNotFoundException e) {
System.out.println("No se localizo la clase");
}
}
return nueva;
}
Now you must call this way:
constFromEnumToList(MiEnum.class);
keytool is part of jdk, it should be $JAVA_HOME/bin/keytool
As said, iteration is needed. For instance, in modern browser you could have:
var key = Object.keys(obj).filter(function(key) {return obj[key] === value})[0];
Where value
contains the value you're looking for.
Said that, I would probably use a loop.
Otherwise you could use a proper "hashmap" object - there are several implementation in JS around - or implement by your own.
UPDATE 2018
Six years passed, but I still get some vote here, so I feel like a more modern solution – for modern browser/environment – should be mentioned in the answer itself and not just in the comments:
const key = Object.keys(obj).find(key => obj[key] === value);
Of course it can be also a function:
const getKeyByValue = (obj, value) =>
Object.keys(obj).find(key => obj[key] === value);
It depends on how you format the Guid:
Guid.NewGuid().ToString()
=> 36 characters (Hyphenated)
outputs: 12345678-1234-1234-1234-123456789abc
Guid.NewGuid().ToString("D")
=> 36 characters (Hyphenated, same as ToString()
)
outputs: 12345678-1234-1234-1234-123456789abc
Guid.NewGuid().ToString("N")
=> 32 characters (Digits only)
outputs: 12345678123412341234123456789abc
Guid.NewGuid().ToString("B")
=> 38 characters (Braces)
outputs: {12345678-1234-1234-1234-123456789abc}
Guid.NewGuid().ToString("P")
=> 38 characters (Parentheses)
outputs: (12345678-1234-1234-1234-123456789abc)
Guid.NewGuid().ToString("X")
=> 68 characters (Hexadecimal)
outputs: {0x12345678,0x1234,0x1234,{0x12,0x34,0x12,0x34,0x56,0x78,0x9a,0xbc}}
http://www.besthostratings.com/articles/force-ssl-htaccess.html
Sometimes you may need to make sure that the user is browsing your site over securte connection. An easy to way to always redirect the user to secure connection (https://) can be accomplished with a .htaccess file containing the following lines:
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]
Please, note that the .htaccess should be located in the web site main folder.
In case you wish to force HTTPS for a particular folder you can use:
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} somefolder
RewriteRule ^(.*)$ https://www.domain.com/somefolder/$1 [R,L]
The .htaccess file should be placed in the folder where you need to force HTTPS.
Typecasting in Objective-C is easy as:
NSArray *threeViews = @[[UIView new], [UIView new], [UIView new]];
UIView *firstView = (UIView *)threeViews[0];
However, what happens if first object is not UIView
and you try to use it:
NSArray *threeViews = @[[NSNumber new], [UIView new], [UIView new]];
UIView *firstView = (UIView *)threeViews[0];
CGRect firstViewFrame = firstView.frame; // CRASH!
It will crash. And it's easy to find such crash for this case, but what if those lines are in different classes and the third line is executed only once in 100 cases. I bet your customers find this crash, not you! A plausible solution is to crash early, like this:
UIView *firstView = (UIView *)threeViews[0];
NSAssert([firstView isKindOfClass:[UIView class]], @"firstView is not UIView");
Those assertions doesn't look very nice, so we could improve them with this handy category:
@interface NSObject (TypecastWithAssertion)
+ (instancetype)typecastWithAssertion:(id)object;
@end
@implementation NSObject (TypecastWithAssertion)
+ (instancetype)typecastWithAssertion:(id)object {
if (object != nil)
NSAssert([object isKindOfClass:[self class]], @"Object %@ is not kind of class %@", object, NSStringFromClass([self class]));
return object;
}
@end
This is much better:
UIView *firstView = [UIView typecastWithAssertion:[threeViews[0]];
P.S. For collections type safety Xcode 7 have a much better than typecasting - generics
With define keyword constant, you will get the facilities of case insensitive but with const keyword you did not.
define("FOO", 1, true);
echo foo; //1
echo "<br/>";
echo FOO; //1
echo "<br/>";
class A {
const FOO = 1;
}
echo A::FOO; //valid
echo "<br/>";
//but
class B {
define FOO = 1; //syntax error, unexpected 'define'
}
echo B::FOO; //invalid
Suppose your "Don't Check" list is on Sheet2 in cells A1:A100
, say, and your current client IDs are in Sheet1 in Column A.
What you would do is:
Conditional Formatting
> New Rule
> Use a Formula to determine which cells to format
=ISNUMBER(MATCH($A1,Sheet2!$A$1:$A$100,0))
and select how you want those rows formattedAnd that should do the trick.
Here my example ssl socket server threads (multiple connection) https://github.com/breakermind/CppLinux/blob/master/QtSslServerThreads/breakermindsslserver.cpp
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <iostream>
#include <breakermindsslserver.h>
using namespace std;
int main(int argc, char *argv[])
{
BreakermindSslServer boom;
boom.Start(123,"/home/user/c++/qt/BreakermindServer/certificate.crt", "/home/user/c++/qt/BreakermindServer/private.key");
return 0;
}
For removing padding around toggle button we need set minWidth and minHeight 0dp.android:minWidth="0dp" android:minHeight="0dp"
<ToggleButton
android:id="@+id/toggle_row_notifications"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="0dp"
android:minHeight="0dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:padding="@dimen/_5sdp"
android:textOn=""
android:textOff=""
android:background="@android:color/transparent"
android:button="@drawable/toggle_selector"
/>
set your drawable file to button attribute like: android:button="@drawable/toggle_selector"
Below is my toggle_selecter.xml
file
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/notifications_toggle_on"
android:state_checked="true"/>
<item android:drawable="@drawable/notifications_toggle_off"
android:state_checked="false"/>
</selector>
I may be wrong but it seems people seem to be going way off-topic for
i just need to know if the gps icon at the top of the screen is blinking (no actual fix)
That is easily done with
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean gps_on = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
To see if you have a solid fix, things get a little trickier:
public class whatever extends Activity {
LocationManager lm;
Location loc;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
loc = null;
request_updates();
}
private void request_updates() {
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// GPS is enabled on device so lets add a loopback for this locationmanager
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0, 0, locationListener);
}
}
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Each time the location is changed we assign loc
loc = location;
}
// Need these even if they do nothing. Can't remember why.
public void onProviderDisabled(String arg0) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
Now whenever you want to see if you have fix?
if (loc != null){
// Our location has changed at least once
blah.....
}
If you want to be fancy you can always have a timeout using System.currentTimeMillis() and loc.getTime()
Works reliably, at least on an N1 since 2.1.
Check out this snippet:
Private Sub openDialog()
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
' Set the title of the dialog box.
.Title = "Please select the file."
' Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls"
.Filters.Add "All Files", "*.*"
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox
End If
End With
End Sub
I think this is what you are asking for.
You may use NULL
instead of NA
. This creates a truly empty data frame.
i don't see any for loop to initalize the variables.you can do something like this.
for(i=0;i<50;i++){
/* Code which is necessary with a simple if statement*/
}
When in a window, go to GO ---> ENTER LOCATION... And then copy paste this: /opt/lampp/htdocs
Now you are at the htdocs folder. Then you can add your files there, or in a new folder inside this one (for example "myproyects" folder and inside it your files... and then from a navigator you access it by writting: localhost/myproyects/nameofthefile.php
What I did to find it easily everytime, was right click on "myproyects" folder and "Make link..."... then I moved this link I created to the Desktop and then I didn't have to go anymore to the htdocs, but just enter the folder I created in my Desktop.
Hope it helps!!
All three way you can use for newline character :
'\n'
"\n"
"""\n"""
For some people which might still see this question, there is another way on how to append another array element(s) in C. You can refer to this blog which shows a C code on how to append another element in your array
.
But you can also use memcpy()
function, to append element(s) of another array. You can use memcpy()
like this:
#include <stdio.h>
#include <string.h>
int main(void)
{
int first_array[10] = {45, 2, 48, 3, 6};
int scnd_array[] = {8, 14, 69, 23, 5};
// 5 is the number of the elements which are going to be appended
memcpy(a + 5, b, 5 * sizeof(int));
// loop through and print all the array
for (i = 0; i < 10; i++) {
printf("%d\n", a[i]);
}
}
create a new page php and add this code:
<?php_x000D_
function ch_title($title){_x000D_
$output = ob_get_contents();_x000D_
if ( ob_get_length() > 0) { ob_end_clean(); }_x000D_
$patterns = array("/<title>(.*?)<\/title>/");_x000D_
$replacements = array("<title>$title</title>");_x000D_
$output = preg_replace($patterns, $replacements,$output);_x000D_
echo $output;_x000D_
}_x000D_
?>
_x000D_
in <head>
add code: <?php require 'page.php' ?>
and on each page you call the function ch_title('my title');
using subprocess ping command to ping decode it because the response is binary:
import subprocess
ping_response = subprocess.Popen(["ping", "-a", "google.com"], stdout=subprocess.PIPE).stdout.read()
result = ping_response.decode('utf-8')
print(result)
Check your my.cnf
file in your MySQL program directory, look for
[mysqld]
datadir=
The datadir
is the location where your MySQL database is stored.
@user.route('/<user_id>', defaults={'username': default_value})
@user.route('/<user_id>/<username>')
def show(user_id, username):
#
pass
It appears that you can throw only RuntimeException from the method orElseThrow
. Otherwise you will get an error message like MyException cannot be converted to java.lang.RuntimeException
Update:- This was an issue with an older version of JDK. I don't see this issue with the latest versions.
I had the Same problem when connecting to a Socket and I came up with the below solution ,It works Fine for me. `
private bool CheckConnectivityForProxyHost(string hostName, int port)
{
if (string.IsNullOrEmpty(hostName))
return false;
bool isUp = false;
Socket testSocket = null;
try
{
testSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = null;
if (testSocket != null && NetworkingCollaboratorBase.GetResolvedConnecionIPAddress(hostName, out ip))//Use a method to resolve your IP
{
IPEndPoint ipEndPoint = new IPEndPoint(ip, port);
isUp = false;
//time out 5 Sec
CallWithTimeout(ConnectToProxyServers, 5000, testSocket, ipEndPoint);
if (testSocket != null && testSocket.Connected)
{
isUp = true;
}
}
}
}
catch (Exception ex)
{
isUp = false;
}
finally
{
try
{
if (testSocket != null)
{
testSocket.Shutdown(SocketShutdown.Both);
}
}
catch (Exception ex)
{
}
finally
{
if (testSocket != null)
testSocket.Close();
}
}
return isUp;
}
private void CallWithTimeout(Action<Socket, IPEndPoint> action, int timeoutMilliseconds, Socket socket, IPEndPoint ipendPoint)
{
try
{
Action wrappedAction = () =>
{
action(socket, ipendPoint);
};
IAsyncResult result = wrappedAction.BeginInvoke(null, null);
if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
{
wrappedAction.EndInvoke(result);
}
}
catch (Exception ex)
{
}
}
private void ConnectToProxyServers(Socket testSocket, IPEndPoint ipEndPoint)
{
try
{
if (testSocket == null || ipEndPoint == null)
return;
testSocket.Connect(ipEndPoint);
}
catch (Exception ex)
{
}
}
Here is the formula
create a new rule in conditional formating based on a formula. Use the following formula and apply it to $A:$A
=NOT(ISERROR(MATCH(A1,$B$1:$B$1000,0)))
here is the example sheet to download if you encounter problems
UPDATE
here is @pnuts's suggestion which works perfect as well:
=MATCH(A1,B:B,0)>0
Feel free to disregard this solution as subtracting a list from an Index does not preserve the order of the original Index, if that's important.
In [61]: df.reindex(columns=pd.Index(['x', 'y']).append(df.columns - ['x', 'y']))
Out[61]:
x y a b
0 3 -1 1 2
1 6 -2 2 4
2 9 -3 3 6
3 12 -4 4 8
I believe you have libx264
installed and configured with ffmpeg
to convert video to h264
... Then you can try with -vcodec libx264
... The -format
option is for showing available formats, this is not a conversion option I think...
Mr Purple's example I used in mysql trigger like that,
begin
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
Select COUNT(*) from user where deleted_at is null INTO n;
SET i=0;
WHILE i<n DO
INSERT INTO user_notification(notification_id,status,userId)values(new.notification_id,1,(Select userId FROM user LIMIT i,1)) ;
SET i = i + 1;
END WHILE;
end
If you are familiar with Maven there also rpm-maven-plugin
which simplifies making RPMs: you have to write only pom.xml
which will be then used to build RPM. RPM build environment is created implicitly by the plugin.
Just put in fg
and go back to your most recently suspended program.
Sometimes .concat() is better than .push() since .concat() returns the new array whereas .push() returns the length of the array.
Therefore, if you are setting a variable equal to the result, use .concat().
items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];
newArray = items.push({'id':5})
In this case, newArray will return 5 (the length of the array).
newArray = items.concat({'id': 5})
However, here newArray will return [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}, {'id': 5}].
Solution native Javascript :
document.getElementById("theSelectId").insertBefore(new Option('', ''), document.getElementById("theSelectId").firstChild);
example : http://codepen.io/anon/pen/GprybL
I know, I am answering an old question, it might be helpful for someone else, for striking out a particular portion of TextView programmatically.
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("Text need to be set here", TextView.BufferType.SPANNABLE);
Spannable spannable = (Spannable) textView.getText();
spannable.setSpan(new StrikethroughSpan(), 5, 8, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
So, in this example code, 5 is starting position and 8 is ending position of text need to be stricken out, so after running this code we can get the text "need" with striked out. Hope it will helpful for someone else.
var canvasId = chart.id + '-canvas';
var canvasDownloadId = chart.id + '-download-canvas';
var canvasHtml = Ext.String.format('<canvas id="{0}" width="{1}" height="{2}"></canvas><a id="{3}"/>',
canvasId,
chart.getWidth(),
chart.getHeight(),
canvasDownloadId);
var canvasElement = reportBuilder.add({ html: canvasHtml });
var canvas = document.getElementById(canvasId);
var canvasDownload = document.getElementById(canvasDownloadId);
canvasDownload.href = chart.getImage().data;
canvasDownload.download = 'chart';
canvasDownload.click();
It's also possible to to do this without the wrapper - div#main. You can center the #page-wrap using the margin: 0 auto; method and then use the left:-n; method to position the #sidebar and adding the width of #page-wrap.
body { background: black; }
#sidebar {
position: absolute;
left: 50%;
width: 200px;
height: 400px;
background: red;
margin-left: -230px;
}
#page-wrap {
width: 60px;
background: #fff;
height: 400px;
margin: 0 auto;
}
However, the sidebar would disappear beyond the browser viewport if the window was smaller than the content.
Nick's second answer is best though, because it's also more maintainable as you don't have to adjust #sidebar if you want to resize #page-wrap.
If the above solution didn't work for you, you can use import { withRouter } from 'react-router-dom';
Using this you can export your child class as -
class MyApp extends Component{
// your code
}
export default withRouter(MyApp);
And your class with Router -
// your code
<Router>
...
<Route path="/myapp" component={MyApp} />
// or if you are sending additional fields
<Route path="/myapp" component={() =><MyApp process={...} />} />
<Router>
Set the items into display: inline
and use :after
:
.text span { display: inline }
.break-after:after { content: '\A'; white-space:pre; }
and add the class into your html spans:
<span class="medium break-after">We</span>
the "title"
attribute will be used as the text for tooltip by the browser, if you want to apply style to it consider using some plugins
Try File
> New
> Project...
> Android Project From Existing Code
.
Don't copy your project from pc into workspace, copy it elsewhere and let the eclipse copy it into workspace by menu commands above and checking copy in existing workspace
.
Or you can encapsulate the looping logic itself in a try catch e.g.
for(int i = function2(); i < 100 /*where 100 is the end or another function call to get the end*/; i = function2()){
try{
//ToDo
}
catch { continue; }
}
Or...
try{
for(int i = function2(); ; ;) {
try { i = function2(); return; }
finally { /*decide to break or not :P*/continue; } }
} catch { /*failed on first try*/ } finally{ /*afterwardz*/ }
#!/usr/bin/awk -f
BEGIN {
command = "ls -lh"
command |getline
}
Runs "ls -lh" in an awk script
I'm using Eclipse Kepler release. There is no Installation Details or About Eclipse menu item under help. For me, it was Help | Eclipse Marketplace...
I had to click on the "Installed" tab. The plug-in I wanted to remove was listed there, with an "Uninstall" option.
I didn't want to reinstall everything because I have so many SDK versions installed and my development environment is set up just right. Getting it set up again takes way too long.
What worked for me was deleting, then re-creating the Android Virtual Device, being certain to put in a value for SD Card Size (I used 200 MiB).
while the above does fix the problem temporarily, it is recurring. I just tried my application within Android Studio and saw this in the output log which I did not notice before in Eclipse:
"/Applications/Android Studio.app/sdk/tools/emulator" -avd AVD_for_Nexus_S_by_Google -netspeed full -netdelay none
WARNING: Data partition already in use. Changes will not persist!
WARNING: SD Card image already in use: /Users/[user]/.android/avd/AVD_for_Nexus_S_by_Google.avd/sdcard.img
ko:Snapshot storage already in use: /Users/[user]/.android/avd/AVD_for_Nexus_S_by_Google.avd/snapshots.img
I suspect that changes to the log are not saving to the SD Card, so when LogCat tries to access the logs, they aren't there, causing the error message. The act of deleting the AVD and re-creating it removes the files, and the next launch is a fresh launch, allowing LogCat to access the virtual SD Card.
VB has the IsNumeric
function. You could reference Microsoft.VisualBasic.dll
and use it.
First the computer looks up the destination host. If it exists in local DNS cache, it uses that information. Otherwise, DNS querying is performed until the IP address is found.
Then, your browser opens a TCP connection to the destination host and sends the request according to HTTP 1.1 (or might use HTTP 1.0, but normal browsers don't do it any more).
The server looks up the required resource (if it exists) and responds using HTTP protocol, sends the data to the client (=your browser)
The browser then uses HTML parser to re-create document structure which is later presented to you on screen. If it finds references to external resources, such as pictures, css files, javascript files, these are is delivered the same way as the HTML document itself.
I found this code works for me:
public String Translate(String word)
{
var toLanguage = "en";//English
var fromLanguage = "de";//Deutsch
var url = $"https://translate.googleapis.com/translate_a/single?client=gtx&sl={fromLanguage}&tl={toLanguage}&dt=t&q={HttpUtility.UrlEncode(word)}";
var webClient = new WebClient
{
Encoding = System.Text.Encoding.UTF8
};
var result = webClient.DownloadString(url);
try
{
result = result.Substring(4, result.IndexOf("\"", 4, StringComparison.Ordinal) - 4);
return result;
}
catch
{
return "Error";
}
}
Please note that, you should allow "system" key as well
$(element).keydown(function (e) {
var code = (e.keyCode ? e.keyCode : e.which), value;
if (isSysKey(code) || code === 8 || code === 46) {
return true;
}
if (e.shiftKey || e.altKey || e.ctrlKey) {
return ;
}
if (code >= 48 && code <= 57) {
return true;
}
if (code >= 96 && code <= 105) {
return true;
}
return false;
});
function isSysKey(code) {
if (code === 40 || code === 38 ||
code === 13 || code === 39 || code === 27 ||
code === 35 ||
code === 36 || code === 37 || code === 38 ||
code === 16 || code === 17 || code === 18 ||
code === 20 || code === 37 || code === 9 ||
(code >= 112 && code <= 123)) {
return true;
}
return false;
}
You can try this:
-ms-transform: scale(width,height); /* IE 9 */
-webkit-transform: scale(width,height); /* Safari */
transform: scale(width, height);
Example: image "grows" 1.3 times
-ms-transform: scale(1.3,1.3); /* IE 9 */
-webkit-transform: scale(1.3,1.3); /* Safari */
transform: scale(1.3,1.3);
url=”http://shahkrunalm.wordpress.com“
content=”$(curl -sLI “$url” | grep HTTP/1.1 | tail -1 | awk {‘print $2'})”
if [ ! -z $content ] && [ $content -eq 200 ]
then
echo “valid url”
else
echo “invalid url”
fi
It labels whatever input is the parameter for the for
attribute.
<input id='myInput' type='radio'>_x000D_
<label for='myInput'>My 1st Radio Label</label>_x000D_
<br>_x000D_
<input id='input2' type='radio'>_x000D_
<label for='input2'>My 2nd Radio Label</label>_x000D_
<br>_x000D_
<input id='input3' type='radio'>_x000D_
<label for='input3'>My 3rd Radio Label</label>
_x000D_
HTML DOM querySelectorAll() method seems apt here.
W3School Link given here
Syntax (As given in W3School)
document.querySelectorAll(CSS selectors)
So the answer.
document.querySelectorAll("[name^=q1_]")
Edit:
Considering FLX's suggestion adding link to MDN here
The error usually gets introduced while creation of CSV. Try using Linux for saving the CSV as a TextCSV. Libre Office in Ubuntu can enforce the encoding to be UTF-8, worked for me. I wasted a lot of time trying this on Mac OS. Linux is the key. I've tested on Ubuntu.
Good Luck
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).bind("contextmenu",function(e){
return false;
});
});
</script>
</head>
<body>
<p>Right click is disabled on this page.</p>
</body>
</html>
I'm late to the party but I encountered the same thing when I tried to get fancy and move my library and then had files being saved to a folder that was outdated:
.libloc <<- "C:/Program Files/rest_of_your_Library_FileName"
One other point to mention is that for Windows Computers, if you copy the address from Windows Explorer, you have to manually change the '\' to a '/' for the directory to be recognized.
I would like to expand the answers to whoever might be using this in a bigger project, you could accidentally attach multiple event handlers and the program would behave weirdly.
To get rid of that, I used a singleton function exposed by a factory, from which you would call inactivityTimeoutFactory.switchTimeoutOn()
and inactivityTimeoutFactory.switchTimeoutOff()
in your angular application to respectively activate and deactivate the logout due to inactivity functionality.
This way you make sure you are only running a single instance of the event handlers, no matter how many times you try to activate the timeout procedure, making it easier to use in applications where the user might login from different routes.
Here is my code:
'use strict';
angular.module('YOURMODULENAME')
.factory('inactivityTimeoutFactory', inactivityTimeoutFactory);
inactivityTimeoutFactory.$inject = ['$document', '$timeout', '$state'];
function inactivityTimeoutFactory($document, $timeout, $state) {
function InactivityTimeout () {
// singleton
if (InactivityTimeout.prototype._singletonInstance) {
return InactivityTimeout.prototype._singletonInstance;
}
InactivityTimeout.prototype._singletonInstance = this;
// Timeout timer value
const timeToLogoutMs = 15*1000*60; //15 minutes
const timeToWarnMs = 13*1000*60; //13 minutes
// variables
let warningTimer;
let timeoutTimer;
let isRunning;
function switchOn () {
if (!isRunning) {
switchEventHandlers("on");
startTimeout();
isRunning = true;
}
}
function switchOff() {
switchEventHandlers("off");
cancelTimersAndCloseMessages();
isRunning = false;
}
function resetTimeout() {
cancelTimersAndCloseMessages();
// reset timeout threads
startTimeout();
}
function cancelTimersAndCloseMessages () {
// stop any pending timeout
$timeout.cancel(timeoutTimer);
$timeout.cancel(warningTimer);
// remember to close any messages
}
function startTimeout () {
warningTimer = $timeout(processWarning, timeToWarnMs);
timeoutTimer = $timeout(processLogout, timeToLogoutMs);
}
function processWarning() {
// show warning using popup modules, toasters etc...
}
function processLogout() {
// go to logout page. The state might differ from project to project
$state.go('authentication.logout');
}
function switchEventHandlers(toNewStatus) {
const body = angular.element($document);
const trackedEventsList = [
'keydown',
'keyup',
'click',
'mousemove',
'DOMMouseScroll',
'mousewheel',
'mousedown',
'touchstart',
'touchmove',
'scroll',
'focus'
];
trackedEventsList.forEach((eventName) => {
if (toNewStatus === 'off') {
body.off(eventName, resetTimeout);
} else if (toNewStatus === 'on') {
body.on(eventName, resetTimeout);
}
});
}
// expose switch methods
this.switchOff = switchOff;
this.switchOn = switchOn;
}
return {
switchTimeoutOn () {
(new InactivityTimeout()).switchOn();
},
switchTimeoutOff () {
(new InactivityTimeout()).switchOff();
}
};
}
There are tcpdump filters for HTTP GET & HTTP POST (or for both plus message body):
Run man tcpdump | less -Ip examples
to see some examples
Here’s a tcpdump filter for HTTP GET (GET
= 0x47
, 0x45
, 0x54
, 0x20
):
sudo tcpdump -s 0 -A 'tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420'
Here’s a tcpdump filter for HTTP POST (POST
= 0x50
, 0x4f
, 0x53
, 0x54
):
sudo tcpdump -s 0 -A 'tcp dst port 80 and (tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x504f5354)'
Monitor HTTP traffic including request and response headers and message body (source):
tcpdump -A -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
tcpdump -X -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
For more information on the bit-twiddling in the TCP header see: String-Matching Capture Filter Generator (link to Sake Blok's explanation).
Try this snippet of code
private static boolean isStringInt(String s){
Scanner in=new Scanner(s);
return in.hasNextInt();
}
just replace JFrame
to JDialog
in class
public class MyDialog extends JFrame // delete JFrame and write JDialog
and then write setModal(true);
in constructor
After that you will be able to construct your Form in netbeans and the form becomes modal
Notepad++ address has changed, so many of the links above are broken. The up to date link for this question is here: https://npp-user-manual.org/docs/plugins/
Just in case the address changes again, here is what we have there today:
How to install a plugin
Install plugin manually
If the plugin you want to install is not listed in the Plugins Admin, you may still install it manually. The plugin (in the DLL form) should be placed in the plugins subfolder of the Notepad++ Install Folder, under the subfolder with the same name of plugin binary name without file extension. For example, if the plugin you want to install named myAwesomePlugin.dll, you should install it with the following path: %PROGRAMFILES(x86)%\Notepad++\plugins\myAwesomePlugin\myAwesomePlugin.dll
Once you installed the plugin, you can use (and you may configure) it via the menu “Plugins”.
SELECT *
FROM table1
WHERE CONVERT(varchar(10),columnDatetime,121) =
CONVERT(varchar(10),CONVERT('14 AUG 2008' ,smalldatetime),121)
This will convert the datatime and the string into varchars of the format "YYYY-MM-DD".
This is very ugly, but should work
POP UP WINDOWS IN APPLET
hi guys i was searching pop up windows in applet all over the internet but could not find answer for windows.
Although it is simple i am just helping you. Hope you will like it as it is in simpliest form. here's the code :
Filename: PopUpWindow.java
for java file and we need html file too.
For applet let us take its popup.html
CODE:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class PopUpWindow extends Applet{
public void init(){
Button open = new Button("open window");
add(open);
Button close = new Button("close window");
add(close);
Frame f = new Frame("pupup win");
f.setSize(200,200);
open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!f.isShowing()) {
f.setVisible(true);
}
}
});
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(f.isShowing()) {
f.setVisible(false);
}
}
});
}
}
/*
<html>
<body>
<APPLET CODE="PopUpWindow" width="" height="">
</APPLET>
</body>
</html>
*/
to run:
$javac PopUpWindow.java && appletviewer popup.html
I've solved this problem by using the search function on Docker's website where '*' is a valid search that returns 200k repositories and then I crawled each invididual page. HTML parsing allows me to extract all the image names on each page.