Anyway, I was following my workflow on a recent branch, and when I tried to merge it back to master, it all went to hell. There were tons of conflicts with things that should have not mattered. The conflicts just made no sense to me. It took me a day to sort everything out, and eventually culminated in a forced push to the remote master, since my local master has all conflicts resolved, but the remote one still wasn't happy.
In neither your partner's nor your suggested workflows should you have come across conflicts that didn't make sense. Even if you had, if you are following the suggested workflows then after resolution a 'forced' push should not be required. It suggests that you haven't actually merged the branch to which you were pushing, but have had to push a branch that wasn't a descendent of the remote tip.
I think you need to look carefully at what happened. Could someone else have (deliberately or not) rewound the remote master branch between your creation of the local branch and the point at which you attempted to merge it back into the local branch?
Compared to many other version control systems I've found that using Git involves less fighting the tool and allows you to get to work on the problems that are fundamental to your source streams. Git doesn't perform magic, so conflicting changes cause conflicts, but it should make it easy to do the write thing by its tracking of commit parentage.
I found the Chrome option to be OK but there are quite a few steps to go through to get to the font files. Once you're there, the downloading is super easy. I usually use the dev tools in Safari as there are fewer steps. Just go to the page you want, click on "Show page source" or "show page resources" in the Developer menu (both work for this) and the page resources are listed in folders on the left hand side. Click the font folder and the fonts are listed. Right click and save file. If you are downloading a lot of font files from one site it may be quicker to work your way through Chrome's pathway as the "open in tab" does download the fonts quicker. If you're taking one or two fonts from a lot of different sites, Safari will be quicker overall.
yet another way (my favorite), starting with C# 6
private readonly int MyVal = 5;
public int MyProp => MyVal;
Use its value directly:
In [79]: df[df.c > 0.5][['b', 'e']].values
Out[79]:
array([[ 0.98836259, 0.82403141],
[ 0.337358 , 0.02054435],
[ 0.29271728, 0.37813099],
[ 0.70033513, 0.69919695]])
For Windows Subsystem for Linux (WSL) you'll need
apt install libswt-gtk-4-jni
If you don't have an OpenJDK 8 you'll also need
apt install openjdk-8-jdk
Can be done with toLocaleDateString
<script>_x000D_
const date = new Date();_x000D_
const formattedDate = date.toLocaleDateString('en-GB', {_x000D_
day: '2-digit', month: 'short', year: 'numeric'_x000D_
}).replace(/ /g, '-');_x000D_
document.write(formattedDate);_x000D_
</script>
_x000D_
If you need your form to submit/commit data to a 1:M relational database, I would recommend creating an "after insert" DB trigger on table A that will insert the necessary data for table B.
<xs:element name="price" type="decimal">
<xs:attribute name="currency" type="xs:string" value="(euros|pounds|dollars)" />
</element>
This would eliminate the need for enumeration completely. You could change type to double if required.
If you only want to read the first 999,999 (non-header) rows:
read_csv(..., nrows=999999)
If you only want to read rows 1,000,000 ... 1,999,999
read_csv(..., skiprows=1000000, nrows=999999)
nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*
skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file
and for large files, you'll probably also want to use chunksize:
chunksize : int, default None Return TextFileReader object for iteration
you can use just
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version></version>
</dependency>
datetime.datetime.strptime
has problems with timezone parsing. Have a look at the dateutil
package:
>>> from dateutil import parser
>>> parser.parse("Tue May 08 15:14:45 +0800 2012")
datetime.datetime(2012, 5, 8, 15, 14, 45, tzinfo=tzoffset(None, 28800))
The pack
method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize
or setBounds
(which also sets the frame location). In general, using pack is preferable to calling setSize
, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.
From Java tutorial
You should also refer to Javadocs any time you need additional information on any Java API
embedded with closures or functions is one way. This is common in JS although not required for non-browser platforms or browser workers.
In Python it seems a bit strange, but if something really needs to be hidden than that might be the way. More to the point using the python API and keeping things that require to be hidden in the C (or other language) is probably the best way. Failing that I would go for putting the code inside a function, calling that and having it return the items you want to export.
From Stroustrup's speech at "Going Native 2012":
template<int M, int K, int S> struct Unit { // a unit in the MKS system
enum { m=M, kg=K, s=S };
};
template<typename Unit> // a magnitude with a unit
struct Value {
double val; // the magnitude
explicit Value(double d) : val(d) {} // construct a Value from a double
};
using Speed = Value<Unit<1,0,-1>>; // meters/second type
using Acceleration = Value<Unit<1,0,-2>>; // meters/second/second type
using Second = Unit<0,0,1>; // unit: sec
using Second2 = Unit<0,0,2>; // unit: second*second
constexpr Value<Second> operator"" s(long double d)
// a f-p literal suffixed by ‘s’
{
return Value<Second> (d);
}
constexpr Value<Second2> operator"" s2(long double d)
// a f-p literal suffixed by ‘s2’
{
return Value<Second2> (d);
}
Speed sp1 = 100m/9.8s; // very fast for a human
Speed sp2 = 100m/9.8s2; // error (m/s2 is acceleration)
Speed sp3 = 100/9.8s; // error (speed is m/s and 100 has no unit)
Acceleration acc = sp1/0.5s; // too fast for a human
Use org.apache.commons.io.IOUtils
InputStream inStream = new ...
OutputStream outStream = new ...
IOUtils.copy(inStream, outStream);
or copyLarge for size >2GB
You could use Jsel - https://github.com/dragonworx/jsel (for full disclosure, I am the owner of this library).
It uses a real XPath engine and is highly customizable. Runs in both Node.js and the browser.
Given your original question, you'd find the people by name with:
// include or require jsel library (npm or browser)
var dom = jsel({
"people": {
"person": [{
"name": "Peter",
"age": 43,
"sex": "male"},
{
"name": "Zara",
"age": 65,
"sex": "female"}]
}
});
var person = dom.select("//person/*[@name='Peter']");
person.age === 43; // true
If you you were always working with the same JSON schema you could create your own schema with jsel, and be able to use shorter expressions like:
dom.select("//person[@name='Peter']")
If you're in the middle of a commit (i.e. in your editor already), you can cancel it by deleting all lines above the first #
. That will abort the commit.
So you can delete all lines so that the commit message is empty, then save the file:
You'll then get a message that says Aborting commit due to empty commit message.
.
EDIT:
You can also delete all the lines and the result will be exactly the same.
To delete all lines in vim (if that is your default editor), once you're in the editor, type gg
to go to the first line, then dG
to delete all lines. Finally, write and quit the file with wq
and your commit will be aborted.
Just for convenience, very simple.
def hexlify_byteString(byteString, delim="%"):
''' very simple way to hexlify a bytestring using delimiters '''
retval = ""
for intval in byteString:
retval += ( '0123456789ABCDEF'[int(intval / 16)])
retval += ( '0123456789ABCDEF'[int(intval % 16)])
retval += delim
return( retval[:-1])
hexlify_byteString(b'Hello World!', ":")
# Out[439]: '48:65:6C:6C:6F:20:57:6F:72:6C:64:21'
my jQuery powered solution is below :)
Text Element:
<asp:TextBox ID="txtTextBox" ClientIDMode="Static" onkeypress="return EnterEvent(event);" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmitButton" ClientIDMode="Static" OnClick="btnSubmitButton_Click" runat="server" Text="Submit Form" />
Javascript behind:
<script type="text/javascript" language="javascript">
function fnCheckValue() {
var myVal = $("#txtTextBox").val();
if (myVal == "") {
alert("Blank message");
return false;
}
else {
return true;
}
}
function EnterEvent(e) {
if (e.keyCode == 13) {
if (fnCheckValue()) {
$("#btnSubmitButton").trigger("click");
} else {
return false;
}
}
}
$("#btnSubmitButton").click(function () {
return fnCheckValue();
});
</script>
library(plyr)
ldply(apply(data, 1, function(x) data.frame(
x = paste(x[2:4],sep="",collapse="-"))))
# x
#1 a-d-g
#2 b-e-h
#3 c-f-i
# and with just the vector of names you have:
ldply(apply(data, 1, function(x) data.frame(
x = paste(x[c('b','c','d')],sep="",collapse="-"))))
# or equally:
mynames <-c('b','c','d')
ldply(apply(data, 1, function(x) data.frame(
x = paste(x[mynames],sep="",collapse="-"))))
NSURL.h provided - (BOOL)checkResourceIsReachableAndReturnError:(NSError **)error
to do so
NSURL *fileURL = [NSURL fileURLWithPath:NSHomeDirectory()];
NSError * __autoreleasing error = nil;
if ([fileURL checkResourceIsReachableAndReturnError:&error]) {
NSLog(@"%@ exists", fileURL);
} else {
NSLog(@"%@ existence checking error: %@", fileURL, error);
}
Or using Swift
if let url = URL(fileURLWithPath: NSHomeDirectory()) {
do {
let result = try url.checkResourceIsReachable()
} catch {
print(error)
}
}
height
of your label to the same height
as the multiline textbox.Add the cssClass .alignTop{vertical-align: middle;}
for the label control.
<p>
<asp:Label ID="DescriptionLabel" runat="server" Text="Description: " Width="70px" Height="200px" CssClass="alignTop"></asp:Label>
<asp:Textbox id="DescriptionTextbox" runat="server" Width="400px" Height="200px" TextMode="MultiLine"></asp:Textbox>
<asp:RequiredFieldValidator id="DescriptionRequiredFieldValidator" runat="server" ForeColor="Red"
ControlToValidate="DescriptionTextbox" ErrorMessage="Description is a required field.">
</asp:RequiredFieldValidator>
Another way-too-complicated workaround, with the benefit of not having to re-install the application as the previous workaround required. This requires that you have access to the msi (or a setup.exe with the msi embedded).
If you have Visual Studio 2012 (or possibly other editions) and install the free "InstallShield LE", then you can create a new setup project using InstallShield.
One of the configuration options in the "Organize your Setup" step is called "Upgrade Paths". Open the properties for Upgrade Paths, and in the left pane right click "Upgrade Paths" and select "New Upgrade Path" ... now browse to the msi (or setup.exe containing the msi) and click "open". The upgrade code will be populated for you in the settings page in the right pane which you should now see.
When you register for a new website, often you are sent an email to activate your account. That email typically contains a link to click on. Part of that link, contains a token, the server knows about this token and can associate it with your account. The token would usually have an expiry date associated with it, so you may only have an hour to click on the link and activate your account. None of this would be possible with cookies or session variables, since its unknown what device or browser the customer is using to check emails.
You are looking to see if a single value is in an array. Use in_array
.
However note that case is important, as are any leading or trailing spaces. Use var_dump
to find out the length of the strings too, and see if they fit.
I render context path to attribute of link tag with id="contextPahtHolder" and then obtain it in JS code. For example:
<html>
<head>
<link id="contextPathHolder" data-contextPath="${pageContext.request.contextPath}"/>
<body>
<script src="main.js" type="text/javascript"></script>
</body>
</html>
main.js
var CONTEXT_PATH = $('#contextPathHolder').attr('data-contextPath');
$.get(CONTEXT_PATH + '/action_url', function() {});
If context path is empty (like in embedded servlet container istance), it will be empty string. Otherwise it contains contextPath string
Here is another method, much simple, lets say your dataframe name is daat
and column name is YEARMONTH
daat.YEARMONTH.value_counts()
The result is probably not in JSON format, so when jQuery tries to parse it as such, it fails. You can catch the error with error:
callback function.
You don't seem to need JSON in that function anyways, so you can also take out the dataType: 'json'
row.
I believe it adds them there for consistency... they're only required when you have a space or special character in the column name, but it's cleaner to just include them all the time when the IDE generates SQL.
Try this, to set the focus to the first input field:
$(this).parent().siblings('div.bottom').find("input.post").focus();
If you're looking to capture everything up to "abc":
/^(.*?)abc/
Explanation:
( )
capture the expression inside the parentheses for access using $1
, $2
, etc.
^
match start of line
.*
match anything, ?
non-greedily (match the minimum number of characters required) - [1]
[1] The reason why this is needed is that otherwise, in the following string:
whatever whatever something abc something abc
by default, regexes are greedy, meaning it will match as much as possible. Therefore /^.*abc/
would match "whatever whatever something abc something ". Adding the non-greedy quantifier ?
makes the regex only match "whatever whatever something ".
If you have multiple divs that you want aligned side by side at the right end of the parent div, set text-align: right;
on the parent div.
Full Outer join don't exist in mysql , you might need to use a combination of left and right join.
If you want to use scrollWidth to get the "REAL" CONTENT WIDTH/HEIGHT (as content can be BIGGER than the css-defined width/height-Box) the scrollWidth/Height is very UNRELIABLE as some browser seem to "MOVE" the paddingRIGHT & paddingBOTTOM if the content is to big. They then place the paddings at the RIGHT/BOTTOM of the "too broad/high content" (see picture below).
==> Therefore to get the REAL CONTENT WIDTH in some browsers you have to substract BOTH paddings from the scrollwidth and in some browsers you only have to substract the LEFT Padding.
I found a solution for this and wanted to add this as a comment, but was not allowed. So I took the picture and made it a bit clearer in the regard of the "moved paddings" and the "unreliable scrollWidth". In the BLUE AREA you find my solution on how to get the "REAL" CONTENT WIDTH!
Hope this helps to make things even clearer!
If you want a string, then the other answers are fine, but if what you're looking for is the first few letters as characters you can access them as a list:
your_text.chars.take(30)
You can add elements of a list
to a set
like this:
>>> foo = set(range(0, 4))
>>> foo
set([0, 1, 2, 3])
>>> foo.update(range(2, 6))
>>> foo
set([0, 1, 2, 3, 4, 5])
Simple Steps
I assume bash is running on a vt100-compatible terminal in which the user did not explicitly turn off the support for formatting.
First, turn on support for special characters in echo
, using -e
option. Later, use ansi escape sequence ESC[1m
, like:
echo -e "\033[1mSome Text"
More on ansi escape sequences for example here: ascii-table.com/ansi-escape-sequences-vt-100.php
Use this to list Grantee too and remove (PG_monitor and Public) for Postgres PaaS Azure.
SELECT grantee,table_catalog, table_schema, table_name, privilege_type
FROM information_schema.table_privileges
WHERE grantee not in ('pg_monitor','PUBLIC');
The window['variableName'] method ONLY works if the variable is defined in the global scope. The correct answer is "Refactor". If you can provide an "Object" context then a possible general solution exists, but there are some variables which no global function could resolve based on the scope of the variable.
(function(){
var findMe = 'no way';
})();
This work for me:
#If VBA7 And Win64 Then
Private Declare PtrSafe Function ShellExecuteA Lib "Shell32.dll" _
(ByVal hwnd As Long, _
ByVal lpOperation As String, _
ByVal lpFile As String, _
ByVal lpParameters As String, _
ByVal lpDirectory As String, _
ByVal nShowCmd As Long) As Long
#Else
Private Declare Function ShellExecuteA Lib "Shell32.dll" _
(ByVal hwnd As Long, _
ByVal lpOperation As String, _
ByVal lpFile As String, _
ByVal lpParameters As String, _
ByVal lpDirectory As String, _
ByVal nShowCmd As Long) As Long
#End If
Thanks Jon49 for insight.
An alternative and simple to use solution is to adjust the coordinates of the suptitle text in the figure using the y argument in the call of suptitle (see the docs):
import numpy as np
import matplotlib.pyplot as plt
f = np.random.random(100)
g = np.random.random(100)
fig = plt.figure()
fig.suptitle('Long Suptitle', y=1.05, fontsize=24)
plt.subplot(121)
plt.plot(f)
plt.title('Very Long Title 1', fontsize=20)
plt.subplot(122)
plt.plot(g)
plt.title('Very Long Title 2', fontsize=20)
plt.show()
If you don't care about loading the file into memory, as of Go 1.16, you can use the os.ReadFile
and bytes.Count
functions.
package main
import (
"log"
"os"
"bytes"
)
func main() {
data, err := os.ReadFile("input.txt")
if err != nil {
log.Fatal(err)
}
n := bytes.Count(data, []byte{'\n'})
fmt.Printf("input.txt has %d lines\n", n)
}
Yep, both and
and or
operators short-circuit -- see the docs.
Sorry to dig up an old question but in case someone stumbles onto this thread and wants a quicker solution.
Bulk inserting a unknown width file with \n row terminators into a temp table that is created outside of the EXEC statement.
DECLARE @SQL VARCHAR(8000)
IF OBJECT_ID('TempDB..#BulkInsert') IS NOT NULL
BEGIN
DROP TABLE #BulkInsert
END
CREATE TABLE #BulkInsert
(
Line VARCHAR(MAX)
)
SET @SQL = 'BULK INSERT #BulkInser FROM ''##FILEPATH##'' WITH (ROWTERMINATOR = ''\n'')'
EXEC (@SQL)
SELECT * FROM #BulkInsert
Further support that dynamic SQL within an EXEC statement has access to temp tables outside of the EXEC statement. http://sqlfiddle.com/#!3/d41d8/19343
DECLARE @SQL VARCHAR(8000)
IF OBJECT_ID('TempDB..#BulkInsert') IS NOT NULL
BEGIN
DROP TABLE #BulkInsert
END
CREATE TABLE #BulkInsert
(
Line VARCHAR(MAX)
)
INSERT INTO #BulkInsert
(
Line
)
SELECT 1
UNION SELECT 2
UNION SELECT 3
SET @SQL = 'SELECT * FROM #BulkInsert'
EXEC (@SQL)
Further support, written for MSSQL2000 http://technet.microsoft.com/en-us/library/aa175921(v=sql.80).aspx
Example at the bottom of the link
DECLARE @cmd VARCHAR(1000), @ExecError INT
CREATE TABLE #ErrFile (ExecError INT)
SET @cmd = 'EXEC GetTableCount ' +
'''pubs.dbo.authors''' +
'INSERT #ErrFile VALUES(@@ERROR)'
EXEC(@cmd)
SET @ExecError = (SELECT * FROM #ErrFile)
SELECT @ExecError AS '@@ERROR'
It should work the way you intended.
$array = array('value-0', 'value-1', 'value-2', 'value-3', 'value-4', 'value-5' /* … */);
$key = 4;
$value = $array[$key];
echo $value; // value-4
But maybe there is no element with the key 4
. If you want to get the fiveth item no matter what key it has, you can use array_slice
:
$value = array_slice($array, 4, 1);
You're multipling your "1 + 0.01" times the growthRate list, not the item in the list you're iterating through. I've renamed i
to rate
and using that instead. See the updated code below:
def nestEgVariable(salary, save, growthRates):
SavingsRecord = []
fund = 0
depositPerYear = salary * save * 0.01
# V-- rate is a clearer name than i here, since you're iterating through the rates contained in the growthRates list
for rate in growthRates:
# V-- Use the `rate` item in the growthRate list you're iterating through rather than multiplying by the `growthRate` list itself.
fund = fund * (1 + 0.01 * rate) + depositPerYear
SavingsRecord += [fund,]
return SavingsRecord
print nestEgVariable(10000,10,[3,4,5,0,3])
Arrays' constructors are different. Here are some ways to make an empty string array:
var arr = new string[0];
var arr = new string[]{};
var arr = Enumerable.Empty<string>().ToArray()
(sorry, on mobile)
Since version 50 (if I remember correctly), the "Disable cache" option was removed from the Devtool Settings. Go to the "Network" tab and there's the "Disable cache" option.
Redis supports 5 data types. You need to know what type of value that a key maps to, as for each data type, the command to retrieve it is different.
Here are the commands to retrieve key value:
<key>
<key>
<key> <start> <end>
<key>
<key> <min> <max>
Use the TYPE
command to check the type of value a key is mapping to:
<key>
Try to do...
DELIMITER $$
CREATE TRIGGER aumentarsalario
BEFORE INSERT
ON empregados
FOR EACH ROW
BEGIN
if (NEW.SALARIO < 900) THEN
set NEW.SALARIO = NEW.SALARIO + (NEW.SALARIO * 0.1);
END IF;
END $$
DELIMITER ;
The common way is to make the private method protected or package-private and to put the unit test for this method in the same package as the class under test.
Guava has a @VisibleForTesting
annotation, but it's only for documentation purposes.
This works for me:
CSS
.form-group.required.control-label:before{
content: "*";
color: red;
}
OR
.form-group.required.control-label:after{
content: "*";
color: red;
}
Basic HTML
<div class="form-group required control-label">
<input class="form-control" />
</div>
NUMBER (precision, scale)
If a precision is not specified, the column stores values as given. If no scale is specified, the scale is zero.
A lot more info at:
http://download.oracle.com/docs/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT1832
With this command:
dpkg -s mysql-server | grep Status
This solved my problem (sorry for my bad English):
open cmd as administrator and run command (Without the square brackets):
netsh http add urlacl url=http://[ip adress]:[port]/ user=everyone
in documents/iisexpress/config/applicationhost.config
and in your root project folder in (hidden) folder: .vs/config/applicationhost.config
you need add row to "site" tag:
<binding protocol="http" bindingInformation="*:8080:192.xxx.xxx.xxx" />
open "internet information services (iis) manager"
(to find it: in search in taskbar write "Turn Window features on or off" and open result and then check the checkbox "internet information service" and install that):
open "Windows Firewall With Advanced Security",
done.
Delete the hidden .git
folder (that you can locate within your project folder) and again start the process of creating a git repository using git init
command.
Here is a working sample.
<html>_x000D_
<script type="text/javascript">_x000D_
var canvas, ctx, flag = false,_x000D_
prevX = 0,_x000D_
currX = 0,_x000D_
prevY = 0,_x000D_
currY = 0,_x000D_
dot_flag = false;_x000D_
_x000D_
var x = "black",_x000D_
y = 2;_x000D_
_x000D_
function init() {_x000D_
canvas = document.getElementById('can');_x000D_
ctx = canvas.getContext("2d");_x000D_
w = canvas.width;_x000D_
h = canvas.height;_x000D_
_x000D_
canvas.addEventListener("mousemove", function (e) {_x000D_
findxy('move', e)_x000D_
}, false);_x000D_
canvas.addEventListener("mousedown", function (e) {_x000D_
findxy('down', e)_x000D_
}, false);_x000D_
canvas.addEventListener("mouseup", function (e) {_x000D_
findxy('up', e)_x000D_
}, false);_x000D_
canvas.addEventListener("mouseout", function (e) {_x000D_
findxy('out', e)_x000D_
}, false);_x000D_
}_x000D_
_x000D_
function color(obj) {_x000D_
switch (obj.id) {_x000D_
case "green":_x000D_
x = "green";_x000D_
break;_x000D_
case "blue":_x000D_
x = "blue";_x000D_
break;_x000D_
case "red":_x000D_
x = "red";_x000D_
break;_x000D_
case "yellow":_x000D_
x = "yellow";_x000D_
break;_x000D_
case "orange":_x000D_
x = "orange";_x000D_
break;_x000D_
case "black":_x000D_
x = "black";_x000D_
break;_x000D_
case "white":_x000D_
x = "white";_x000D_
break;_x000D_
}_x000D_
if (x == "white") y = 14;_x000D_
else y = 2;_x000D_
_x000D_
}_x000D_
_x000D_
function draw() {_x000D_
ctx.beginPath();_x000D_
ctx.moveTo(prevX, prevY);_x000D_
ctx.lineTo(currX, currY);_x000D_
ctx.strokeStyle = x;_x000D_
ctx.lineWidth = y;_x000D_
ctx.stroke();_x000D_
ctx.closePath();_x000D_
}_x000D_
_x000D_
function erase() {_x000D_
var m = confirm("Want to clear");_x000D_
if (m) {_x000D_
ctx.clearRect(0, 0, w, h);_x000D_
document.getElementById("canvasimg").style.display = "none";_x000D_
}_x000D_
}_x000D_
_x000D_
function save() {_x000D_
document.getElementById("canvasimg").style.border = "2px solid";_x000D_
var dataURL = canvas.toDataURL();_x000D_
document.getElementById("canvasimg").src = dataURL;_x000D_
document.getElementById("canvasimg").style.display = "inline";_x000D_
}_x000D_
_x000D_
function findxy(res, e) {_x000D_
if (res == 'down') {_x000D_
prevX = currX;_x000D_
prevY = currY;_x000D_
currX = e.clientX - canvas.offsetLeft;_x000D_
currY = e.clientY - canvas.offsetTop;_x000D_
_x000D_
flag = true;_x000D_
dot_flag = true;_x000D_
if (dot_flag) {_x000D_
ctx.beginPath();_x000D_
ctx.fillStyle = x;_x000D_
ctx.fillRect(currX, currY, 2, 2);_x000D_
ctx.closePath();_x000D_
dot_flag = false;_x000D_
}_x000D_
}_x000D_
if (res == 'up' || res == "out") {_x000D_
flag = false;_x000D_
}_x000D_
if (res == 'move') {_x000D_
if (flag) {_x000D_
prevX = currX;_x000D_
prevY = currY;_x000D_
currX = e.clientX - canvas.offsetLeft;_x000D_
currY = e.clientY - canvas.offsetTop;_x000D_
draw();_x000D_
}_x000D_
}_x000D_
}_x000D_
</script>_x000D_
<body onload="init()">_x000D_
<canvas id="can" width="400" height="400" style="position:absolute;top:10%;left:10%;border:2px solid;"></canvas>_x000D_
<div style="position:absolute;top:12%;left:43%;">Choose Color</div>_x000D_
<div style="position:absolute;top:15%;left:45%;width:10px;height:10px;background:green;" id="green" onclick="color(this)"></div>_x000D_
<div style="position:absolute;top:15%;left:46%;width:10px;height:10px;background:blue;" id="blue" onclick="color(this)"></div>_x000D_
<div style="position:absolute;top:15%;left:47%;width:10px;height:10px;background:red;" id="red" onclick="color(this)"></div>_x000D_
<div style="position:absolute;top:17%;left:45%;width:10px;height:10px;background:yellow;" id="yellow" onclick="color(this)"></div>_x000D_
<div style="position:absolute;top:17%;left:46%;width:10px;height:10px;background:orange;" id="orange" onclick="color(this)"></div>_x000D_
<div style="position:absolute;top:17%;left:47%;width:10px;height:10px;background:black;" id="black" onclick="color(this)"></div>_x000D_
<div style="position:absolute;top:20%;left:43%;">Eraser</div>_x000D_
<div style="position:absolute;top:22%;left:45%;width:15px;height:15px;background:white;border:2px solid;" id="white" onclick="color(this)"></div>_x000D_
<img id="canvasimg" style="position:absolute;top:10%;left:52%;" style="display:none;">_x000D_
<input type="button" value="save" id="btn" size="30" onclick="save()" style="position:absolute;top:55%;left:10%;">_x000D_
<input type="button" value="clear" id="clr" size="23" onclick="erase()" style="position:absolute;top:55%;left:15%;">_x000D_
</body>_x000D_
</html>
_x000D_
What i do is to prepare a 512x512 PNG, the Alpha Channel is good for rounded corners or drop shadows, then I upload it to this site http://convertico.com/, and for free then it returns me a 6 sizes .ico file with 256x256, 128x128, 64x64, 48x48, 32x32 and 16x16 sizes.
To expand on the "use JAXB" comments above,
In Windows
"%java_home%\bin\xjc" -p [your namespace] [xsd_file].xsd
e.g.,
"%java_home%\bin\xjc" -p com.mycompany.quickbooks.obj quickbooks.xsd
Wait a bit, and if you had a well-formed XSD file, you will get some well-formed Java classes
Simplified way of doing this based on the accepted answer.
In my case I needed to check if current date (Today) is pithing the range of two other dates so used newDate() instead of hardcoded values but you can get the point how you can use hardcoded dates.
var currentDate = new Date().toJSON().slice(0,10);
var from = new Date('2020/01/01');
var to = new Date('2020/01/31');
var check = new Date(currentDate);
console.log(check > from && check < to);
I am posting a complete example which I finally got working. Here I am reading in a file rooms/rooms.txt
from a script rooms/rooms.js
var fs = require('fs');
var path = require('path');
var readStream = fs.createReadStream(path.join(__dirname, '../rooms') + '/rooms.txt', 'utf8');
let data = ''
readStream.on('data', function(chunk) {
data += chunk;
}).on('end', function() {
console.log(data);
});
this one is 42 lines long, fits in 120 characters horizontally, and looks good. Is it fast? Well - it's fast enough and it's approximately the same as all other JS implementations.
I just wanted something that doesn't look ugly in my helpers.js file and doesn't slow down my SublimeText with 20-mile long minified one-liners.
So here's my favourite md5.
// A formatted version of a popular md5 implementation.
// Original copyright (c) Paul Johnston & Greg Holt.
// The function itself is now 42 lines long.
function md5(inputString) {
var hc="0123456789abcdef";
function rh(n) {var j,s="";for(j=0;j<=3;j++) s+=hc.charAt((n>>(j*8+4))&0x0F)+hc.charAt((n>>(j*8))&0x0F);return s;}
function ad(x,y) {var l=(x&0xFFFF)+(y&0xFFFF);var m=(x>>16)+(y>>16)+(l>>16);return (m<<16)|(l&0xFFFF);}
function rl(n,c) {return (n<<c)|(n>>>(32-c));}
function cm(q,a,b,x,s,t) {return ad(rl(ad(ad(a,q),ad(x,t)),s),b);}
function ff(a,b,c,d,x,s,t) {return cm((b&c)|((~b)&d),a,b,x,s,t);}
function gg(a,b,c,d,x,s,t) {return cm((b&d)|(c&(~d)),a,b,x,s,t);}
function hh(a,b,c,d,x,s,t) {return cm(b^c^d,a,b,x,s,t);}
function ii(a,b,c,d,x,s,t) {return cm(c^(b|(~d)),a,b,x,s,t);}
function sb(x) {
var i;var nblk=((x.length+8)>>6)+1;var blks=new Array(nblk*16);for(i=0;i<nblk*16;i++) blks[i]=0;
for(i=0;i<x.length;i++) blks[i>>2]|=x.charCodeAt(i)<<((i%4)*8);
blks[i>>2]|=0x80<<((i%4)*8);blks[nblk*16-2]=x.length*8;return blks;
}
var i,x=sb(inputString),a=1732584193,b=-271733879,c=-1732584194,d=271733878,olda,oldb,oldc,oldd;
for(i=0;i<x.length;i+=16) {olda=a;oldb=b;oldc=c;oldd=d;
a=ff(a,b,c,d,x[i+ 0], 7, -680876936);d=ff(d,a,b,c,x[i+ 1],12, -389564586);c=ff(c,d,a,b,x[i+ 2],17, 606105819);
b=ff(b,c,d,a,x[i+ 3],22,-1044525330);a=ff(a,b,c,d,x[i+ 4], 7, -176418897);d=ff(d,a,b,c,x[i+ 5],12, 1200080426);
c=ff(c,d,a,b,x[i+ 6],17,-1473231341);b=ff(b,c,d,a,x[i+ 7],22, -45705983);a=ff(a,b,c,d,x[i+ 8], 7, 1770035416);
d=ff(d,a,b,c,x[i+ 9],12,-1958414417);c=ff(c,d,a,b,x[i+10],17, -42063);b=ff(b,c,d,a,x[i+11],22,-1990404162);
a=ff(a,b,c,d,x[i+12], 7, 1804603682);d=ff(d,a,b,c,x[i+13],12, -40341101);c=ff(c,d,a,b,x[i+14],17,-1502002290);
b=ff(b,c,d,a,x[i+15],22, 1236535329);a=gg(a,b,c,d,x[i+ 1], 5, -165796510);d=gg(d,a,b,c,x[i+ 6], 9,-1069501632);
c=gg(c,d,a,b,x[i+11],14, 643717713);b=gg(b,c,d,a,x[i+ 0],20, -373897302);a=gg(a,b,c,d,x[i+ 5], 5, -701558691);
d=gg(d,a,b,c,x[i+10], 9, 38016083);c=gg(c,d,a,b,x[i+15],14, -660478335);b=gg(b,c,d,a,x[i+ 4],20, -405537848);
a=gg(a,b,c,d,x[i+ 9], 5, 568446438);d=gg(d,a,b,c,x[i+14], 9,-1019803690);c=gg(c,d,a,b,x[i+ 3],14, -187363961);
b=gg(b,c,d,a,x[i+ 8],20, 1163531501);a=gg(a,b,c,d,x[i+13], 5,-1444681467);d=gg(d,a,b,c,x[i+ 2], 9, -51403784);
c=gg(c,d,a,b,x[i+ 7],14, 1735328473);b=gg(b,c,d,a,x[i+12],20,-1926607734);a=hh(a,b,c,d,x[i+ 5], 4, -378558);
d=hh(d,a,b,c,x[i+ 8],11,-2022574463);c=hh(c,d,a,b,x[i+11],16, 1839030562);b=hh(b,c,d,a,x[i+14],23, -35309556);
a=hh(a,b,c,d,x[i+ 1], 4,-1530992060);d=hh(d,a,b,c,x[i+ 4],11, 1272893353);c=hh(c,d,a,b,x[i+ 7],16, -155497632);
b=hh(b,c,d,a,x[i+10],23,-1094730640);a=hh(a,b,c,d,x[i+13], 4, 681279174);d=hh(d,a,b,c,x[i+ 0],11, -358537222);
c=hh(c,d,a,b,x[i+ 3],16, -722521979);b=hh(b,c,d,a,x[i+ 6],23, 76029189);a=hh(a,b,c,d,x[i+ 9], 4, -640364487);
d=hh(d,a,b,c,x[i+12],11, -421815835);c=hh(c,d,a,b,x[i+15],16, 530742520);b=hh(b,c,d,a,x[i+ 2],23, -995338651);
a=ii(a,b,c,d,x[i+ 0], 6, -198630844);d=ii(d,a,b,c,x[i+ 7],10, 1126891415);c=ii(c,d,a,b,x[i+14],15,-1416354905);
b=ii(b,c,d,a,x[i+ 5],21, -57434055);a=ii(a,b,c,d,x[i+12], 6, 1700485571);d=ii(d,a,b,c,x[i+ 3],10,-1894986606);
c=ii(c,d,a,b,x[i+10],15, -1051523);b=ii(b,c,d,a,x[i+ 1],21,-2054922799);a=ii(a,b,c,d,x[i+ 8], 6, 1873313359);
d=ii(d,a,b,c,x[i+15],10, -30611744);c=ii(c,d,a,b,x[i+ 6],15,-1560198380);b=ii(b,c,d,a,x[i+13],21, 1309151649);
a=ii(a,b,c,d,x[i+ 4], 6, -145523070);d=ii(d,a,b,c,x[i+11],10,-1120210379);c=ii(c,d,a,b,x[i+ 2],15, 718787259);
b=ii(b,c,d,a,x[i+ 9],21, -343485551);a=ad(a,olda);b=ad(b,oldb);c=ad(c,oldc);d=ad(d,oldd);
}
return rh(a)+rh(b)+rh(c)+rh(d);
}
But really, I posted it merely out of aesthetic considerations. Also, with the comments it's exactly 4000 bytes. Please don't ask why. I can't come up with a proper explanation for my OCD/rebel behaviour. Also, thank you Paul Johnston, thank you Greg Holt. (Side note: you guys omitted a few var keywords so I took the liberty of adding them.)
Firstly, it is not related to Angular versions>2. Just import following in your app.module.ts file will fix the problems.
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
Then add FormsModule and ReactiveFormsModule in to your imports array.
imports: [
FormsModule,
ReactiveFormsModule
],
Note : You can also import ReactiveFormsModule
to specific module instead to app.module.ts
A straight forward way would be :
soup = BeautifulSoup(sdata)
for each_div in soup.findAll('div',{'class':'stylelist'}):
print each_div
Make sure you take of the casing of findAll, its not findall
<?php _x000D_
_x000D_
$terms = get_terms( array(_x000D_
'taxonomy' => 'product_cat',_x000D_
'hide_empty' => false,_x000D_
) ); // Get Terms_x000D_
_x000D_
foreach ($terms as $key => $value) _x000D_
{_x000D_
$metaterms = get_term_meta($value->term_id);_x000D_
$thumbnail_id = get_woocommerce_term_meta($value->term_id, 'thumbnail_id', true );_x000D_
$image = wp_get_attachment_url( $thumbnail_id );_x000D_
echo '<img src="'.$image.'" alt="" />';_x000D_
} // Get Images from woocommerce term meta_x000D_
_x000D_
?>
_x000D_
I find the answer. 1/First put in the presets, i have this example "Output format MPEG2 DVD HQ"
-vcodec mpeg2video -vstats_file MFRfile.txt -r 29.97 -s 352x480 -aspect 4:3 -b 4000k -mbd rd -trellis -mv0 -cmp 2 -subcmp 2 -acodec mp2 -ab 192k -ar 48000 -ac 2
If you want a report includes the commands -vstats_file MFRfile.txt into the presets like the example. this can make a report which it's ubicadet in the folder source of your file Source. you can put any name if you want , i solved my problem "i write many times in this forum" reading a complete .docx about mpeg properties. finally i can do my progress bar reading this txt file generated.
Regards.
According to @Data description you can use:
All generated getters and setters will be public. To override the access level, annotate the field or class with an explicit @Setter and/or @Getter annotation. You can also use this annotation (by combining it with AccessLevel.NONE) to suppress generating a getter and/or setter altogether.
You need to make sure and have the following:
#include <windows.h>
and not this:
#include "windows.h"
If that's not the problem, then check RichieHindle's response.
Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.
<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
<li class = "ui-divider">
{{ meter.DESCRIPTION }}
{{ htmlgeneration() }}
</li>
</ul>
They're also useful when you need several "constructors" with the same parameter type but with different behavior.
Those reference pretty much answered your question. Simply put, vectors' lengths are dynamic while arrays have a fixed size. when using an array, you specify its size upon declaration:
int myArray[100];
myArray[0]=1;
myArray[1]=2;
myArray[2]=3;
for vectors, you just declare it and add elements
vector<int> myVector;
myVector.push_back(1);
myVector.push_back(2);
myVector.push_back(3);
...
at times you wont know the number of elements needed so a vector would be ideal for such a situation.
Follow instructions (steps 1 to 3 don't needed in windows):
Find mysql config to edit:
/etc/mysql/my.cnf (Mysql 5.5)
/etc/mysql/conf.d/mysql.cnf (Mysql 5.6+)
Find bind-address=127.0.0.1
in config file change bind-address=0.0.0.0
(you can set bind address to one of your interface ips or like me use 0.0.0.0)
Restart mysql service run on console:
service restart mysql
Create a user with a safe password for remote connection. To do this run following command in mysql (if you are linux user to reach mysql console run mysql
and if you set password for root run mysql -p
):
GRANT ALL PRIVILEGES
ON *.* TO 'remote'@'%'
IDENTIFIED BY 'safe_password'
WITH GRANT OPTION;`
Now you should have a user with name of user
and password of safe_password
with capability of remote connect.
Use insert
if you want to insert a new element. insert
will not
overwrite an existing element, and you can verify that there was no
previously exising element:
if ( !myMap.insert( std::make_pair( key, value ) ).second ) {
// Element already present...
}
Use []
if you want to overwrite a possibly existing element:
myMap[ key ] = value;
assert( myMap.find( key )->second == value ); // post-condition
This form will overwrite any existing entry.
To get a scrollbar for an ItemsControl
, you can host it in a ScrollViewer
like this:
<ScrollViewer VerticalScrollBarVisibility="Auto">
<ItemsControl>
<uc:UcSpeler />
<uc:UcSpeler />
<uc:UcSpeler />
<uc:UcSpeler />
<uc:UcSpeler />
</ItemsControl>
</ScrollViewer>
Modify the_script.php like this.
<script>
the_function() {
alert("You win");
}
</script>
Regular solution, that does not work always:
npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli
Other more drastic solution:
Angular CLI
globallynpm uninstall -g @angular/cli
Node.js
& npm
with uninstallerNode.js
& npm
C:\Users\<user>\AppData\Roaming\npm
and C:\Users\<user>\AppData\Roaming\npm-cache
ng version
npm -v
node -v
Node.js
& npm
with installer: https://nodejs.org/en/download/ Angular CLI
npm install -g @angular/cli
ng version
Don't use MD5
as it is insecure. I would recommend using SHA
or bcrypt
with a salt
:
SHA256('".$password."')
target="_blank" is enough to open in a new tab, when you are using react-router
eg:
<Link to={
/admin/posts/error-post-list/${this.props.errorDate}}
target="_blank"> View Details </Link>
The iframe element.
<iframe src="name.html"></iframe>
But content that you way to have appear on multiple pages is better handled using templates.
No need to update gradle for making release application in Android studio.If you were eclipse user then it will be so easy for you. If you are new then follow the steps
1: Go to the "Build" at the toolbar section. 2: Choose "Generate Signed APK..." option.
3:fill opened form and go next 4 :if you already have .keystore or .jks then choose that file enter your password and alias name and respective password. 5: Or don't have .keystore or .jks file then click on Create new... button as shown on pic 1 then fill the form.
Above process was to make build manually. If You want android studio to automatically Signing Your App
In Android Studio, you can configure your project to sign your release APK automatically during the build process:
On the project browser, right click on your app and select Open Module Settings. On the Project Structure window, select your app's module under Modules. Click on the Signing tab. Select your keystore file, enter a name for this signing configuration (as you may create more than one), and enter the required information. Figure 4. Create a signing configuration in Android Studio.
Click on the Build Types tab. Select the release build. Under Signing Config, select the signing configuration you just created. Figure 5. Select a signing configuration in Android Studio.
4:Most Important thing that make debuggable=false at gradle.
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard- android.txt'), 'proguard-rules.txt'
debuggable false
jniDebuggable false
renderscriptDebuggable false
zipAlignEnabled true
}
}
visit for more in info developer.android.com
A bit late but may also help to someone who looks for answers...
Between rows/row_number example - recursive query that may be used in any SQL:
WITH data(row_num, some_val) AS
(
SELECT 1 row_num, 1 some_val FROM any_table --dual in Oracle
UNION ALL
SELECT row_num+1, some_val+row_num FROM data WHERE row_num < 20 -- any number
)
SELECT * FROM data
WHERE row_num BETWEEN 5 AND 10
/
ROW_NUM SOME_VAL
-------------------
5 11
6 16
7 22
8 29
9 37
10 46
Based upon an answer of a similar question here: https://stackoverflow.com/a/22695523/1412268
Take a look at Guzzle
$client = new GuzzleHttp\Client();
$res = $client->get('https://api.github.com/user', ['auth' => ['user', 'pass']]);
echo $res->getStatusCode(); // 200
echo $res->getBody(); // { "type": "User", ....
Okay I got help and figured it out. Also I put in a nice little alert system just in case the phone number is not valid. My issue was I was calling it right but the number had spaces and unwanted characters such as ("123 456-7890"). UIApplication only works or accepts if your number is ("1234567890"). So you basically remove the space and invalid characters by making a new variable to pull only the numbers. Then calls those numbers with the UIApplication.
func callSellerPressed (sender: UIButton!){
var newPhone = ""
for (var i = 0; i < countElements(busPhone); i++){
var current:Int = i
switch (busPhone[i]){
case "0","1","2","3","4","5","6","7","8","9" : newPhone = newPhone + String(busPhone[i])
default : println("Removed invalid character.")
}
}
if (busPhone.utf16Count > 1){
UIApplication.sharedApplication().openURL(NSURL(string: "tel://" + newPhone)!)
}
else{
let alert = UIAlertView()
alert.title = "Sorry!"
alert.message = "Phone number is not available for this business"
alert.addButtonWithTitle("Ok")
alert.show()
}
}
def Partition(A,p,q):
i=p
x=A[i]
for j in range(p+1,q+1):
if A[j]<=x:
i=i+1
tmp=A[j]
A[j]=A[i]
A[i]=tmp
l=A[p]
A[p]=A[i]
A[i]=l
return i
def quickSort(A,p,q):
if p<q:
r=Partition(A,p,q)
quickSort(A,p,r-1)
quickSort(A,r+1,q)
return A
another solution using dplyr is:
df <- ## your data ##
df <- df %>%
mutate(Den = ifelse(any(is.na(Den)) | any(Den != 1), 0, 1))
git reset --hard 4a155e5
Will move the HEAD back to where you want to be. There may be other references ahead of that time that you would need to remove if you don't want anything to point to the history you just deleted.
The preceding 0 is used to indicate a number in base 2, 8, or 16.
In my opinion, 0x was chosen to indicate hex because 'x' sounds like hex.
Just my opinion, but I think it makes sense.
Good Day!
You want to read raw lines to avoid problems with backslashes in the input (use -r
):
while read -r line; do
printf "<%s>\n" "$line"
done < file.txt
This will keep whitespace within the line, but removes leading and trailing whitespace. To keep those as well, set the IFS empty, as in
while IFS= read -r line; do
printf "%s\n" "$line"
done < file.txt
This now is an equivalent of cat < file.txt
as long as file.txt
ends with a newline.
Note that you must double quote "$line"
in order to keep word splitting from splitting the line into separate words--thus losing multiple whitespace sequences.
spans default to inline style, which you can't specify the width of.
display: inline-block;
would be a good way, except IE doesn't support it
you can, however, hack a multiple browser solution
For me, update SDK doesn't help. I solve this problem by unchecking the emulator option "Use detected ADB location". Give it a try.
Easiest and java way of doing is : implement serializable in your pojo/model class
Recommended for Android for performance view: make model parcelable
You could use the library lxml (Note top level link is now spam) , which is a superset of ElementTree. Its tostring() method includes a parameter pretty_print - for example:
>>> print(etree.tostring(root, pretty_print=True))
<root>
<child1/>
<child2/>
<child3/>
</root>
Just Close the opened file where you are going to write.
First there is an elevator class. It has a direction (up, down, stand, maintenance), a current floor and a list of floor requests sorted in the direction. It receives request from this elevator.
Then there is a bank. It contains the elevators and receives the requests from the floors. These are scheduled to all active elevators (not in maintenance).
The scheduling will be like:
Each elevator has a set of states.
There are additional signals:
EDIT: Some elevators don't start at bottom/first_floor esp. in case of skyscrapers.
min_floor & max_floor are two additional attributes for Elevator.
Try this Function :
public int indexOfArray(String input){
for(int i=0;i<TYPES,length();i++)
{
if(TYPES[i].equals(input))
{
return i ;
}
}
return -1 // if the text not found the function return -1
}
Try this, you can parse nested JSON
public static String getJsonValue(String jsonReq, String key) {
JSONObject json = new JSONObject(jsonReq);
boolean exists = json.has(key);
Iterator<?> keys;
String nextKeys;
String val = "";
if (!exists) {
keys = json.keys();
while (keys.hasNext()) {
nextKeys = (String) keys.next();
try {
if (json.get(nextKeys) instanceof JSONObject) {
return getJsonValue(json.getJSONObject(nextKeys).toString(), key);
} else if (json.get(nextKeys) instanceof JSONArray) {
JSONArray jsonArray = json.getJSONArray(nextKeys);
int i = 0;
if (i < jsonArray.length()) do {
String jsonArrayString = jsonArray.get(i).toString();
JSONObject innerJson = new JSONObject(jsonArrayString);
return getJsonValue(innerJson.toString(),key);
} while (i < jsonArray.length());
}
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
val = json.get(key).toString();
}
return val;
}
if you have just two parameters you can do this:
$.getJSON('/url-you-are-posting-to',data,function(result){
//do something useful with returned result//
result.variable-in-result;
});
Put this at the end of your app module build.gradle:
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
def requested = details.requested
if (requested.group == 'com.android.support') {
if (!requested.name.startsWith("multidex")) {
details.useVersion '25.3.0'
}
}
}
}
Credit to Eugen Pechanec
plotpath<- file.path(path, "PLOT_name",paste("plot_",file,".png",sep=""))
png(filename=plotpath)
plot(x,y, main= file)
dev.off()
static synchronized
means holding lock on the the class's Class
object
where as
synchronized
means holding lock on that class's object itself. That means, if you are accessing a non-static synchronized method in a thread (of execution) you still can access a static synchronized method using another thread.
So, accessing two same kind of methods(either two static or two non-static methods) at any point of time by more than a thread is not possible.
Along with the many other reasons mentioned already, you could also point outh that hard-coding
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
is brittle because it presumes the location of script.py -- it will only work if script.py is located in Project/package. It will break if a user decides to move/copy/symlink script.py (almost) anywhere else.
Old question but I use this quite frequently (for version 3.8). It's a bit of syntactic salt, but it has the advantage over the top answer in that you could retrieve a list of results (if there are multiple) by simply removing the [0]
and it still defaults to None
if nothing is found. For any other condition, simply change the x.value==value
to what ever you're looking for.
_[0] if (_:=[x for x in test_list if x.value==value]) else None
If you are using jQuery:
$('#sel').val('bike');
Since it's a NodeList
, not an Array
, you shouldn't really be using brackets or casting to Array
. The property way to get the first node is:
document.getElementsByName(id).item(0)
You can just cast that:
var script = <HTMLScriptElement> document.getElementsByName(id).item(0)
Or, extend NodeList
:
interface HTMLScriptElementNodeList extends NodeList
{
item(index: number): HTMLScriptElement;
}
var scripts = <HTMLScriptElementNodeList> document.getElementsByName('script'),
script = scripts.item(0);
Life span of java Thread is over after completion of run()
method. Same thread can't be started again.
Looper transforms normal Thread
into a message loop. Key methods of Looper
are :
void prepare ()
Initialize the current thread as a looper. This gives you a chance to create handlers that then reference this looper, before actually starting the loop. Be sure to call loop() after calling this method, and end it by calling quit().
void loop ()
Run the message queue in this thread. Be sure to call quit() to end the loop.
void quit()
Quits the looper.
Causes the loop() method to terminate without processing any more messages in the message queue.
This mindorks article by Janishar explains the core concepts in nice way.
Looper
is associated with a Thread. If you need Looper
on UI thread, Looper.getMainLooper()
will return associated thread.
You need Looper
to be associated with a Handler.
Looper
, Handler
, and HandlerThread
are the Android’s way of solving the problems of asynchronous programming.
Once you have Handler
, you can call below APIs.
post (Runnable r)
Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.
boolean sendMessage (Message msg)
Pushes a message onto the end of the message queue after all pending messages before the current time. It will be received in handleMessage(Message), in the thread attached to this handler.
HandlerThread is handy class for starting a new thread that has a looper. The looper can then be used to create handler classes
In some scenarios, you can't run Runnable
tasks on UI Thread.
e.g. Network operations : Send message on a socket, open an URL and get content by reading InputStream
In these cases, HandlerThread
is useful. You can get Looper
object from HandlerThread
and create a Handler
on HandlerThread
instead of main thread.
The HandlerThread code will be like this:
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
Refer to below post for example code:
There's no such thing as a global variable in C#. Period.
You can have static members if you want:
public static class MyStaticValues
{
public static bool MyStaticBool {get;set;}
}
For fine tuning the position of an inline-block
item, use top and left:
position: relative;
top: 5px;
left: 5px;
Thanks CSS-Tricks!
protected void CheckedRecords(object sender, EventArgs e)
{
string email = string.Empty;
foreach (GridViewRow gridrows in GridView1.Rows)
{
CheckBox chkbox = (CheckBox)gridrows.FindControl("ChkRecords");
if (chkbox != null & chkbox.Checked)
{
int columnIndex = 0;
foreach (DataControlFieldCell cell in gridrows.Cells)
{
if (cell.ContainingField is BoundField)
if (((BoundField)cell.ContainingField).DataField.Equals("UserEmail"))
break;
columnIndex++;
}
email += gridrows.Cells[columnIndex].Text + ',';
}
}
Label1.Text = "email:" + email;
}
Another simple trick:
SELECT CONVERT(char(2), cast('2015-01-01' as datetime), 101) -- month with 2 digits
SELECT CONVERT(char(6), cast('2015-01-01' as datetime), 112) -- year (yyyy) and month (mm)
Outputs:
01
201501
I know I'm uprising a very old topic, but after a couple of hours struggling with this very problem and not finding a solution anywhere else, I think this is a good place to put an answer.
We have some Build Servers WindowsXP based and found this very problem: svn command line client is not caching auth credentials.
We finally found out that we are using Cygwin's svn client! not a "native" Windows. So... this client stores all the auth credentials in /home/<user>/.subversion/auth
This /home directory in Cygwin, in our installation is in c:\cygwin\home. AND: the problem was that the Windows user that is running svn did never ever "logged in" in Cygwin, and so there was no /home/<user> directory.
A simple "bash -ls" from a Windows command terminal created the directory, and after the first access to our SVN server with interactive prompting for access credentials, alás, they got cached.
So if you are using Cygwin's svn client, be sure to have a "home" directory created for the local Windows user.
Here's a sample code:
Exec sp_add_schedule
@schedule_name = N'SchedulName'
@freq_type = 1
@active_start_time = 08300
The following JavaScript will open a new browser window, 450px wide by 300px high with scrollbars:
window.open("http://myurl", "_blank", "scrollbars=1,resizable=1,height=300,width=450");
You can add this to a link like so:
<a href='#' onclick='javascript:window.open("http://myurl", "_blank", "scrollbars=1,resizable=1,height=300,width=450");' title='Pop Up'>Pop Up</a>
This was added to the upgrade documentation on Dec 29, 2015, so if you upgraded before then you probably missed it.
When fetching any attribute from the model it checks if that column should be cast as an integer, string, etc.
By default, for auto-incrementing tables, the ID is assumed to be an integer in this method:
https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Model.php#L2790
So the solution is:
class UserVerification extends Model
{
protected $primaryKey = 'your_key_name'; // or null
public $incrementing = false;
// In Laravel 6.0+ make sure to also set $keyType
protected $keyType = 'string';
}
I'm afraid your posted example is not working, since X and Y aren't defined. So instead of pcolormesh
let's use imshow
:
import numpy as np
import matplotlib.pyplot as plt
H = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]) # added some commas and array creation code
fig = plt.figure(figsize=(6, 3.2))
ax = fig.add_subplot(111)
ax.set_title('colorMap')
plt.imshow(H)
ax.set_aspect('equal')
cax = fig.add_axes([0.12, 0.1, 0.78, 0.8])
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
cax.patch.set_alpha(0)
cax.set_frame_on(False)
plt.colorbar(orientation='vertical')
plt.show()
The for
-in
loops for each property in an object or array. You can use this property to get to the value as well as change it.
Note: Private properties are not available for inspection, unless you use a "spy"; basically, you override the object and write some code which does a for-in loop inside the object's context.
For in looks like:
for (var property in object) loop();
Some sample code:
function xinspect(o,i){
if(typeof i=='undefined')i='';
if(i.length>50)return '[MAX ITERATIONS]';
var r=[];
for(var p in o){
var t=typeof o[p];
r.push(i+'"'+p+'" ('+t+') => '+(t=='object' ? 'object:'+xinspect(o[p],i+' ') : o[p]+''));
}
return r.join(i+'\n');
}
// example of use:
alert(xinspect(document));
Edit: Some time ago, I wrote my own inspector, if you're interested, I'm happy to share.
Edit 2: Well, I wrote one up anyway.
The javax.mail-api
artifact is only good for compiling against.
You actually need to run code, so you need a complete implementation of JavaMail API. Use this:
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
NOTE: The version number will probably differ. Check the latest version here.
To add the reference to "System.Windows.Forms", it seems to be a little different for Visual Studio Community 2017.
1) Go to solution explorer and select references
2) Right-click and select Add references
3) In Assemblies, check System.Windows.Forms and press ok
4) That's it.
Call label.Invalidate
and then label.Update()
- usually the update only happens after you exit the current function but calling Update forces it to update at that specific place in code.
From MSDN:
The Invalidate method governs what gets painted or repainted. The Update method governs when the painting or repainting occurs. If you use the Invalidate and Update methods together rather than calling Refresh, what gets repainted depends on which overload of Invalidate you use. The Update method just forces the control to be painted immediately, but the Invalidate method governs what gets painted when you call the Update method.
If you want to get full screen without actionBar and Title.
Add it in style.xml
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
</style>
and use the style at activity of manifest.xml.
<activity ....
android:theme="@style/AppTheme.NoActionBar" > ......
</activity>
define VERSION variable and import version into it.
import { VERSION } from '@angular/core';
Now you can use VERSION variable in your code to print version For example,
console.log(VERSION.full);
if you are using inline coding in single page and not using oops than go with this full example, it will sure help
//connect to the db
$dbh = new PDO('mysql:host=localhost;dbname=mydb', dbuser, dbpw);
//build the query
$query="SELECT field1, field2
FROM ubertable
WHERE field1 > 6969";
//execute the query
$data = $dbh->query($query);
//convert result resource to array
$result = $data->fetchAll(PDO::FETCH_ASSOC);
//view the entire array (for testing)
print_r($result);
//display array elements
foreach($result as $output) {
echo output[field1] . " " . output[field1] . "<br />";
}
To add to the previous answers, if you have a tarball image, you can simply load it to you local docker set of images docker image load -i /path/image.tar
.Please remember to run it after eval $(minikube docker-env)
, since minikube does not share images with the locally installed docker engine.
Try adding this to your web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/your-servlet-name.xml
</param-value>
The results of the execution time directly contradict the results of the Query Cost, but I'm having difficulty determining what "Query Cost" actually means.
Query cost
is what optimizer thinks of how long your query will take (relative to total batch time).
The optimizer tries to choose the optimal query plan by looking at your query and statistics of your data, trying several execution plans and selecting the least costly of them.
Here you may read in more detail about how does it try to do this.
As you can see, this may differ significantly of what you actually get.
The only real query perfomance metric is, of course, how long does the query actually take.
temp[::-1].sort()
sorts the array in place, whereas np.sort(temp)[::-1]
creates a new array.
In [25]: temp = np.random.randint(1,10, 10)
In [26]: temp
Out[26]: array([5, 2, 7, 4, 4, 2, 8, 6, 4, 4])
In [27]: id(temp)
Out[27]: 139962713524944
In [28]: temp[::-1].sort()
In [29]: temp
Out[29]: array([8, 7, 6, 5, 4, 4, 4, 4, 2, 2])
In [30]: id(temp)
Out[30]: 139962713524944
It works for me. See this solution - https://alvarotrigo.com/blog/firing-resize-event-only-once-when-resizing-is-finished/
var resizeId;_x000D_
$(window).resize(function() {_x000D_
clearTimeout(resizeId);_x000D_
resizeId = setTimeout(doneResizing, 500);_x000D_
});_x000D_
function doneResizing(){_x000D_
//whatever we want to do _x000D_
}
_x000D_
check the formats here http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
main
System.out.println("date : " + new classname().getMyDate("2014-01-09 14:06", "dd-MMM-yyyy E hh:mm a z", "yyyy-MM-dd HH:mm"));
method
public String getMyDate(String myDate, String returnFormat, String myFormat)
{
DateFormat dateFormat = new SimpleDateFormat(returnFormat);
Date date=null;
String returnValue="";
try {
date = new SimpleDateFormat(myFormat, Locale.ENGLISH).parse(myDate);
returnValue = dateFormat.format(date);
} catch (ParseException e) {
returnValue= myDate;
System.out.println("failed");
e.printStackTrace();
}
return returnValue;
}
Evidence that std::unordered_map
uses a hash map in GCC stdlibc++ 6.4
This was mentioned at: https://stackoverflow.com/a/3578247/895245 but in the following answer: What data structure is inside std::map in C++? I have given further evidence of such for the GCC stdlibc++ 6.4 implementation by:
Here is a preview of the performance characteristic graph described in that answer:
How to use a custom class and hash function with unordered_map
This answer nails it: C++ unordered_map using a custom class type as the key
Excerpt: equality:
struct Key
{
std::string first;
std::string second;
int third;
bool operator==(const Key &other) const
{ return (first == other.first
&& second == other.second
&& third == other.third);
}
};
Hash function:
namespace std {
template <>
struct hash<Key>
{
std::size_t operator()(const Key& k) const
{
using std::size_t;
using std::hash;
using std::string;
// Compute individual hash values for first,
// second and third and combine them using XOR
// and bit shifting:
return ((hash<string>()(k.first)
^ (hash<string>()(k.second) << 1)) >> 1)
^ (hash<int>()(k.third) << 1);
}
};
}
I think you set it as
var data = [];
but after some time you made it like:
data = 'some thing which is not an array';
then
data.push('')
will not work as it is not an array anymore.
Simply we can trace the request message as.
OperationContext context = OperationContext.Current;
if (context != null && context.RequestContext != null)
{
Message msg = context.RequestContext.RequestMessage;
string reqXML = msg.ToString();
}
If you are using Asp.Identity UseManager, it automatically sets the value of
RequestContext.Principal.Identity.GetUserId()
based on IdentityUser you use in creating the IdentityDbContext.
If ever you are implementing a custom user table and owin token bearer authentication, kindly check on my answer.
How to get user context during Web Api calls?
Hope it still helps. :)
Try like this
<script>
$(document).ready(function(){
$("#order_ship_date").datepicker({
changeMonth:true,
changeYear:true,
dateFormat:"yy-mm-dd",
minDate: +2,
});
});
</script>
html code is given below
<input id="order_ship_date" type="text" class="input" style="width:80px;" />
Came across the same problem. Fixed it by adding to my controller:
skip_before_filter :verify_authenticity_token, if: :json_request?
So far all the answers are about that %n
does, but not why anyone would want it in the first place. I find it's somewhat useful with sprintf
/snprintf
, when you might need to later break up or modify the resulting string, since the value stored is an array index into the resulting string. This application is a lot more useful, however, with sscanf
, especially since functions in the scanf
family don't return the number of chars processed but the number of fields.
Another really hackish use is getting a pseudo-log10 for free at the same time while printing a number as part of another operation.
I was having an issue with this, my server was running behind a load balancer. The load balancer was terminating the SSL/TLS connection. It then passed the request to the web servers using http.
Using the Url.Action() method with Request.Url.Schema, it kept creating a http url, in my case to create a link in an automated email (which my PenTester didn't like).
I may have cheated a little, but it is exactly what I needed to force a https url:
<a href="@Url.Action("Action", "Controller", new { id = Model.Id }, "https")">Click Here</a>
I actually use a web.config AppSetting so I can use http when debugging locally, but all test and prod environments use transformation to set the https value.
document.getElementsByClassName
returns a NodeList
, not a single element, I'd recommend either using jQuery, since you'd only have to use something like $('.new').toggle()
or if you want plain JS try :
function toggle_by_class(cls, on) {
var lst = document.getElementsByClassName(cls);
for(var i = 0; i < lst.length; ++i) {
lst[i].style.display = on ? '' : 'none';
}
}
I got this error in an Ubuntu Docker container. I believe the cause was that the container was missing CA certs. To fix it, I had to run:
apt-get update
apt-get install ca-certificates
by typing yes it wont charge taxes, by typing no it will charge taxes.
=IF(C39="Yes","0",IF(C39="no",PRODUCT(G36*0.0825)))
Here is from pandas docs on advanced indexing:
The section will explain exactly what you need! Turns out df.loc
(as .ix has been deprecated -- as many have pointed out below) can be used for cool slicing/dicing of a dataframe. And. It can also be used to set things.
df.loc[selection criteria, columns I want] = value
So Bren's answer is saying 'find me all the places where df.A == 0
, select column B
and set it to np.nan
'
Set the value from code on showing the form, not in the design-timeProperties for the text box.
Private Sub UserForm_Activate()
Me.txtDate.Value = Format(Date, "mm/dd/yy")
End Sub
Typically you model the enum itself as a class with the enum
stereotype
sort dictionary 'in_dict' by value in decreasing order
sorted_dict = {r: in_dict[r] for r in sorted(in_dict, key=in_dict.get, reverse=True)}
example above
sorted_d = {r: d[r] for r in sorted(d, key=d.get('key3'), reverse=True)}
a proper solution with streams and error handling is below:
const fs = require('fs')
const stream = require('stream')
app.get('/report/:chart_id/:user_id',(req, res) => {
const r = fs.createReadStream('path to file') // or any other way to get a readable stream
const ps = new stream.PassThrough() // <---- this makes a trick with stream error handling
stream.pipeline(
r,
ps, // <---- this makes a trick with stream error handling
(err) => {
if (err) {
console.log(err) // No such file or any other kind of error
return res.sendStatus(400);
}
})
ps.pipe(res) // <---- this makes a trick with stream error handling
})
with Node older then 10 you will need to use pump instead of pipeline.
$description = nl2br(stripcslashes($description));
public static float roundFloat(float in) {
return ((int)((in*100f)+0.5f))/100f;
}
Should be ok for most cases. You can still changes types if you want to be compliant with doubles for instance.
Here is the BESTEST way to send emails using PHPmailer library, this is the only method that works for me.
require_once 'mailer/class.phpmailer.php';
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = "[email protected]";
$mail->Password = "xxxxxxx";
$mail->SetFrom("[email protected]");
$mail->AddAddress($to);
$logfile = dirname(dirname(__FILE__)) . '/mail.log';
try {
$mail->Body = $message;
$mail->Subject = $subject;
file_put_contents($logfile, "Content: \n", FILE_APPEND);
file_put_contents($logfile, $message . "\n\n", FILE_APPEND);
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Email has been sent";
}
} catch (Exception $e) {
#print_r($e->getMessage());
file_put_contents($logfile, "Error: \n", FILE_APPEND);
file_put_contents($logfile, $e->getMessage() . "\n", FILE_APPEND);
file_put_contents($logfile, $e->getTraceAsString() . "\n\n", FILE_APPEND);
}
The zabbix-server
daemon doesn't seem to like passwords with special characters in them. Unsure whether quotes would work in the configuration I just removed special characters from the database password, updated the configuration files and restarted the daemon.
Configuration parsing errors don't show up in logs for some reason.
I think it's worth looking at GNU "time" command source code. time It outputs user/system cpu time along with real elapsed time. It calls wait3/wait4 system call (if available) and otherwise it calls times system call. wait* system call returns a "rusage" struct variable and times system call returns "tms". Also, you can have a look at getrusage system call which also return very interesting timing information. time
I did apt-get install python3-dev
in my Ubuntu and added setup_requires=["wheel"]
in setup.py
If you dont care about the aspect ration (i.e you want to force the image to a particular dimension), here is a simplified answer
// for jpg
function resize_imagejpg($file, $w, $h) {
list($width, $height) = getimagesize($file);
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($w, $h);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
return $dst;
}
// for png
function resize_imagepng($file, $w, $h) {
list($width, $height) = getimagesize($file);
$src = imagecreatefrompng($file);
$dst = imagecreatetruecolor($w, $h);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
return $dst;
}
// for gif
function resize_imagegif($file, $w, $h) {
list($width, $height) = getimagesize($file);
$src = imagecreatefromgif($file);
$dst = imagecreatetruecolor($w, $h);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
return $dst;
}
Now let's handle the upload part. First step, upload the file to your desired directory. Then called one of the above functions based on file type (jpg, png or gif) and pass the absolute path of your uploaded file as below:
// jpg change the dimension 750, 450 to your desired values
$img = resize_imagejpg('path/image.jpg', 750, 450);
The return value $img
is a resource object. We can save to a new location or override the original as below:
// again for jpg
imagejpeg($img, 'path/newimage.jpg');
Hope this helps someone. Check these links for more on resizing Imagick::resizeImage and imagejpeg()
How's this for an explantation to the layman. One way computers represent numbers is by counting discrete units. These are digital computers. For whole numbers, those without a fractional part, modern digital computers count powers of two: 1, 2, 4, 8. ,,, Place value, binary digits, blah , blah, blah. For fractions, digital computers count inverse powers of two: 1/2, 1/4, 1/8, ... The problem is that many numbers can't be represented by a sum of a finite number of those inverse powers. Using more place values (more bits) will increase the precision of the representation of those 'problem' numbers, but never get it exactly because it only has a limited number of bits. Some numbers can't be represented with an infinite number of bits.
Snooze...
OK, you want to measure the volume of water in a container, and you only have 3 measuring cups: full cup, half cup, and quarter cup. After counting the last full cup, let's say there is one third of a cup remaining. Yet you can't measure that because it doesn't exactly fill any combination of available cups. It doesn't fill the half cup, and the overflow from the quarter cup is too small to fill anything. So you have an error - the difference between 1/3 and 1/4. This error is compounded when you combine it with errors from other measurements.
If you wish to have an Array in which you will not be allocating all of the elements, you will have to do your own bookkeeping to ensure how many elements you have placed in it via some other variable. If you'd like to avoid doing this while also getting an "Array" that can grow capacities after its initial instantiation, you can create an ArrayList
ArrayList<Integer> theArray = new ArrayList<Integer>();
theArray.add(5); // places at index 0
theArray.size(); // returns length of 1
int answer = theArray.get(0); // index 0 = 5
Don't forget to import it at the top of the file:
import java.util.ArrayList;
You can call setScale(newScale, roundingMode)
method three times with changing the newScale value from 4 to 3 to 2 like
First case
BigDecimal a = new BigDecimal("10.12345");
a = a.setScale(4, BigDecimal.ROUND_HALF_UP);
System.out.println("" + a); //10.1235
a = a.setScale(3, BigDecimal.ROUND_HALF_UP);
System.out.println("" + a); //10.124
a = a.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("" + a); //10.12
Second case
BigDecimal a = new BigDecimal("10.12556");
a = a.setScale(4, BigDecimal.ROUND_HALF_UP);
System.out.println("" + a); //10.1256
a = a.setScale(3, BigDecimal.ROUND_HALF_UP);
System.out.println("" + a); //10.126
a = a.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("" + a); //10.13
textarea {
border: 0;
overflow: auto; }
less CSS ^ you can't align the text to the bottom unfortunately.
git remote manpage is pretty straightforward:
Use
Older (backwards-compatible) syntax:
$ git remote rm upstream
Newer syntax for newer git versions: (* see below)
$ git remote remove upstream
Then do:
$ git remote add upstream https://github.com/Foo/repos.git
or just update the URL directly:
$ git remote set-url upstream https://github.com/Foo/repos.git
or if you are comfortable with it, just update the .git/config directly - you can probably figure out what you need to change (left as exercise for the reader).
...
[remote "upstream"]
fetch = +refs/heads/*:refs/remotes/upstream/*
url = https://github.com/foo/repos.git
...
===
* Regarding 'git remote rm' vs 'git remote remove' - this changed around git 1.7.10.3 / 1.7.12 2 - see
Log message
remote: prefer subcommand name 'remove' to 'rm'
All remote subcommands are spelled out words except 'rm'. 'rm', being a
popular UNIX command name, may mislead users that there are also 'ls' or
'mv'. Use 'remove' to fit with the rest of subcommands.
'rm' is still supported and used in the test suite. It's just not
widely advertised.
I think Jason's right. If your "Delete" action is a minimal one, make that be in a form by itself, and line it up with the other buttons so as to make the interface look like one unified form, even if it's not.
Or, of course, redesign your interface, and let people delete somewhere else entirely which doesn't require them to see the enormo-form at all.
November 2019:
onclick="self.close()"
still works in Chrome while Edge gives a warning that must be confirmed before it will close.
On the other hand the solution onclick="window.open('', '_self', ''); window.close();"
works in both.
There was a requirement to get status and cpu / memory usage of some specific windows servers. I used below script:
This is an example of Windows Search Service.
$cpu = Get-WmiObject win32_processor
$search = get-service "WSearch"
if ($search.Status -eq 'Running')
{
$searchmem = Get-WmiObject Win32_Service -Filter "Name = 'WSearch'"
$searchid = $searchmem.ProcessID
$searchcpu1 = Get-WmiObject Win32_PerfRawData_PerfProc_Process | Where {$_.IDProcess -eq $searchid}
Start-Sleep -Seconds 1
$searchcpu2 = Get-WmiObject Win32_PerfRawData_PerfProc_Process | Where {$_.IDProcess -eq $searchid}
$searchp2p1 = $searchcpu2.PercentProcessorTime - $searchcpu1.PercentProcessorTime
$searcht2t1 = $searchcpu2.Timestamp_Sys100NS - $searchcpu1.Timestamp_Sys100NS
$searchcpu = [Math]::Round(($searchp2p1 / $searcht2t1 * 100) /$cpu.NumberOfLogicalProcessors, 1)
$searchmem = [Math]::Round($searchcpu1.WorkingSetPrivate / 1mb,1)
Write-Host 'Service is' $search.Status', Memory consumed: '$searchmem' MB, CPU Usage: '$searchcpu' %'
}
else
{
Write-Host Service is $search.Status -BackgroundColor Red
}
Looks to be an indentation problem. You don't have to match curly brackets in Python but you do have to match indentation levels.
The best way to prevent space/tab problems is to display invisible characters within your text editor. This will give you a quick way to prevent and/or resolve indentation-related errors.
Also, injecting copy-pasted code is a common source for this type of problem.
As discussed above, we need to implement Select Class in Selenium and further we can use various available methods like :-
If you VS solution contains several projects, select all of them in the right pane, and press "properties". Then go to C++ -> Code Generation and chose one Run Time library option for all of them
The os.makedirs
function does this. Try the following:
import os
import errno
filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
with open(filename, "w") as f:
f.write("FOOBAR")
The reason to add the try-except
block is to handle the case when the directory was created between the os.path.exists
and the os.makedirs
calls, so that to protect us from race conditions.
In Python 3.2+, there is a more elegant way that avoids the race condition above:
import os
filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
f.write("FOOBAR")
Your header file Hash.h
declares "what class hash
should look like", but not its implementation, which is (presumably) in some other source file we'll call Hash.cpp
. By including the header in your main file, the compiler is informed of the description of class Hash
when compiling the file, but not how class Hash
actually works. When the linker tries to create the entire program, it then complains that the implementation (toHash::insert(int, char)
) cannot be found.
The solution is to link all the files together when creating the actual program binary. When using the g++ frontend, you can do this by specifying all the source files together on the command line. For example:
g++ -o main Hash.cpp main.cpp
will create the main program called "main".
when you render
a request tou coctext
some information:
for exampel:
return render(request, 'path to template',{'username' :username , 'email'.email})
you can acces to it on template like this :
for variabels :
{% if username %}{{ username }}{% endif %}
for array :
{% if username %}{{ username.1 }}{% endif %}
{% if username %}{{ username.2 }}{% endif %}
you can also name array objects in views.py
and ten use it like:
{% if username %}{{ username.first }}{% endif %}
if there is other problem i wish to help you
The picture you showd in the question is actually a chart made using JavaScript. It is actually very easy to plot multi-axis chart using JavaScript with the help of 3rd party libraries like HighChart.js or D3.js. Here I propose to use the Funfun Excel add-in which allows you to use JavaScript directly in Excel so you could plot chart like you've showed easily in Excel. Here I made an example using Funfun in Excel.
You could see in this chart you have one axis of Rainfall at the left side while two axis of Temperature and Sea-pressure level at the right side. This is also a combination of line chart and bar chart for different datasets. In this example, with the help of the Funfun add-in, I used HighChart.js to plot this chart.
Funfun also has an online editor in which you could test your JavaScript code with you data. You could check the detailed code of this example on the link below.
https://www.funfun.io/1/#/edit/5a43b416b848f771fbcdee2c
Edit: The content on the previous link has been changed so I posted a new link here. The link below is the original link https://www.funfun.io/1/#/edit/5a55dc978dfd67466879eb24
If you are satisfied with the result you achieved in the online editor, you could easily load the result into you Excel using the URL above. Of couse first you need to insert the Funfun add-in from Insert - My add-ins. Here are some screenshots showing how you could do this.
Disclosure: I'm a developer of Funfun
add:
@SuppressLint("ValidFragment")
before your class.
it it doesn´t work do something like this:
@SuppressLint({ "ValidFragment", "HandlerLeak" })
As has already been pointed out by others, using a function should be considered best practice.
However, here is another approach, leveraging xargs
:
alias junk="xargs -I "{}" -- mv "{}" "~/.Trash" <<< "
Note that this has side effects regarding redirection of streams.
UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.
If your project uses Maven you can simply include UCanAccess via the following coordinates:
groupId: net.sf.ucanaccess
artifactId: ucanaccess
The following is an excerpt from pom.xml
, you may need to update the <version>
to get the most recent release:
<dependencies>
<dependency>
<groupId>net.sf.ucanaccess</groupId>
<artifactId>ucanaccess</artifactId>
<version>4.0.4</version>
</dependency>
</dependencies>
As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:
UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)
Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like
ucanaccess-4.0.1.jar
/lib/
commons-lang-2.6.jar
commons-logging-1.1.1.jar
hsqldb.jar
jackcess-2.1.6.jar
All you need to do is add all five (5) JARs to your project.
NOTE: Do not add
loader/ucanload.jar
to your build path if you are adding the other five (5) JAR files. TheUcanloadDriver
class is only used in special circumstances and requires a different setup. See the related answer here for details.
Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path...
. Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this
NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.
After adding all five (5) JAR files the "Libraries" folder should look something like this:
IntelliJ IDEA: Choose File > Project Structure...
from the main menu. In the "Libraries" pane click the "Add" (+
) button and add the five (5) JAR files. Once that is done the project should look something like this:
Now "U Can Access" data in .accdb and .mdb files using code like this
// assumes...
// import java.sql.*;
Connection conn=DriverManager.getConnection(
"jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
System.out.println(rs.getString(1));
}
At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.
.list-inline class in bootstrap is a Inline Unordered List.
If you want to create a horizontal menu using ordered or unordered list you need to place all list items in a single line i.e. side by side. You can do this by simply applying the class
<div class="list-inline">
<a href="#" class="list-inline-item">First item</a>
<a href="#" class="list-inline-item">Secound item</a>
<a href="#" class="list-inline-item">Third item</a>
</div>
Problem:
Your View
cannot be found in default locations.
Explanation:
Views should be in the same folder named as the Controller
or in the Shared
folder.
Solution:
Either move your View
to the MyAccount
folder or create a HomeController
.
Alternatives:
If you don't want to move your View
or create a new Controller
you can check at this link.
I had trouble initially (don't know why) but I finally got the following to work with SSMS for SQL Server 2008.
Insert ALT-13 then ALT-10 where desired in your text in a varchar type column (music symbol and square appear and save when you leave the row). Initially you'll get a warning(!) to the left of the row after leaving it. Just re-excecute your SELECT statement. The symbols and warning will disappear but the CR/LF is saved. You must include ALT-13 if you want the text displayed properly in HTML. To quickly determine if this worked, copy the saved text from SSMS to Notepad.
Alternatively, if you can't get this to work, you can do the same thing starting with an nvarchar column. However the symbols will be saved as text so you must convert the column to varchar when you're done to convert the symbols to CR/LFs.
If you want to copy & paste text from another source (another row or table, HTML, Notepad, etc.) and not have your text truncated at the first CR, I found that the solution (Programmer's Notepad) referred to at the following link works with SSMS for SQL Server 2008 using varchar & nvarchar column types.
The author of the post (dbaspot) mentions something about creating SQL queries - not sure what he means. Just follow the intructions about Programmer's Notepad and you can copy & paste text to and from SSMS and retain the LFs both ways (using Programmer's Notepad, not Notepad). To have the text display properly in HTML you must add CRs to the text copied to SSMS. The best way to do this is by executing an UPDATE statement using the REPLACE function to add CRs as follows:
UPDATE table_name
SET column_name = REPLACE(column_name , CHAR(10), CHAR(13) + CHAR(10)).
You need to create a C API for exposing the functionality of your C++ code. Basically, you will need to write C++ code that is declared extern "C" and that has a pure C API (not using classes, for example) that wraps the C++ library. Then you use the pure C wrapper library that you've created.
Your C API can optionally follow an object-oriented style, even though C is not object-oriented. Ex:
// *.h file
// ...
#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif
typedef void* mylibrary_mytype_t;
EXTERNC mylibrary_mytype_t mylibrary_mytype_init();
EXTERNC void mylibrary_mytype_destroy(mylibrary_mytype_t mytype);
EXTERNC void mylibrary_mytype_doit(mylibrary_mytype_t self, int param);
#undef EXTERNC
// ...
// *.cpp file
mylibrary_mytype_t mylibrary_mytype_init() {
return new MyType;
}
void mylibrary_mytype_destroy(mylibrary_mytype_t untyped_ptr) {
MyType* typed_ptr = static_cast<MyType*>(untyped_ptr);
delete typed_ptr;
}
void mylibrary_mytype_doit(mylibrary_mytype_t untyped_self, int param) {
MyType* typed_self = static_cast<MyType*>(untyped_self);
typed_self->doIt(param);
}
I solved my issue with : Java Build Path -> JRE system library - > Edit -> Alternate JRE -> -> Finish
As it was configured to JDK folder so it was giving Exception
i am using the following code please try it out
DateFormat fm= new SimpleDateFormatter();
specify the format of the date you want
for example "DD-MM_YYYY"
or 'YYYY-mm-dd'
then use the java Date datatype as
fm.format("object of java.util.date");
then it will parse your date
@Bhabadyuti Bal give us a good answer, in gradle you can use :
compile 'org.springframework.boot:spring-boot-starter-data-jpa'
compile 'com.h2database:h2'
in test time :
testCompile 'org.reactivecommons.utils:object-mapper:0.1.0'
testCompile 'com.h2database:h2'
To enable JMX remote, pass below VM parameters along with JAVA Command.
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=453
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
-Djava.rmi.server.hostname=myDomain.in
Use Boost asynchronous input/output threads, sleep for x milliseconds;
#include <boost/thread.hpp>
#include <boost/asio.hpp>
boost::thread::sleep(boost::get_system_time() + boost::posix_time::millisec(1000));
I know the answer has already been provided. But I just wanted to elaborate with regards to doing this in a Blazor app (razor)...
You will need to inject IJSRuntime, in order to perform JSInterop (running javascript functions from C#)
IN YOUR RAZOR PAGE:
@inject IJSRuntime JSRuntime
Once you have that injected, create a button with a click event that calls a C# method:
<MatFAB Icon="@MatIconNames.Print" OnClick="@(async () => await print())"></MatFAB>
(or something more simple if you don't use MatBlazor)
<button @onclick="@(async () => await print())">PRINT</button>
For the C# method:
public async Task print()
{
await JSRuntime.InvokeVoidAsync("printDocument");
}
NOW IN YOUR index.html:
<script>
function printDocument() {
window.print();
}
</script>
Something to note, the reason the onclick events are asynchronous is because IJSRuntime awaits it's calls such as InvokeVoidAsync
PS: If you wanted to message box in asp net core for instance:
await JSRuntime.InvokeAsync<string>("alert", "Hello user, this is the message box");
To have a confirm message box:
bool question = await JSRuntime.InvokeAsync<bool>("confirm", "Are you sure you want to do this?");
if(question == true)
{
//user clicked yes
}
else
{
//user clicked no
}
Hope this helps :)
For method decorator declaration
with configuration "noImplicitAny": true,
you can specify type of this variable explicitly depends on @tony19's answer
function logParameter(this:any, target: Object, propertyName: string) {
//...
}
e= StringVar()
def fileDialog():
filename = filedialog.askopenfilename(initialdir = "/",title = "Select A
File",filetype = (("jpeg","*.jpg"),("png","*.png"),("All Files","*.*")))
e.set(filename)
la = Entry(self,textvariable = e,width = 30).place(x=230,y=330)
butt=Button(self,text="Browse",width=7,command=fileDialog).place(x=430,y=328)
Sometimes using
instead of spaces will work. Clearly it has drawbacks, though.
I'm not entirely sure if you want it, but I had a similar task and needed to remove a field if it is zero. For example, 86401 seconds would show "1 days, 1 seconds" instead of "1 days, 0 hours, 0 minutes, 1 seconds". THe following code does that.
def secondsToText(secs):
days = secs//86400
hours = (secs - days*86400)//3600
minutes = (secs - days*86400 - hours*3600)//60
seconds = secs - days*86400 - hours*3600 - minutes*60
result = ("{} days, ".format(days) if days else "") + \
("{} hours, ".format(hours) if hours else "") + \
("{} minutes, ".format(minutes) if minutes else "") + \
("{} seconds, ".format(seconds) if seconds else "")
return result
EDIT: a slightly better version that handles pluralization of words.
def secondsToText(secs):
days = secs//86400
hours = (secs - days*86400)//3600
minutes = (secs - days*86400 - hours*3600)//60
seconds = secs - days*86400 - hours*3600 - minutes*60
result = ("{0} day{1}, ".format(days, "s" if days!=1 else "") if days else "") + \
("{0} hour{1}, ".format(hours, "s" if hours!=1 else "") if hours else "") + \
("{0} minute{1}, ".format(minutes, "s" if minutes!=1 else "") if minutes else "") + \
("{0} second{1}, ".format(seconds, "s" if seconds!=1 else "") if seconds else "")
return result
EDIT2: created a gist that does that in several languages
I think You are using //--style="display:none"--//
for hiding the div.
Use this code:
<script>
function klikaj(i) {
document.getElementById(i).style.display = 'block';
}
</script>
<div id="thumb0" class="thumbs" onclick="klikaj('rad1')">Click Me..!</div>
<div id="rad1" class="thumbs" style="display:none">Helloooooo</div>
Even after going through many posts, it took several hours to figure out the problem. Here is the detailed approach written in simple language to run python via command line in windows.
1. Download executable file from python.org
Choose the latest version and download Windows-executable installer. Execute the downloaded file and let installation complete.
2. Ensure the file is downloaded in some administrator folder
3. Update the system PATH variable This is the most crucial step and there are two ways to do this:- (Follow the second one preferably)
1. MANUALLY
- Search for 'Edit the system Environment Variables' in the search bar.(WINDOWS 10)
- In the System Properties dialog, navigate to "Environment Variables".
- In the Environment Variables dialog look for "Path" under the System Variables window. (# Ensure to click on Path under bottom window named System Variables and not under user variables)
- Edit the Path Variable by adding location of Python37/ PythonXX folder. I added following line:-
" ;C:\Program Files (x86)\Python37;C:\Program Files (x86)\Python37\Scripts "
- Click Ok and close the dialogs.
2. SCRIPTED
- Open the command prompt and navigate to Python37/XX folder using cd command.
- Write the following statement:-
"python.exe Tools\Scripts\win_add2path.py"
You can now use python in the command prompt:)
1. Using Shell
Type python in cmd and use it.
2. Executing a .py file
Type python filename.py to execute it.
you can use spread operator in a more basic form
[].concat(...array)
in the case of functions that return arrays but are expected to pass as arguments
Example:
function expectArguments(...args){
return [].concat(...args);
}
JSON.stringify(expectArguments(1,2,3)) === JSON.stringify(expectArguments([1,2,3]))
Use std::vector for this. For example:
std::vector<int> values;
values.resize(n);
The memory will be allocated on the heap, but this holds only a small performance drawback. Furthermore, it is wise not to allocate large datablocks on the stack, as it is rather limited in size.
In Java 8, you can read a whole file, simply with:
public String read(String file) throws IOException {
return new String(Files.readAllBytes(Paths.get(file)));
}
or if its a Resource:
public String read(String file) throws IOException {
URL url = Resources.getResource(file);
return Resources.toString(url, Charsets.UTF_8);
}
On Latest Mac with Jio IP6 Configuration issue ,it block internet on android simulator ,so from Android Virtual Device Manager simulator list Actions column dropdown select the option "Cold Boot Now" fixed the issue.I faced this problem after i kept same its working for me.
There is no way to do so, as JavaScript does not have an access to computer name, file system and other local info. Security is the main purpose.
Well generally you shouldn't need to classify an element specified by id, because id is always unique, but if you really need to, the following should work:
div#content.sectionA {
/* ... */
}
HTML
<p> <input type="checkbox" name="fruits" id="fruits" value="1" /> Apple </p>
<p> <input type="checkbox" name="fruits" id="fruits" value="2" /> Banana </p>
<p> <input type="checkbox" name="fruits" id="fruits" value="3" /> Mango </p>
<p> <input type="checkbox" name="fruits" id="fruits" value="4" /> Grape </p>
Jquery
for storing the selected fruit values define array.
fruitArray = [];
$.each will iterate the checked check boxes and pushed into array.
$.each($("input[name='fruits']:checked"), function (K, V) {
fruitArray.push(V.value);
});
Note: This is not a duplicate, because the OP is aware that the image from cv2.imread
is in BGR format (unlike the suggested duplicate question that assumed it was RGB hence the provided answers only address that issue)
To illustrate, I've opened up this same color JPEG image:
once using the conversion
img = cv2.imread(path)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
and another by loading it in gray scale mode
img_gray_mode = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
Like you've documented, the diff between the two images is not perfectly 0, I can see diff pixels in towards the left and the bottom
I've summed up the diff too to see
import numpy as np
np.sum(diff)
# I got 6143, on a 494 x 750 image
I tried all cv2.imread()
modes
Among all the IMREAD_
modes for cv2.imread()
, only IMREAD_COLOR
and IMREAD_ANYCOLOR
can be converted using COLOR_BGR2GRAY
, and both of them gave me the same diff against the image opened in IMREAD_GRAYSCALE
The difference doesn't seem that big. My guess is comes from the differences in the numeric calculations in the two methods (loading grayscale vs conversion to grayscale)
Naturally what you want to avoid is fine tuning your code on a particular version of the image just to find out it was suboptimal for images coming from a different source.
In brief, let's not mix the versions and types in the processing pipeline.
So I'd keep the image sources homogenous, e.g. if you have capturing the image from a video camera in BGR, then I'd use BGR as the source, and do the BGR to grayscale conversion cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Vice versa if my ultimate source is grayscale then I'd open the files and the video capture in gray scale cv2.imread(path, cv2.IMREAD_GRAYSCALE)
I found these two links very helpful while I was trying to learn socket.io:
echo -ne '\n' | <yourfinecommandhere>
or taking advantage of the implicit newline that echo generates (thanks Marcin)
echo | <yourfinecommandhere>
Now we can simply use the --sk
option:
--sk
,--skip-keypress
Don't wait for a keypress after each test
i.e. sudo rkhunter --sk --checkall
we can write the UTF-8 encoded file with java using use PrintWriter to write UTF-8 encoded xml
Or Click here
PrintWriter out1 = new PrintWriter(new File("C:\\abc.xml"), "UTF-8");
I just went through the same problem. And found out once you have a syntax or any type of error in you javascript, the whole file don't get loaded so you cannot use any of the other functions at all.
Try This:
<img class="img-responsive" src="assets/img/google-body-ads.png">
WCF is a newer technology that is a viable alternative in many instances. ASP is great and works well, but I personally prefer WCF. And you can do it in .Net 4.5.
Create a new project. Right-Click on the project in solution explorer, select "Add Service Reference"
Create a textbox and button in the new application. Below is my click event for the button:
private void btnGo_Click(object sender, EventArgs e)
{
ServiceReference1.Service1Client testClient = new ServiceReference1.Service1Client();
//Add error handling, null checks, etc...
int iValue = int.Parse(txtInput.Text);
string sResult = testClient.GetData(iValue).ToString();
MessageBox.Show(sResult);
}
And you're done.