Just wanted to add, you can return classes in __init__
@property
def failureException(self):
class MyCustomException(AssertionError):
def __init__(self_, *args, **kwargs):
*** Your code here ***
return super().__init__(*args, **kwargs)
MyCustomException.__name__ = AssertionError.__name__
return MyCustomException
The above method helps you implement a specific action upon an Exception in your test
Yes assuming you have this:
var WhatIsThe = AnswerToLife()
func AnswerToLife() int {
return 42
}
func init() {
WhatIsThe = 0
}
func main() {
if WhatIsThe == 0 {
fmt.Println("It's all a lie.")
}
}
AnswerToLife()
is guaranteed to run before init()
is called, and init()
is guaranteed to run before main()
is called.
Keep in mind that init()
is always called, regardless if there's main or not, so if you import a package that has an init
function, it will be executed.
Additionally, you can have multiple init()
functions per package; they will be executed in the order they show up in the file (after all variables are initialized of course). If they span multiple files, they will be executed in lexical file name order (as pointed out by @benc):
It seems that
init()
functions are executed in lexical file name order. The Go spec says "build systems are encouraged to present multiple files belonging to the same package in lexical file name order to a compiler". It seems thatgo build
works this way.
A lot of the internal Go packages use init()
to initialize tables and such, for example https://github.com/golang/go/blob/883bc6/src/compress/bzip2/bzip2.go#L480
A simple change in Num2 class like this:
super().__init__(num)
It works in python3.
class Num:
def __init__(self,num):
self.n1 = num
class Num2(Num):
def __init__(self,num):
super().__init__(num)
self.n2 = num*2
def show(self):
print (self.n1,self.n2)
mynumber = Num2(8)
mynumber.show()
Old thread. I found out that adding an __all__= ['submodule', ...]
to the
__init__.py file and then using the from <CURRENT_MODULE> import *
in the target works fine.
NB. Constructor function names should start with a capital letter to distinguish them from ordinary functions, e.g. MyClass
instead of myClass
.
Either you can call init
from your constructor function:
var myObj = new MyClass(2, true);
function MyClass(v1, v2)
{
// ...
// pub methods
this.init = function() {
// do some stuff
};
// ...
this.init(); // <------------ added this
}
Or more simply you could just copy the body of the init
function to the end of the constructor function. No need to actually have an init
function at all if it's only called once.
I usually do it the way that you are doing it (i.e. sudo -u username command). But, there is also the 'djb' way to run a daemon with privileges of another user. See: http://thedjbway.b0llix.net/daemontools/uidgid.html
You should use other variable:
$m=0;
for($n=1; $n<=8; $n++):
$n = $n + $m;
$m++;
echo '<p>'. $n .'</p>';
endfor;
If you have access to node you can do a npm install -g rexreplace
and then
rexreplace 'subdomainA.example.com' 'subdomainB.example.com' /home/www/**/*.*
Use the --sort=-committerdate
option of git for-each-ref
;
Also available since Git 2.7.0 for git branch
:
git for-each-ref --sort=-committerdate refs/heads/
# Or using git branch (since version 2.7.0)
git branch --sort=-committerdate # DESC
git branch --sort=committerdate # ASC
git for-each-ref --sort=committerdate refs/heads/ --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(color:red)%(objectname:short)%(color:reset) - %(contents:subject) - %(authorname) (%(color:green)%(committerdate:relative)%(color:reset))'
This should kill all processes matching the grep that you are permitted to kill.
-9 means "Kill all processes you can kill".
kill -9 $(ps -ef | grep [s]yncapp | awk '{print $2}')
My approach to the problem is similar to the way datayeah did it. I had a lot of hardcoded width and height values and the app looked fine on a specific device. So I got the screen height of the device and just created a factor to scale the hardcoded values.
double heightFactor = MediaQuery.of(context).size.height/708
where 708 is the height of the specific device.
declare @T1 table(ID int, ReceivedDate datetime, [type] varchar(10))
declare @T2 table(ID int, ReceivedDate datetime, [type] varchar(10))
insert into @T1 values(1, '20010101', '1')
insert into @T1 values(2, '20010102', '1')
insert into @T1 values(3, '20010103', '1')
insert into @T2 values(10, '20010101', '2')
insert into @T2 values(20, '20010102', '2')
insert into @T2 values(30, '20010103', '2')
;with cte1 as
(
select *,
row_number() over(order by ReceivedDate desc) as rn
from @T1
where [type] = '1'
),
cte2 as
(
select *,
row_number() over(order by ReceivedDate desc) as rn
from @T2
where [type] = '2'
)
select *
from cte1
where rn <= 2
union all
select *
from cte2
where rn <= 2
For Java 7 you can use try-with-resource for more compact code:
private static boolean available(int port) {
try (Socket ignored = new Socket("localhost", port)) {
return false;
} catch (IOException ignored) {
return true;
}
}
KEYS command should not be used on Redis production instances if you have a lot of keys, since it may block the Redis event loop for several seconds.
I would generate a dump (bgsave), and then use the following Python package to parse it and extract the data:
https://github.com/sripathikrishnan/redis-rdb-tools
You can have json output, or customize your own output in Python.
"...by a class and a div."
I assume when you say "div" you mean "id"? Try this:
$('#test2.test1').prop('checked', true);
No need to muck about with your [attributename=value]
style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".
Or more generally to select an input where you want to specify a multiple attribute selector:
$('input:radio[class=test1][id=test2]').prop('checked', true);
That is, list each attribute with its own square brackets.
Note that unless you have a pretty old version of jQuery you should use .prop()
rather than .attr()
for this purpose.
Here is a solution which requires no additional libraries and is very fast. This was found from: https://nedbatchelder.com/blog/200712/extracting_jpgs_from_pdfs.html# I have added the code in a function to make it more convenient.
def convert(filepath):
with open(filepath, "rb") as file:
pdf = file.read()
startmark = b"\xff\xd8"
startfix = 0
endmark = b"\xff\xd9"
endfix = 2
i = 0
njpg = 0
while True:
istream = pdf.find(b"stream", i)
if istream < 0:
break
istart = pdf.find(startmark, istream, istream + 20)
if istart < 0:
i = istream + 20
continue
iend = pdf.find(b"endstream", istart)
if iend < 0:
raise Exception("Didn't find end of stream!")
iend = pdf.find(endmark, iend - 20)
if iend < 0:
raise Exception("Didn't find end of JPG!")
istart += startfix
iend += endfix
jpg = pdf[istart:iend]
newfile = "{}jpg".format(filepath[:-3])
with open(newfile, "wb") as jpgfile:
jpgfile.write(jpg)
njpg += 1
i = iend
return newfile
Call convert with the pdf path as the argument and the function will create a .jpg file in the same directory
The Array.prototype
property represents the prototype for the Array
constructor and allows you to add new properties
and methods
to all Array
objects. we can create a prototype for this purpose
Array.prototype.has_element = function(element) {
return $.inArray( element, this) !== -1;
};
And then use it like this
var numbers= [1, 2, 3, 4];
numbers.has_element(3) => true
numbers.has_element(10) => false
See the Demo below
Array.prototype.has_element = function(element) {_x000D_
return $.inArray(element, this) !== -1;_x000D_
};_x000D_
_x000D_
_x000D_
_x000D_
var numbers = [1, 2, 3, 4];_x000D_
console.log(numbers.has_element(3));_x000D_
console.log(numbers.has_element(10));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
As @CQ says, you need to use HttpUtility.HtmlDecode, but it's not available in a non-ASP .NET project by default.
For a non-ASP .NET application, you need to add a reference to System.Web.dll
. Right-click your project in Solution Explorer, select "Add Reference", then browse the list for System.Web.dll
.
Now that the reference is added, you should be able to access the method using the fully-qualified name System.Web.HttpUtility.HtmlDecode
or insert a using
statement for System.Web
to make things easier.
It's called a shebang. In unix-speak, # is called sharp (like in music) or hash (like hashtags on twitter), and ! is called bang. (You can actually reference your previous shell command with !!, called bang-bang). So when put together, you get haSH-BANG, or shebang.
The part after the #! tells Unix what program to use to run it. If it isn't specified, it will try with bash (or sh, or zsh, or whatever your $SHELL variable is) but if it's there it will use that program. Plus, # is a comment in most languages, so the line gets ignored in the subsequent execution.
You can do the following steps:
First isolate the column (by inserting a blank column before and/or after the column you want to count the unique values if there are any adjacent columns;
Then select the whole column, go to 'Data' > 'Advanced Filter' and check the checkbox 'Unique records only'. This will hide all non-unique records so you can count the unique ones by selecting the whole column.
For install with zsh and Homebrew:
brew install nvm
Then Add the following to ~/.zshrc or your desired shell configuration file:
export NVM_DIR="$HOME/.nvm"
. "/usr/local/opt/nvm/nvm.sh"
Then install a node version and use it.
nvm install 7.10.1
nvm use 7.10.1
Blob datatypes stores binary objects like images while text datatypes stores text objects like articles of webpages
public List<ItemCustom2> GetBrandListByCat(int id)
{
var OBJ = (from a in db.Items
join b in db.Brands on a.BrandId equals b.Id into abc1
where (a.ItemCategoryId == id)
from b in abc1.DefaultIfEmpty()
select new
{
ItemCategoryId = a.ItemCategoryId,
Brand_Name = b.Name,
Brand_Id = b.Id,
Brand_Pic = b.Pic,
}).Distinct();
List<ItemCustom2> ob = new List<ItemCustom2>();
foreach (var item in OBJ)
{
ItemCustom2 abc = new ItemCustom2();
abc.CategoryId = item.ItemCategoryId;
abc.BrandId = item.Brand_Id;
abc.BrandName = item.Brand_Name;
abc.BrandPic = item.Brand_Pic;
ob.Add(abc);
}
return ob;
}
I use the following object:
function Padder(len, pad) {
if (len === undefined) {
len = 1;
} else if (pad === undefined) {
pad = '0';
}
var pads = '';
while (pads.length < len) {
pads += pad;
}
this.pad = function (what) {
var s = what.toString();
return pads.substring(0, pads.length - s.length) + s;
};
}
With it you can easily define different "paddings":
var zero4 = new Padder(4);
zero4.pad(12); // "0012"
zero4.pad(12345); // "12345"
zero4.pad("xx"); // "00xx"
var x3 = new Padder(3, "x");
x3.pad(12); // "x12"
ROW_NUMBER : Returns a unique number for each row starting with 1. For rows that have duplicate values,numbers are arbitarily assigned.
Rank : Assigns a unique number for each row starting with 1,except for rows that have duplicate values,in which case the same ranking is assigned and a gap appears in the sequence for each duplicate ranking.
$foobar = new foobar;
put the class foobar in $foobar, not the object. To get the object, you need to add parenthesis: $foobar = new foobar();
Your error is simply that you call a method on a class, so there is no $this
since $this
only exists in objects.
You can change the color of EditText programmatically just using this line of code easily:
edittext.setBackgroundTintList(ColorStateList.valueOf(yourcolor));
The official way to set the disabled
attribute on an HTMLInputElement
is this:
var input = document.querySelector('[name="myButton"]');
// Without querySelector API
// var input = document.getElementsByName('myButton').item(0);
// disable
input.setAttribute('disabled', true);
// enable
input.removeAttribute('disabled');
While @kaushar's answer is sufficient for enabling and disabling an HTMLInputElement
, and is probably preferable for cross-browser compatibility due to IE's historically buggy setAttribute
, it only works because Element
properties shadow Element
attributes. If a property is set, then the DOM uses the value of the property by default rather than the value of the equivalent attribute.
There is a very important difference between properties and attributes. An example of a true HTMLInputElement
property is input.value
, and below demonstrates how shadowing works:
var input = document.querySelector('#test');_x000D_
_x000D_
// the attribute works as expected_x000D_
console.log('old attribute:', input.getAttribute('value'));_x000D_
// the property is equal to the attribute when the property is not explicitly set_x000D_
console.log('old property:', input.value);_x000D_
_x000D_
// change the input's value property_x000D_
input.value = "My New Value";_x000D_
_x000D_
// the attribute remains there because it still exists in the DOM markup_x000D_
console.log('new attribute:', input.getAttribute('value'));_x000D_
// but the property is equal to the set value due to the shadowing effect_x000D_
console.log('new property:', input.value);
_x000D_
<input id="test" type="text" value="Hello World" />
_x000D_
That is what it means to say that properties shadow attributes. This concept also applies to inherited properties on the prototype
chain:
function Parent() {_x000D_
this.property = 'ParentInstance';_x000D_
}_x000D_
_x000D_
Parent.prototype.property = 'ParentPrototype';_x000D_
_x000D_
// ES5 inheritance_x000D_
Child.prototype = Object.create(Parent.prototype);_x000D_
Child.prototype.constructor = Child;_x000D_
_x000D_
function Child() {_x000D_
// ES5 super()_x000D_
Parent.call(this);_x000D_
_x000D_
this.property = 'ChildInstance';_x000D_
}_x000D_
_x000D_
Child.prototype.property = 'ChildPrototype';_x000D_
_x000D_
logChain('new Parent()');_x000D_
_x000D_
log('-------------------------------');_x000D_
logChain('Object.create(Parent.prototype)');_x000D_
_x000D_
log('-----------');_x000D_
logChain('new Child()');_x000D_
_x000D_
log('------------------------------');_x000D_
logChain('Object.create(Child.prototype)');_x000D_
_x000D_
// below is for demonstration purposes_x000D_
// don't ever actually use document.write(), eval(), or access __proto___x000D_
function log(value) {_x000D_
document.write(`<pre>${value}</pre>`);_x000D_
}_x000D_
_x000D_
function logChain(code) {_x000D_
log(code);_x000D_
_x000D_
var object = eval(code);_x000D_
_x000D_
do {_x000D_
log(`${object.constructor.name} ${object instanceof object.constructor ? 'instance' : 'prototype'} property: ${JSON.stringify(object.property)}`);_x000D_
_x000D_
object = object.__proto__;_x000D_
} while (object !== null);_x000D_
}
_x000D_
I hope this clarifies any confusion about the difference between properties and attributes.
As far as I know, this is a work-in-progress. They want to do it, but it's not released yet. See 1377 (the "new" 495 that was mentioned by @Andy).
I ended up implementing the "generate .yml as part of CI" approach as proposed by @Thomas.
Contrary to what pointy says, the blur()
method does exist and is a part of the w3c standard. The following exaple will work in every modern browser (including IE):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Javascript test</title>
<script type="text/javascript" language="javascript">
window.onload = function()
{
var field = document.getElementById("field");
var link = document.getElementById("link");
var output = document.getElementById("output");
field.onfocus = function() { output.innerHTML += "<br/>field.onfocus()"; };
field.onblur = function() { output.innerHTML += "<br/>field.onblur()"; };
link.onmouseover = function() { field.blur(); };
};
</script>
</head>
<body>
<form name="MyForm">
<input type="text" name="field" id="field" />
<a href="javascript:void(0);" id="link">Blur field on hover</a>
<div id="output"></div>
</form>
</body>
</html>
Note that I used link.onmouseover
instead of link.onclick
, because otherwise the click itself would have removed the focus.
I built an extension called Checkpoints, an alternative to Local History. Checkpoints has support for viewing history for all files (that has checkpoints) in the tree view, not just the currently active file. There are some other minor differences aswell, but overall they are pretty similar.
map
may be microscopically faster in some cases (when you're NOT making a lambda for the purpose, but using the same function in map and a listcomp). List comprehensions may be faster in other cases and most (not all) pythonistas consider them more direct and clearer.
An example of the tiny speed advantage of map when using exactly the same function:
$ python -mtimeit -s'xs=range(10)' 'map(hex, xs)'
100000 loops, best of 3: 4.86 usec per loop
$ python -mtimeit -s'xs=range(10)' '[hex(x) for x in xs]'
100000 loops, best of 3: 5.58 usec per loop
An example of how performance comparison gets completely reversed when map needs a lambda:
$ python -mtimeit -s'xs=range(10)' 'map(lambda x: x+2, xs)'
100000 loops, best of 3: 4.24 usec per loop
$ python -mtimeit -s'xs=range(10)' '[x+2 for x in xs]'
100000 loops, best of 3: 2.32 usec per loop
If you are allowed to run real native binaries, then this is your compiler:
https://github.com/ircmaxell/php-compiler
It's a PHP compiler written in PHP!
It compiles PHP code to its own VM code. This VM code can then either be interpreted by its own interpreter (also written in PHP, isn't that crazy?) or it can be translated to Bitcode. And using the LLVM compiler framework (clang
and co), this Bitcode can be compiled into a native binary for any platform that LLVM supports (pretty much any platform that matters today). You can choose to either do that statically or each time just before the code is executed (JIT style). So the only two requirements for this compiler to work on your system is an installed PHP interpreter and an installed clang
compiler.
If you are not allowed to run native binaries, you could use the compiler above as an interpreter and let it interpret its own VM code, yet this will be slow as you are running a PHP interpreter that itself is running on a PHP engine, so you have a "double interpretation".
See this answer; in Chrome and Safari you can use the following style to disable the default dragging:
-webkit-user-drag: auto | element | none;
You could try user-select for Firefox and IE(10+):
-moz-user-select: none | text | all | element
-ms-user-select: none | text | all | element
$("input#myId").bind('keyup', function (e) {
// Do Stuff
});
working in both IE and chrome
http://dl.google.com/android/ndk/android-ndk-r9d-linux-x86_64.tar.bz2
I successfully opened gstreamer SDK tutorials in Eclipse.
All I needed is to use an older version of ndk. specificly 9d.
(10c and 10d does not work, 10b - works just for tutorial-1 )
9d does work for all tutorials ! and you can:
Download it from: http://dl.google.com/android/ndk/android-ndk-r9d-linux-x86_64.tar.bz2
Extract it.
set it in eclipse->window->preferences->Android->NDK->NDK location.
build - (ctrl+b).
Something very similar can be seen on http://goo.gl when you shorten the URL.
There is a readonly input element that gets programmatically focused, with tooltip press CTRL-C to copy.
When you hit that shortcut, the input content effectively gets into the clipboard. Really nice :)
I've had this error crop up on me before, even in Visual Studio 2008. It came back and more prevalent in Visual Studio 2012.
Here is what I do.
Paste this in the troublesome project's pre-build event:
if exist "$(TargetPath).locked" del "$(TargetPath).locked"
if exist "$(TargetPath)" if not exist "$(TargetPath).locked" move "$(TargetPath)" "$(TargetPath).locked"
I notice others have given the non-lambda syntax so just to have this complete I'll put in the lambda syntax equivalent:
Non-lambda (as per James's post):
var name = from i in DataContext.MyTable
where i.ID == 0
select i.Name
Equivalent lambda syntax:
var name = DataContext.MyTable.Where(i => i.ID == 0)
.Select(i => new { Name = i.Name });
There's not really much practical difference, just personal opinion on which you prefer.
Remove all widths set using CSS and set white-space to nowrap like so:
.content-loader tr td {
white-space: nowrap;
}
I would also remove the fixed width from the container (or add overflow-x: scroll
to the container) if you want the fields to display in their entirety without it looking odd...
See more here: http://www.w3schools.com/cssref/pr_text_white-space.asp
No data was received to import. Either no file name was submitted, or the file size exceeded the maximum size permitted by your PHP configuration. See FAQ 1.16.
These are my upload settings from php.iniupload_tmp_dir = "D:\xampp\xampp\tmp" ;//set these for temp file storing
; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 10M ;//change it according to max file upload size
I am sure your problem will be short out using this instructions.
upload_tmp_dir = "D:\xampp\xampp\tmp"
Here you can set any directory that can hold temp file, I have installed in D: drive xampp so I set it "D:\xampp\xampp\tmp".
Refer to here
write query with named parameter, use simple ListPreparedStatementSetter
with all parameters in sequence. Just add below snippet to convert the query in traditional form based to available parameters,
ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(namedSql);
List<Integer> parameters = new ArrayList<Integer>();
for (A a : paramBeans)
parameters.add(a.getId());
MapSqlParameterSource parameterSource = new MapSqlParameterSource();
parameterSource.addValue("placeholder1", parameters);
// create SQL with ?'s
String sql = NamedParameterUtils.substituteNamedParameters(parsedSql, parameterSource);
return sql;
You can declare trk by the following ways : - either
trk : [{
lat : String,
lng : String
}]
or
trk : { type : Array , "default" : [] }
In the second case during insertion make the object and push it into the array like
db.update({'Searching criteria goes here'},
{
$push : {
trk : {
"lat": 50.3293714,
"lng": 6.9389939
} //inserted data is the object to be inserted
}
});
or you can set the Array of object by
db.update ({'seraching criteria goes here ' },
{
$set : {
trk : [ {
"lat": 50.3293714,
"lng": 6.9389939
},
{
"lat": 50.3293284,
"lng": 6.9389634
}
]//'inserted Array containing the list of object'
}
});
this is what it worked for me:
select * from table
where column
BETWEEN STR_TO_DATE('29/01/15', '%d/%m/%Y')
AND STR_TO_DATE('07/10/15', '%d/%m/%Y')
Please, note that I had to change STR_TO_DATE(column, '%d/%m/%Y') from previous solutions, as it was taking ages to load
There's also the MySQL FIELD
function.
If you want complete sorting for all possible values:
SELECT id, name, priority
FROM mytable
ORDER BY FIELD(name, "core", "board", "other")
If you only care that "core" is first and the other values don't matter:
SELECT id, name, priority
FROM mytable
ORDER BY FIELD(name, "core") DESC
If you want to sort by "core" first, and the other fields in normal sort order:
SELECT id, name, priority
FROM mytable
ORDER BY FIELD(name, "core") DESC, priority
There are some caveats here, though:
First, I'm pretty sure this is mysql-only functionality - the question is tagged mysql, but you never know.
Second, pay attention to how FIELD()
works: it returns the one-based index of the value - in the case of FIELD(priority, "core")
, it'll return 1 if "core" is the value. If the value of the field is not in the list, it returns zero. This is why DESC
is necessary unless you specify all possible values.
No, browsers don't provide this formatting option.
You could probably fake it with some checkboxes with <label>
s, and JS to turn it into a fly out menu.
Emacs takes many launch options. The one that you are looking for is
emacs -nw
. This will open Emacs inside the terminal disregarding the DISPLAY environment variable even if it is set.
The long form of this flag is emacs --no-window-system
.
More information about Emacs launch options can be found in the manual.
I would use a listener. Fragment1 calling the listener (main activity)
I realise that this is an old thread but one option is just to remove the http: part from the image URL so that 'http://some/image.jpg' becomes '//some/image.jpg'. This will also work with CDNs
To allow user ec2-user
(Amazon AWS) write access to the public web directory (/var/www/html),
enter this command via Putty or Terminal, as the root user sudo
:
chown -R ec2-user /var/www/html
Make sure permissions on that entire folder were correct:
chmod -R 755 /var/www/html
Doc's:
Setting up amazon ec2-instances
Connect to Amazon EC2 file directory using Filezilla and SFTP (Video)
I was able to solve a similar problem like this:
The only disadvantage is that you have to re-import all your projects.
Try this: Set the toolbar's theme in your layout as follows
android:theme = "@android:style/ThemeOverlay.Material.Dark.ActionBar"
If you want further information
The curious case of the Overflow Icon Color by Martin Bonnin
Vertex *f=(findvertex(from));
if(!f) {
cerr << "vertex not found" << endl;
exit(1) // or return;
}
Because findVertex
can return NULL
if it can't find the vertex.
Otherwise this f->adj;
is trying to do
NULL->adj;
Which causes access violation.
I had this problem. The solution was to allow node.js through the server's firewall.
Without VBA...
If you can use a helper column, you can use the MATCH
function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match
To simply identify duplicates, use a helper column
Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:
=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")
Drag/copy this forumla down, and it should identify the duplicates.
To highlight cells, use conditional formatting:
With some tinkering, you can use this MATCH
function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.
Something like:
=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))
For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:
=B1="Duplicate"
This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.
I'm using the following in a utility class:
public static String lastNUriPathPartsOf(final String uri, final int n, final String... ellipsis)
throws URISyntaxException {
return lastNUriPathPartsOf(new URI(uri), n, ellipsis);
}
public static String lastNUriPathPartsOf(final URI uri, final int n, final String... ellipsis) {
return uri.toString().contains("/")
? (ellipsis.length == 0 ? "..." : ellipsis[0])
+ uri.toString().substring(StringUtils.lastOrdinalIndexOf(uri.toString(), "/", n))
: uri.toString();
}
I'm using get-json very simple to use:
$ npm install get-json --save
Import get-json
var getJSON = require('get-json')
To do a GET
request you would do something like:
getJSON('http://api.listenparadise.org', function(error, response){
console.log(response);
})
using javascript you can send the generated pdf to a new window using the following code.
var string = doc.output('datauristring');
var iframe = "<iframe width='100%' height='100%' src='" + string + "'></iframe>"
var x = window.open();
x.document.open();
x.document.write(iframe);
x.document.close();
This will also work:
<Hyperlink Command="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl},
Path=DataContext.AllowItemCommand}" />
ListView
will inherit its DataContext
from Window
, so it's available at this point, too.
And since ListView
, just like similar controls (e. g. Gridview
, ListBox
, etc.), is a subclass of ItemsControl
, the Binding
for such controls will work perfectly.
Here are two extension methods you can use. They ensure any existing classes are preserved and do not duplicate classes being added.
public static void RemoveCssClass(this WebControl control, String css) {
control.CssClass = String.Join(" ", control.CssClass.Split(' ').Where(x => x != css).ToArray());
}
public static void AddCssClass(this WebControl control, String css) {
control.RemoveCssClass(css);
css += " " + control.CssClass;
control.CssClass = css;
}
Usage: hlCreateNew.AddCssClass("disabled");
Usage: hlCreateNew.RemoveCssClass("disabled");
In computer networking, localhost (meaning "this computer") is the standard hostname given to the address of the loopback network interface.
Localhost always translates to the loopback IP address 127.0.0.1 in IPv4.
It is also used instead of the hostname of a computer. For example, directing a web browser installed on a system running an HTTP server to http://localhost will display the home page of the local web site.
Source: Wikipedia - Localhost.
The :80
part is the TCP port. You can consider these ports as communications endpoints on a particular IP address (in the case of localhost - 127.0.0.1). The IANA is responsible for maintaining the official assignments of standard port numbers for specific services. Port 80 happens to be the standard port for HTTP.
Actually you should define your styles in res/values/styles.xml
. I guess now you've got the following configuration:
<style name="AppBaseTheme" parent="android:Theme.Holo.Light"/>
<style name="AppTheme" parent="AppBaseTheme"/>
so if you want to use Theme.Black then change AppBaseTheme parent to android:Theme.Black
or you could change app style directly in manifest file like this - android:theme="@android:style/Theme.Black"
. You must be lacking android namespace before style tag.
You can read more about styles and themes here.
Use the createFromFormat
method:
$start_date = DateTime::createFromFormat("U", $dbResult->db_timestamp);
UPDATE
I now recommend the use of Carbon
I had the same problem but I solved in other way (becouse at right click on project folder no Maven tab apears only if I do that on pom.xml I can see a Maven tab):
So I tink that you get that error because the IDE (Eclipse) didn`t import the dependecies from Maven. Since you are using Spring framework and you probably have STS allready installed right-click on project folder Spring Tools -> Update Maven Dependecies.
I`m using Eclipse JUNO m2eclipse 1.3.0 Spring IDEE 3.1
The name of the array indicates the starting address. Starting address of both namet2
and nameIt2
are different. So the equal to (==
) operator checks whether the addresses are the same or not. For comparing two strings, a better way is to use strcmp()
, or we can compare character by character using a loop.
Libraries cannot be directly used in any program if not properly added to the project gradle files.
This can easily be done in smart IDEs like inteli J.
1) First as a convention add a folder names 'libs' under your project src file. (this can easily be done using the IDE itself)
2) then copy or add your library file (eg: .jar file) to the folder named 'libs'
3) now you can see the library file inside the libs folder. Now right click on the file and select 'add as library'. And this will fix all the relevant files in your program and library will be directly available for your use.
Please note:
Whenever you are adding libraries to a project, make sure that the project supports the library
Since we know that i
is an int
, you can just go ahead and unsigneding it!
This would do the trick:
int i = -62;
unsigned int j = unsigned(i);
This piece of code will return the value of the data attributes eg: data-id, data-time, data-name etc.., I have shown for the id
<a href="#" id="click-demo" data-id="a1">Click</a>
js:
$(this).data("id");
// get the value of the data-id -> a1
$(this).data("id", "a2");
// this will change the data-id -> a2
$(this).data("id");
// get the value of the data-id -> a2
Leave you stuff there and Try the following as well:
Start > Right-click on My computer > Properties > Advanced system settings > Environment Variables > look for variable name called "Path" in the lower box
set path value value as: (you can just add it to the starting of line, don't forgot semi column in between )
c:\Program Files\java\jre7\bin
HTML controls the semantic meaning of the elements. CSS controls the layout/style of the page. Use CSS when you are controlling your layout.
In short, never use size=""
Old question but anyway !
Same thing happen to me this morning, everything was working fine for weeks before...... yes guess what ... I change my windows PC user account password yesterday night !!!!! (how stupid was I !!!)
So easy fix : IIS -> authentication -> Anonymous authentication -> edit and set the user and new PASSWORD !!!!!
int? is Nullable.
For simulating keyboard events in Chrome:
There is a related bug in webkit that keyboard events when initialized with initKeyboardEvent get an incorrect keyCode and charCode of 0: https://bugs.webkit.org/show_bug.cgi?id=16735
A working solution for it is posted in this SO answer.
Basically both ref
and out
for passing object/value between methods
The out keyword causes arguments to be passed by reference. This is like the ref keyword, except that ref requires that the variable be initialized before it is passed.
out
: Argument is not initialized and it must be initialized in the method
ref
: Argument is already initialized and it can be read and updated in the method.
What is the use of “ref” for reference-types ?
You can change the given reference to a different instance.
Did you know?
Although the ref and out keywords cause different run-time behavior, they are not considered part of the method signature at compile time. Therefore, methods cannot be overloaded if the only difference is that one method takes a ref argument and the other takes an out argument.
You can't use the ref and out keywords for the following kinds of methods:
Properties are not variables and therefore cannot be passed as out parameters.
43 is the dec ascii number for the "+" symbol. That explains why you get a 43 back. http://en.wikipedia.org/wiki/ASCII
In TensorFlow Core v2.3.0, the following code should work.
import tensorflow as tf
visible_devices = tf.config.get_visible_devices()
for devices in visible_devices:
print(devices)
Depending on your environment, this code will produce flowing results.
PhysicalDevice(name='/physical_device:CPU:0', device_type='CPU') PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')
In general, one doesn't expand out log(a + b)
; you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:
log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)
(In fact, this identity is often used when implementing log
in math libraries).
use DataTable object instead:
private void doMore(DataTable dt)
{
foreach(DataColumn dc in dt.Columns)
{
MessageBox.Show(dc.ColumnName);
}
}
The input shape you have defined is the shape of a single sample. The model itself expects some array of samples as input (even if its an array of length 1).
Your output really should be 4-d, with the 1st dimension to enumerate the samples. i.e. for a single image you should return a shape of (1, 32, 32, 3).
You can find more information here under "Convolution2D"/"Input shape"
Edit: Based on Danny's comment below, if you want a batch size of 1, you can add the missing dimension using this:
image = np.expand_dims(image, axis=0)
That for changing directory of the XAMPP. So you have to change the Directory as well as ServerRoot "E:/xampp/apache"
DocumentRoot "E:/xampp/htdocs"
<Directory "E:/xampp/htdocs">
ScriptAlias /cgi-bin/ "E:/xampp/cgi-bin/"
<Directory "E:/xampp/cgi-bin">
AllowOverride All
Options None
Require all granted
</Directory>
I also facing same problem for changing My laptop. thanks
The specific format is:
git commit --author="John Doe <[email protected]>" -m "Impersonation is evil."
To convert a
Kotlin
source file to aJava
source file you need to (when you in Android Studio):
Press Cmd-Shift-A on a Mac, or press Ctrl-Shift-A on a Windows machine.
Type the action you're looking for: Kotlin Bytecode
and choose Show Kotlin Bytecode
from menu.
Decompile
button on the top of Kotlin Bytecode
panel.$sidemenu
is not an object
, so you can't call methods on it. It is probably not being sent to your view
, or $sidemenus
is empty.
You cant simply (directly) convert the datareader to list.
You have to loop through all the elements in datareader and insert into list
below the sample code
using (drOutput)
{
System.Collections.Generic.List<CustomerEntity > arrObjects = new System.Collections.Generic.List<CustomerEntity >();
int customerId = drOutput.GetOrdinal("customerId ");
int CustomerName = drOutput.GetOrdinal("CustomerName ");
while (drOutput.Read())
{
CustomerEntity obj=new CustomerEntity ();
obj.customerId = (drOutput[customerId ] != Convert.DBNull) ? drOutput[customerId ].ToString() : null;
obj.CustomerName = (drOutput[CustomerName ] != Convert.DBNull) ? drOutput[CustomerName ].ToString() : null;
arrObjects .Add(obj);
}
}
This is pretty old, but I found following worth noting:
PS N:\> (measure-command {Get-WmiObject -Class Win32_LogicalDisk|select -property deviceid|%{$_.deviceid}|out-host}).totalmilliseconds
...
928.7403
PS N:\> (measure-command {gdr -psprovider 'filesystem'|%{$_.name}|out-host}).totalmilliseconds
...
169.474
Without filtering properties, on my test system, 4319.4196ms to 1777.7237ms. Unless I need a PS-Drive object returned, I'll stick with WMI.
EDIT: I think we have a winner: PS N:> (measure-command {[System.IO.DriveInfo]::getdrives()|%{$_.name}|out-host}).to??talmilliseconds 110.9819
Here is an example to play with Inline SVG for a list bullet (2020 Browsers)
list-style-image: url("data:image/svg+xml,
<svg width='50' height='50'
xmlns='http://www.w3.org/2000/svg'
viewBox='0 0 72 72'>
<rect width='100%' height='100%' fill='pink'/>
<path d='M70 42a3 3 90 0 1 3 3a3 3 90 0 1-3 3h-12l-3 3l-6 15l-3
l-6-3v-21v-3l15-15a3 3 90 0 1 0 0c3 0 3 0 3 3l-6 12h30
m-54 24v-24h9v24z'/></svg>")
width
& height
to set the sizeM70 42
to position the handrect
li{
font-size:2em;
list-style-image: url("data:image/svg+xml,<svg width='3em' height='3em' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 72 72'><rect width='100%' height='100%' fill='pink'/><path d='M70 42a3 3 90 0 1 3 3a3 3 90 0 1-3 3h-12l-3 3l-6 15l-3 3h-12l-6-3v-21v-3l15-15a3 3 90 0 1 0 0c3 0 3 0 3 3l-6 12h30m-54 24v-24h9v24z'/></svg>");
}
span{
display:inline-block;
vertical-align:top;
margin-top:-10px;
margin-left:-5px;
}
_x000D_
<ul>
<li><span>Apples</span></li>
<li><span>Bananas</span></li>
<li>Oranges</li>
</ul>
_x000D_
Agile is the practice and Scrum is the process to following this practice same as eXtreme Programming (XP) and Kanban are the alternative process to following Agile development practice.
Use http://[jenkins-server]/exit
This page shows how to use URL commands.
Following @Aravind's answer with more details
@RequestMapping("/myPath.htm")
public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception{
myServiceMethodSettingCookie(request, response); //Do service call passing the response
return new ModelAndView("CustomerAddView");
}
// service method
void myServiceMethodSettingCookie(HttpServletRequest request, HttpServletResponse response){
final String cookieName = "my_cool_cookie";
final String cookieValue = "my cool value here !"; // you could assign it some encoded value
final Boolean useSecureCookie = false;
final int expiryTime = 60 * 60 * 24; // 24h in seconds
final String cookiePath = "/";
Cookie cookie = new Cookie(cookieName, cookieValue);
cookie.setSecure(useSecureCookie); // determines whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL
cookie.setMaxAge(expiryTime); // A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.
cookie.setPath(cookiePath); // The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories
response.addCookie(cookie);
}
Related docs:
http://docs.oracle.com/javaee/7/api/javax/servlet/http/Cookie.html
http://docs.spring.io/spring-security/site/docs/3.0.x/reference/springsecurity.html
I had a similar problem, caused by not installing the C++ compiler. In my case I was compiling .cpp files for a Python extension, but the compiler is first invoked as c:\mingw\bin\gcc.exe.
Internally, gcc.exe would notice it was asked to compile a .cpp file. It would try to call g++.exe and fail with the same error message:
gcc.exe: CreateProcess: no such file or directory
you can use enumerate keeping the ind/index of the elements is in vm, if you make vm
a set you will also have 0(1)
lookups:
vm = {-1, -1, -1, -1}
print([ind if q in vm else 9999 for ind,ele in enumerate(vm) ])
Use git rebase
. Specifically:
git stash
to store the changes you want to add.git rebase -i HEAD~10
(or however many commits back you want to see).a0865...
) for edit by changing the word pick
at the start of the line into edit
. Don't delete the other lines as that would delete the commits.[^vimnote]git stash pop
git add <file>
.git commit --amend --no-edit
.git rebase --continue
which will rewrite the rest of your commits against the new one.[^vimnote]: If you are using vim
then you will have to hit the Insert key to edit, then Esc and type in :wq
to save the file, quit the editor, and apply the changes. Alternatively, you can configure a user-friendly git commit editor with git config --global core.editor "nano"
.
A use case for it when you want to use a table with *ngIf and *ngFor - As putting a div in td/th will make the table element misbehave -. I faced this problem and that was the answer.
Wrap your column in this code.
ISNULL(Yourcolumn, 0)
Maybe check why you are getting nulls
Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):
Sub Module for Connecting to MS SQL with Remote Host & Username/Password
Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String
'Setup the connection string for accessing MS SQL database
'Make sure to change:
'1: PASSWORD
'2: USERNAME
'3: REMOTE_IP_ADDRESS
'4: DATABASE
ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"
'Opens connection to the database
cnn.Open ConnectionString
'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
cnn.CommandTimeout = 900
'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
StrQuery = "SELECT TOP 10 * FROM tbl_table"
'Performs the actual query
rst.Open StrQuery, cnn
'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
Sheets(1).Range("A2").CopyFromRecordset rst
End Sub
You can't specify the width of an element with display inline. You could put something in it like a non-breaking space ( ) and then set the padding to give it some more width but you can't control it directly.
You could use display inline-block but that isn't widely supported.
A real hack would be to put an image inside and then set the width of that. Something like a transparent 1 pixel GIF. Not the recommended approach however.
This my extension, this is an example of change image with FadIn and FadOut :
fun ImageView.setImageDrawableWithAnimation(@DrawableRes() resId: Int, duration: Long = 300) {
if (drawable != null) {
animate()
.alpha(0f)
.setDuration(duration)
.withEndAction {
setImageResource(resId)
animate()
.alpha(1f)
.setDuration(duration)
}
} else if (drawable == null) {
setAlpha(0f)
setImageResource(resId)
animate()
.alpha(1f)
.setDuration(duration)
}
}
The error you posted can happen when you're using a clause in the GROUP BY statement without including it in the select.
Example
This one works!
SELECT t.device,
SUM(case when transits.direction = 1 then 1 else 0 end) ,
SUM(case when transits.direction = 0 then 1 else 0 end) from t1 t
where t.device in ('A','B') group by t.device
This one not (omitted t.device from the select)
SELECT
SUM(case when transits.direction = 1 then 1 else 0 end) ,
SUM(case when transits.direction = 0 then 1 else 0 end) from t1 t
where t.device in ('A','B') group by t.device
This will produce your error complaining that I'm grouping for something that is not included in the select
Please, provide all the query to get more support.
File mode, write and binary. Since you are writing a .jpg file, it looks fine.
But if you supposed to read that jpg file you need to use 'rb'
More info
On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files.
Since you tagged this with strtotime, you can use it with the +1 day
modifier like so:
$tomorrow_timestamp = strtotime('+1 day', strtotime('2013-01-22'));
That said, it's a much better solution to use DateTime.
You don't need the into statements:
var query =
from customer in dc.Customers
from order in dc.Orders
.Where(o => customer.CustomerId == o.CustomerId)
.DefaultIfEmpty()
select new { Customer = customer, Order = order }
//Order will be null if the left join is null
And yes, the query above does indeed create a LEFT OUTER join.
Link to a similar question that handles multiple left joins: Linq to Sql: Multiple left outer joins
You need to import the FormsModule
, ReactiveFormsModule
in this module as well as the top level.
If you used a reactiveForm
in another module then you've to do also this step along with above step: import also reactiveFormsModule
in that particular module.
For example:
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
AppRoutingModule,
HttpClientModule,
BrowserAnimationsModule
],
You don't have to track whether you've already changed the character from upper to lower. Your code is already doing that since it's basically:
1 for each character x:
2 if x is uppercase:
3 convert x to lowercase
4 else:
5 if x is lowercase:
6 convert x to uppercase.
The fact that you have that else
in there (on line 4) means that a character that was initially uppercase will never be checked in the second if
statement (on line 5).
Example, start with A
. Because that's uppercase, it will be converted to lowercase on line
3 and then you'll go back up to line 1 for the next character.
If you start with z
, the if
on line 2 will send you directly to line 5 where it will be converted to uppercase. Anything that's neither upper nor lowercase will fail both if
statements and therefore remain untouched.
You can use .empty()
, like this:
$("#foo").empty();
Remove all child nodes of the set of matched elements from the DOM.
I use:
ps -ef | grep 786
Replace 786 with your PID or process name.
I use rst2pdf to create a pdf file, since I am more familiar with RST than with HTML. It supports embedding almost any kind of raster or vector images.
It requires reportlab, but I found reportlab is not so straight forward to use (at least for me).
Here's an example which issues the same warning:
import numpy as np
np.seterr(all='warn')
A = np.array([10])
a=A[-1]
a**a
yields
RuntimeWarning: overflow encountered in long_scalars
In the example above it happens because a
is of dtype int32
, and the maximim value storable in an int32
is 2**31-1. Since 10**10 > 2**32-1
, the exponentiation results in a number that is bigger than that which can be stored in an int32
.
Note that you can not rely on np.seterr(all='warn')
to catch all overflow
errors in numpy. For example, on 32-bit NumPy
>>> np.multiply.reduce(np.arange(21)+1)
-1195114496
while on 64-bit NumPy:
>>> np.multiply.reduce(np.arange(21)+1)
-4249290049419214848
Both fail without any warning, although it is also due to an overflow error. The correct answer is that 21! equals
In [47]: import math
In [48]: math.factorial(21)
Out[50]: 51090942171709440000L
According to numpy developer, Robert Kern,
Unlike true floating point errors (where the hardware FPU sets a flag whenever it does an atomic operation that overflows), we need to implement the integer overflow detection ourselves. We do it on the scalars, but not arrays because it would be too slow to implement for every atomic operation on arrays.
So the burden is on you to choose appropriate dtypes
so that no operation overflows.
A modern alternative:
const textToFind = 'Google';
const dd = document.getElementById ('MyDropDown');
dd.selectedIndex = [...dd.options].findIndex (option => option.text === textToFind);
var list = new List<string>();
var queryable = list.AsQueryable();
Add a reference to: System.Linq
From APUE, Section 5.14 :
char good_template[] = "/tmp/dirXXXXXX"; /* right way */
char *bad_template = "/tmp/dirXXXXXX"; /* wrong way*/
... For the first template, the name is allocated on the stack, because we use an array variable. For the second name, however, we use a pointer. In this case, only the memory for the pointer itself resides on the stack; the compiler arranges for the string to be stored in the read-only segment of the executable. When the
mkstemp
function tries to modify the string, a segmentation fault occurs.
The quoted text matches @Ciro Santilli 's explanation.
When the compiler sees add(3, 4)
it needs to know what that means. With the forward declaration you basically tell the compiler that add
is a function that takes two ints and returns an int. This is important information for the compiler becaus it needs to put 4 and 5 in the correct representation onto the stack and needs to know what type the thing returned by add is.
At that time, the compiler is not worried about the actual implementation of add
, ie where it is (or if there is even one) and if it compiles. That comes into view later, after compiling the source files when the linker is invoked.
The hard truth is: the only good debugger for IE is Visual Studio.
If you don't have money for the real deal, download free Visual Web Developer 2008 Express EditionVisual Web Developer 2010 Express Edition. While the former allows you to attach debugger to already running IE, the latter doesn't (at least previous versions I used didn't allow that). If this is still the case, the trick is to create a simple project with one empty web page, "run" it (it starts the browser), now navigate to whatever page you want to debug, and start debugging.
Microsoft gives away full Visual Studio on different events, usually with license restrictions, but they allow tinkering at home. Check their schedule and the list of freebies.
Another hint: try to debug your web application with other browsers first. I had a great success with Opera. Somehow Opera's emulation of IE and its bugs was pretty close, but the debugger is much better.
To install version 7+ of Babel run:
npm install -g @babel/cli
npm install -g @babel/core
\t
will match tabs, rather than spaces and should also be referred to with a double slash: \\t
. You could call s.split( " " )
but that wouldn't count consecutive spaces. By that I mean...
String bar = " ba jfjf jjj j ";
String[] split = bar.split( " " );
System.out.println( split.length ); // Returns 5
So, despite the fact there are seven space characters, there are only five blocks of space. It depends which you're trying to count, I guess.
Commons Lang is your friend for this one.
int count = StringUtils.countMatches( inputString, " " );
string foo = "Apple, Plum, Cherry";
string[] myArr = null;
myArr = foo.Split(',');
The answer is, "No."
What C programmers do is store the size of the array somewhere. It can be part of a structure, or the programmer can cheat a bit and malloc()
more memory than requested in order to store a length value before the start of the array.
There are many ways. A rather simple solution is to use a 2D vector.
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<vector<double>> val_and_id;
val_and_id.resize(5);
for (int i = 0; i < 5; i++) {
val_and_id[i].resize(2); // one to store value, the other for index.
}
// Store value in dimension 1, and index in the other:
// say values are 5,4,7,1,3.
val_and_id[0][0] = 5.0;
val_and_id[1][0] = 4.0;
val_and_id[2][0] = 7.0;
val_and_id[3][0] = 1.0;
val_and_id[4][0] = 3.0;
val_and_id[0][1] = 0.0;
val_and_id[1][1] = 1.0;
val_and_id[2][1] = 2.0;
val_and_id[3][1] = 3.0;
val_and_id[4][1] = 4.0;
sort(val_and_id.begin(), val_and_id.end());
// display them:
cout << "Index \t" << "Value \n";
for (int i = 0; i < 5; i++) {
cout << val_and_id[i][1] << "\t" << val_and_id[i][0] << "\n";
}
return 0;
}
Here is the output:
Index Value
3 1
4 3
1 4
0 5
2 7
getElementById
is defined by DOM Level 1 HTML to return null
in the case no element is matched.
!==null
is the most explicit form of the check, and probably the best, but there is no non-null
falsy value that getElementById
can return - you can only get null
or an always-truthy Element object. So there's no practical difference here between !==null
, !=null
or the looser if (document.getElementById('xx'))
.
if addition please, if you have a long text please you can use this css code bellow;
text-overflow: ellipsis;
overflow: visible;
white-space: nowrap;
make the whole line text visible.
Just call it and supply self
class A:
def m(self, x, y):
print(x+y)
class B:
def call_a(self):
A.m(self, 1, 2)
b = B()
b.call_a()
output: 3
The problem is that your PATH does not include the location of the node executable.
You can likely run node as "/usr/local/bin/node
".
You can add that location to your path by running the following command to add a single line to your bashrc file:
echo 'export PATH=$PATH:/usr/local/bin' >> $HOME/.bashrc
You are accessing the list elements and then using them to attempt to index your list. This is not a good idea. You already have an answer showing how you could use indexing to get your sum list, but another option would be to zip
the list with a slice of itself such that you can sum the pairs.
b = [i + j for i, j in zip(a, a[1:])]
You can find more information about the signing process on the official Android documentation here : http://developer.android.com/guide/publishing/app-signing.html
Yes, you can sign several applications with the same keystore. But you must remember one important thing : if you publish an app on the Play Store, you have to sign it with a non debug certificate. And if one day you want to publish an update for this app, the keystore used to sign the apk must be the same. Otherwise, you will not be able to post your update.
__main__.py
is used for python programs in zip files. The __main__.py
file will be executed when the zip file in run. For example, if the zip file was as such:
test.zip
__main__.py
and the contents of __main__.py
was
import sys
print "hello %s" % sys.argv[1]
Then if we were to run python test.zip world
we would get hello world
out.
So the __main__.py
file run when python is called on a zip file.
This also can happen if the device you are trying to run on has some older version of the provisioning profile you are using that points to an old, expired or revoked certificate or a certificate without associated private key. Delete any invalid Provisioning Profiles under your device section in Xcode organizer.
Ahh found the solution after trying for a couple of hours.
Assuming that you have a data frame called students
, you can select individual rows or columns using the bracket syntax, like this:
students[1,2]
would select row 1 and column 2, the result here would be a single cell.students[1,]
would select all of row 1, students[,2]
would select all of column 2.If you'd like to select multiple rows or columns, use a list of values, like this:
students[c(1,3,4),]
would select rows 1, 3 and 4, students[c("stu1", "stu2"),]
would select rows named stu1
and stu2
.Hope I could help.
You need the following code below. At a glance, this may look like any old code that I made up. However, what I did was look at the source code for http://grepcode.com/file/repo1.maven.org/maven2/mysql/mysql-connector-java/5.1.31/com/mysql/jdbc/PreparedStatement.java. Then after that, I carefully looked through the code of setString(int parameterIndex, String x) to find the characters which it escapes and customised this to my own class so that it can be used for the purposes that you need. After all, if this is the list of characters that Oracle escapes, then knowing this is really comforting security-wise. Maybe Oracle need a nudge to add a method similar to this one for the next major Java release.
public class SQLInjectionEscaper {
public static String escapeString(String x, boolean escapeDoubleQuotes) {
StringBuilder sBuilder = new StringBuilder(x.length() * 11/10);
int stringLength = x.length();
for (int i = 0; i < stringLength; ++i) {
char c = x.charAt(i);
switch (c) {
case 0: /* Must be escaped for 'mysql' */
sBuilder.append('\\');
sBuilder.append('0');
break;
case '\n': /* Must be escaped for logs */
sBuilder.append('\\');
sBuilder.append('n');
break;
case '\r':
sBuilder.append('\\');
sBuilder.append('r');
break;
case '\\':
sBuilder.append('\\');
sBuilder.append('\\');
break;
case '\'':
sBuilder.append('\\');
sBuilder.append('\'');
break;
case '"': /* Better safe than sorry */
if (escapeDoubleQuotes) {
sBuilder.append('\\');
}
sBuilder.append('"');
break;
case '\032': /* This gives problems on Win32 */
sBuilder.append('\\');
sBuilder.append('Z');
break;
case '\u00a5':
case '\u20a9':
// escape characters interpreted as backslash by mysql
// fall through
default:
sBuilder.append(c);
}
}
return sBuilder.toString();
}
}
There is actually a very simple solution. Just set them both like this:
view.layer.borderWidth = 5
view.layer.borderColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.5).cgColor
view.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.25).cgColor
interestingly in my git-bash on windows sed ""
did the trick already:
$ echo -e "abc\r" >tst.txt
$ file tst.txt
tst.txt: ASCII text, with CRLF line terminators
$ sed -i "" tst.txt
$ file tst.txt
tst.txt: ASCII text
My guess is that sed ignores them when reading lines from input and always writes unix line endings on output.
GSON is a good choice for Android and Web platform to parse JSON in a Kotlin project. This library is developed by Google. https://github.com/google/gson
1. First add GSON to your project:
dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
}
2. Now you need to convert your JSON to Kotlin Data class:
Copy your JSON and go to this(https://json2kt.com) website and paste your JSON to Input Json box. Write package(ex: com.example.appName) and Class name(ex: UserData) in proper box. This site will show live preview of your data class below and also you can download all classes at once in a zip file.
After downloading all classes extract zip file & place them into your project.
3. Now Parse like below:
val myJson = """
{
"user_name": "john123",
"email": "[email protected]",
"name": "John Doe"
}
""".trimIndent()
val gson = Gson()
var mUser = gson.fromJson(myJson, UserData::class.java)
println(mUser.userName)
Done :)
Try keydown
instead of keypress
.
The keyboard events occur in this order: keydown
, keyup
, keypress
The problem with backspace probably is, that the browser will navigate back on keyup
and thus your page will not see the keypress
event.
In General:
An example of an easy way to post XML data and get the response (as a string) would be the following function:
public string postXMLData(string destinationUrl, string requestXml)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
request.ContentType = "text/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseStr = new StreamReader(responseStream).ReadToEnd();
return responseStr;
}
return null;
}
In your specific situation:
Instead of:
request.ContentType = "application/x-www-form-urlencoded";
use:
request.ContentType = "text/xml; encoding='utf-8'";
Also, remove:
string postData = "XMLData=" + Sendingxml;
And replace:
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
with:
byte[] byteArray = Encoding.UTF8.GetBytes(Sendingxml.ToString());
You can't transition between two background images, as there's no way for the browser to know what you want to interpolate. As you've discovered, you can transition the background position. If you want the image to fade in on mouse over, I think the best way to do it with CSS transitions is to put the image on a containing element and then animate the background colour to transparent on the link itself:
span {
background: url(button.png) no-repeat 0 0;
}
a {
width: 32px;
height: 32px;
text-align: left;
background: rgb(255,255,255);
-webkit-transition: background 300ms ease-in 200ms; /* property duration timing-function delay */
-moz-transition: background 300ms ease-in 200ms;
-o-transition: background 300ms ease-in 200ms;
transition: background 300ms ease-in 200ms;
}
a:hover {
background: rgba(255,255,255,0);
}
In Your HTML
<input type="button" name="Release" onclick="hello();" value="Click to Release" />
In Your JavaScript
<script type="text/javascript">
function hello(){
alert('Your message here');
}
</script>
If you need to run PHP in JavaScript You need to use JQuery Ajax Function
<script type="text/javascript">
function hello(){
$.ajax(
{
type: 'post',
url: 'folder/my_php_file.php',
data: '&id=' + $('#id').val() + '&name=' + $('#name').val(),
dataType: 'json',
//alert(data);
success: function(data)
{
//alert(data);
}
});
}
</script>
Now in your my_php_file.php file
<?php
echo 'hello';
?>
Good Luck !!!!!
You can force the cell to commit the value as soon as you click the checkbox and then catch the CellValueChanged event. The CurrentCellDirtyStateChanged fires as soon as you click the checkbox.
The following code works for me:
private void grid_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
SendKeys.Send("{tab}");
}
You can then insert your code in the CellValueChanged event.
Run it like this:
java -jar HelloWorld.jar
you can't use input.click()
directly, but you can call this in other element click event.
html
<input type="file">
<button>Select file</button>
js
var botton = document.querySelector('button');
var input = document.querySelector('input');
botton.addEventListener('click', function (e) {
input.click();
});
this tell you Using hidden file input elements using the click() method
If you use terminal to build and you have this error you can point to jdk bundled with android studio in your gradle.properties
file:
org.gradle.java.home=/usr/local/android-studio/jre
If you want the second highest number you can use
=LARGE(E4:E9;2)
although that doesn't account for duplicates so you could get the same result as the Max
If you want the largest number that is smaller than the maximum number you can use this version
=LARGE(E4:E9;COUNTIF(E4:E9;MAX(E4:E9))+1)
For LINQ -> SQL:
SingleOrDefault
FirstOrDefault
asdf
These days I suggest using asdf to install various versions of Python interpreters next to each other.
Note1: asdf
works not only for Python but for all major languages.
Note2: asdf
works fine in combination with popular package-managers such as pipenv and poetry.
If you have asdf installed you can easily download/install new Python interpreters:
# Install Python plugin for asdf:
asdf plugin-add python
# List all available Python interpreters:
asdf list-all python
# Install the Python interpreters that you need:
asdf install python 3.7.4
asdf install python 3.6.9
# etc...
# If you want to define the global version:
asdf global python 3.7.4
# If you want to define the local (project) version:
# (this creates a file .tool-versions in the current directory.)
asdf local python 3.7.4
If you need to install multiple versions of Python (next to the main one) on Ubuntu / Mint: (should work similar on other Unixs'.)
1) Install Required Packages for source compilation
$ sudo apt-get install build-essential checkinstall
$ sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev
2) Download and extract desired Python version
Download Python Source for Linux as tarball and move it to /usr/src
.
Extract the downloaded package in place. (replace the 'x's with your downloaded version)
$ sudo tar xzf Python-x.x.x.tgz
3) Compile and Install Python Source
$ cd Python-x.x.x
$ sudo ./configure
$ sudo make altinstall
Your new Python bin is now located in /usr/local/bin
. You can test the new version:
$ pythonX.X -V
Python x.x.x
$ which pythonX.X
/usr/local/bin/pythonX.X
# Pip is now available for this version as well:
$ pipX.X -V
pip X.X.X from /usr/local/lib/pythonX.X/site-packages (python X.X)
You have an extra '{' before return type. You may also want to put '==' instead of '=' in if and else condition.
I found that you don't necessarily need the text vertically centred, it also looks good near the bottom of the row, it's only when it's at the top (or above centre?) that it looks wrong. So I went with this to push the links to the bottom of the row:
.navbar-brand {
min-height: 80px;
}
@media (min-width: 768px) {
#navbar-collapse {
position: absolute;
bottom: 0px;
left: 250px;
}
}
My brand image is SVG and I used height: 50px; width: auto
which makes it about 216px wide. It spilled out of its container vertically so I added the min-height: 80px;
to make room for it plus bootstrap's 15px margins. Then I tweaked the navbar-collapse
's left
setting until it looked right.
I was able to solve it by clicking on the "Kernel" drop down menu and choosing "Interrupt."
Kafka is a distributed system and needs Zookeeper. you have to start zookeeper too. Follow "Quick Start" here : https://kafka.apache.org/0100/documentation.html#quickstart
Try this:
Project -> Properties -> Java Build Path -> Add Class Folder.
If it doesnt work, please be specific in what way your compilation fails, specifically post the error messages Eclipse returns, and i will know what to do about it.
if you just want diff the specified file, you can :
git diff master 766eceb -- connections/ > 000-mysql-connector.patch
There is no standard JSON representation of dates. You should do what @jAndy suggested and not serialize a DateTime
at all; just send an RFC 1123 date string ToString("r")
or a seconds-from-Unix-epoch number, or something else that you can use in the JavaScript to construct a Date
.
You could convert it to a string instead of printing the list directly:
print(", ".join(LIST))
If the elements in the list aren't strings, you can convert them to string using either repr
(if you want quotes around strings) or str
(if you don't), like so:
LIST = [1, "foo", 3.5, { "hello": "bye" }]
print( ", ".join( repr(e) for e in LIST ) )
Which gives the output:
1, 'foo', 3.5, {'hello': 'bye'}
I think this is a simple and easy way to compare two lists element by element
x=[1,2,3,5,4,8,7,11,12,45,96,25]
y=[2,4,5,6,8,7,88,9,6,55,44,23]
tmp = []
for i in range(len(x)) and range(len(y)):
if x[i]>y[i]:
tmp.append(1)
else:
tmp.append(0)
print(tmp)
Not the best way to error log, but you can always set everything to an array for the promiseAll, and store the resulting results into new variables.
If you use graphQL you need to postprocess the response regardless and if it doesn't find the correct reference it'll crash the app, narrowing down where the problem is at
const results = await Promise.all([
this.props.client.query({
query: GET_SPECIAL_DATES,
}),
this.props.client.query({
query: GET_SPECIAL_DATE_TYPES,
}),
this.props.client.query({
query: GET_ORDER_DATES,
}),
]).catch(e=>console.log(e,"error"));
const specialDates = results[0].data.specialDates;
const specialDateTypes = results[1].data.specialDateTypes;
const orderDates = results[2].data.orders;
Worth mentioning: you should download the x64 version!
From the main download page (https://www.iis.net/downloads/microsoft/url-rewrite) click "additional downloads" (under the main download button) and download the x64 version (because for some reason - the default download version is x86)
you can use this function to download file from base64.
function downloadPDF(pdf) {
const linkSource = `data:application/pdf;base64,${pdf}`;
const downloadLink = document.createElement("a");
const fileName = "abc.pdf";
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();}
This code will made an anchor tag with href and download file. if you want to use button then you can call click method on your button click.
i hope this will help of you thanks
A binary search works by dividing the problem in half repeatedly, something like this (details omitted):
Example looking for 3 in [4,1,3,8,5]
It is a bi-nary search when you divide the problem in 2.
The search only requires log2(n) steps to find the correct value.
I would recommend Introduction to Algorithms if you want to learn about algorithmic complexity.
A login page isn't the only part of a database-driven website that interacts with the database.
Any user-editable input which is used to construct a database query is a potential entry point for a SQL injection attack. The attacker may not necessarily login to the site as an admin through this attack, but can do other things. They can change data, change server settings, etc. depending on the nature of the application's interaction with the database.
Appending a '
to an input is usually a pretty good test to see if it generates an error or otherwise produces unexpected behavior on the site. It's an indication that the user input is being used to build a raw query and the developer didn't expect a single quote, which changes the query structure.
Keep in mind that one page may be secure against SQL injection while another one may not. The login page, for example, may be hardened against such attacks. But a different page elsewhere in the site might be wide open. So, for example, if one wanted to login as an admin then one can use the SQL injection on that other page to change the admin password. Then return to the perfectly non-SQL-injectable login page and login as the admin.
It means exactly what it says: "The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path"
The library referred to is bundled into an OS specific dll (tcnative-1.dll) loaded via JNI. It allows tomcat to use OS functionalities not provided in the Java Runtime (such as sendfile, epoll, OpenSSL, system status, etc.). Tomcat will run just fine without it, but for some use cases, it will be faster with the native libraries.
If you really want it, download the tcnative-1.dll
(or libtcnative.so
for Linux) and put it in the bin folder, and add a system property to the launch configuration of the tomcat server in eclipse.
-Djava.library.path=c:\dev\tomcat\bin
in IE you can get the event object by window.event
in other browsers with no 'use strict'
directive, it is possible to get by arguments.callee.caller.arguments[0]
.
function myFunc(p1, p2, p3) {
var evt = window.event || arguments.callee.caller.arguments[0];
}
This is an article that I always refer to when working with sockets..
It will show you how to reliably use 'select()' and contains some other useful links at the bottom for further info on sockets.
Yes you can do this both programmatically and for all your activities making an AbstractActivity that all your activities extends.
public abstract class AbstractActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
This abstract activity can also be used for a global menu.
The if
attribute does not exist for <copy>
. It should be applied to the <target>
.
Below is an example of how you can use the depends
attribute of a target and the if
and unless
attributes to control execution of dependent targets. Only one of the two should execute.
<target name="prepare-copy" description="copy file based on condition"
depends="prepare-copy-true, prepare-copy-false">
</target>
<target name="prepare-copy-true" description="copy file based on condition"
if="copy-condition">
<echo>Get file based on condition being true</echo>
<copy file="${some.dir}/true" todir="." />
</target>
<target name="prepare-copy-false" description="copy file based on false condition"
unless="copy-condition">
<echo>Get file based on condition being false</echo>
<copy file="${some.dir}/false" todir="." />
</target>
If you are using ANT 1.8+, then you can use property expansion and it will evaluate the value of the property to determine the boolean value. So, you could use if="${copy-condition}"
instead of if="copy-condition"
.
In ANT 1.7.1 and earlier, you specify the name of the property. If the property is defined and has any value (even an empty string), then it will evaluate to true.
Just edit your .git/config file. For example; if you have a "common" submodule you can do this in the super-module:
git config submodule.common.url /data/my_local_common
Here's a mmap example:
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
/*
* pvtmMmapAlloc - creates a memory mapped file area.
* The return value is a page-aligned memory value, or NULL if there is a failure.
* Here's the list of arguments:
* @mmapFileName - the name of the memory mapped file
* @size - the size of the memory mapped file (should be a multiple of the system page for best performance)
* @create - determines whether or not the area should be created.
*/
void* pvtmMmapAlloc (char * mmapFileName, size_t size, char create)
{
void * retv = NULL;
if (create)
{
mode_t origMask = umask(0);
int mmapFd = open(mmapFileName, O_CREAT|O_RDWR, 00666);
umask(origMask);
if (mmapFd < 0)
{
perror("open mmapFd failed");
return NULL;
}
if ((ftruncate(mmapFd, size) == 0))
{
int result = lseek(mmapFd, size - 1, SEEK_SET);
if (result == -1)
{
perror("lseek mmapFd failed");
close(mmapFd);
return NULL;
}
/* Something needs to be written at the end of the file to
* have the file actually have the new size.
* Just writing an empty string at the current file position will do.
* Note:
* - The current position in the file is at the end of the stretched
* file due to the call to lseek().
* - The current position in the file is at the end of the stretched
* file due to the call to lseek().
* - An empty string is actually a single '\0' character, so a zero-byte
* will be written at the last byte of the file.
*/
result = write(mmapFd, "", 1);
if (result != 1)
{
perror("write mmapFd failed");
close(mmapFd);
return NULL;
}
retv = mmap(NULL, size,
PROT_READ | PROT_WRITE, MAP_SHARED, mmapFd, 0);
if (retv == MAP_FAILED || retv == NULL)
{
perror("mmap");
close(mmapFd);
return NULL;
}
}
}
else
{
int mmapFd = open(mmapFileName, O_RDWR, 00666);
if (mmapFd < 0)
{
return NULL;
}
int result = lseek(mmapFd, 0, SEEK_END);
if (result == -1)
{
perror("lseek mmapFd failed");
close(mmapFd);
return NULL;
}
if (result == 0)
{
perror("The file has 0 bytes");
close(mmapFd);
return NULL;
}
retv = mmap(NULL, size,
PROT_READ | PROT_WRITE, MAP_SHARED, mmapFd, 0);
if (retv == MAP_FAILED || retv == NULL)
{
perror("mmap");
close(mmapFd);
return NULL;
}
close(mmapFd);
}
return retv;
}
If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149
To summarize, open up a Terminal window and type the following command:
defaults write NSGlobalDomain KeyRepeat -int 0
More detail from the article:
Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:
defaults write NSGlobalDomain KeyRepeat -int 0
Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.
You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.
//Spanish
$('#TableName').DataTable({
"language": {
"sProcessing": "Procesando...",
"sLengthMenu": "Mostrar _MENU_ registros",
"sZeroRecords": "No se encontraron resultados",
"sEmptyTable": "Ningún dato disponible en esta tabla",
"sInfo": "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
"sInfoEmpty": "Mostrando registros del 0 al 0 de un total de 0 registros",
"sInfoFiltered": "(filtrado de un total de _MAX_ registros)",
"sInfoPostFix": "",
"sSearch": "Buscar:",
"sUrl": "",
"sInfoThousands": ",",
"sLoadingRecords": "Cargando...",
"oPaginate": {
"sFirst": "Primero",
"sLast": "Último",
"sNext": "Siguiente",
"sPrevious": "Anterior"
},
"oAria": {
"sSortAscending": ": Activar para ordenar la columna de manera ascendente",
"sSortDescending": ": Activar para ordenar la columna de manera descendente"
}
}
});
Also using a cdn:
//cdn.datatables.net/plug-ins/a5734b29083/i18n/Spanish.json
More options: http://www.datatables.net/plug-ins/i18n/English [| Spanish | etc]
If the files aren't numbered in order, take the hassle-free approach below: Python 3.6 on windows machine:
import pandas as pd
from glob import glob
interesting_files = glob("C:/temp/*.csv") # it grabs all the csv files from the directory you mention here
df_list = []
for filename in sorted(interesting_files):
df_list.append(pd.read_csv(filename))
full_df = pd.concat(df_list)
# save the final file in same/different directory:
full_df.to_csv("C:/temp/merged_pandas.csv", index=False)
From within gdb press Ctrl
x
2
and the screen will split into 3 parts.
First part will show you the normal code in high level language.
Second will show you the assembly equivalent and corresponding instruction Pointer
.
Third will present you the normal gdb
prompt to enter commands.
There is also the rather spiffy FileStream
, introduced in SQL Server 2008.
If X
and beta
do not have the same shape as the second term in the rhs of your last line (i.e. nsample
), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.
I would recommend looking at the numpy broadcasting rules.
It's rather trivial to check for existing username:
var arr = [{ id: 1, username: 'fred' },
{ id: 2, username: 'bill'},
{ id: 3, username: 'ted' }];
function userExists(username) {
return arr.some(function(el) {
return el.username === username;
});
}
console.log(userExists('fred')); // true
console.log(userExists('bred')); // false
But it's not so obvious what to do when you have to add a new user to this array. The easiest way out - just pushing a new element with id
equal to array.length + 1
:
function addUser(username) {
if (userExists(username)) {
return false;
}
arr.push({ id: arr.length + 1, username: username });
return true;
}
addUser('fred'); // false
addUser('bred'); // true, user `bred` added
It will guarantee the IDs uniqueness, but will make this array look a bit strange if some elements will be taken off its end.
As simple as 80 lines:
package windows.prefs;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IniFile {
private Pattern _section = Pattern.compile( "\\s*\\[([^]]*)\\]\\s*" );
private Pattern _keyValue = Pattern.compile( "\\s*([^=]*)=(.*)" );
private Map< String,
Map< String,
String >> _entries = new HashMap<>();
public IniFile( String path ) throws IOException {
load( path );
}
public void load( String path ) throws IOException {
try( BufferedReader br = new BufferedReader( new FileReader( path ))) {
String line;
String section = null;
while(( line = br.readLine()) != null ) {
Matcher m = _section.matcher( line );
if( m.matches()) {
section = m.group( 1 ).trim();
}
else if( section != null ) {
m = _keyValue.matcher( line );
if( m.matches()) {
String key = m.group( 1 ).trim();
String value = m.group( 2 ).trim();
Map< String, String > kv = _entries.get( section );
if( kv == null ) {
_entries.put( section, kv = new HashMap<>());
}
kv.put( key, value );
}
}
}
}
}
public String getString( String section, String key, String defaultvalue ) {
Map< String, String > kv = _entries.get( section );
if( kv == null ) {
return defaultvalue;
}
return kv.get( key );
}
public int getInt( String section, String key, int defaultvalue ) {
Map< String, String > kv = _entries.get( section );
if( kv == null ) {
return defaultvalue;
}
return Integer.parseInt( kv.get( key ));
}
public float getFloat( String section, String key, float defaultvalue ) {
Map< String, String > kv = _entries.get( section );
if( kv == null ) {
return defaultvalue;
}
return Float.parseFloat( kv.get( key ));
}
public double getDouble( String section, String key, double defaultvalue ) {
Map< String, String > kv = _entries.get( section );
if( kv == null ) {
return defaultvalue;
}
return Double.parseDouble( kv.get( key ));
}
}
Adding one more scalable solution.
lists = [lst1, lst2, lst3, lst4]
df = pd.concat([pd.Series(x) for x in lists], axis=1)
java
is the root JNDI namespace for resources. What the original snippet of code means is that the container the application was initially deployed in did not apply any additional namespaces to the JNDI context you retrieved (as an example, Tomcat automatically adds all resources to the namespace comp/env
, so you would have to do dataSource = (javax.sql.DataSource) context.lookup("java:comp/env/jdbc/myDataSource");
if the resource reference name is jdbc/myDataSource
).
To avoid having to change your legacy code I think if you register the datasource with the name myDataSource
(remove the jdbc/
) you should be fine. Let me know if that works.
We chose a combination of Mongo/Dynamo for a healthcare product. Basically mongo allows better searching, but the hosted Dynamo is great because its HIPAA compliant without any extra work. So we host the mongo portion with no personal data on a standard setup and allow amazon to deal with the HIPAA portion in terms of infrastructure. We can query certain items from mongo which bring up documents with pointers (ID's) of the relatable Dynamo document.
The main reason we chose to do this using mongo instead of hosting the entire application on dynamo was for 2 reasons. First, we needed to preform location based searches which mongo is great at and at the time, Dynamo was not, but they do have an option now.
Secondly was that some documents were unstructured and we did not know ahead of time what the data would be, so for example lets say user a inputs a document in the "form" collection like this: {"username": "user1", "email": "[email protected]"}. And another user puts this in the same collection {"phone": "813-555-3333", "location": [28.1234,-83.2342]}. With mongo we can search any of these dynamic and unknown fields at any time, with Dynamo, you could do this but would have to make a index every time a new field was added that you wanted searchable. So if you have never had a phone field in your Dynamo document before and then all of the sudden, some one adds it, its completely unsearchable.
Now this brings up another point in which you have mentioned. Sometimes choosing the right solution for the job does not always mean choosing the best product for the job. For example you may have a client who needs and will use the system you created for 10+ years. Going with a SaaS/IaaS solution that is good enough to get the job done may be a better option as you can rely on amazon to have up-kept and maintained their systems over the long haul.
If you lost a keystore file, don't create/update the new one with another set of value. First do the thorough search. Because it will overwrite the old one, so it will not match to your previous apk.
If you use eclipse most probably it will store in default path. For MAC (eclipse) it will be in your elispse installation path something like:
/Applications/eclipse/Eclipse.app/Contents/MacOS/
then your keystore file without any extension. You need root privilege to access this path (file).
Use the property TextWrapping
of the TextBlock
element:
<TextBlock Text="StackOverflow Forum"
Width="100"
TextWrapping="WrapWithOverflow"/>
If using Nginx
and getting a similar problem, then this might help:
Scan your domain on this sslTesturl, and see if the connection is allowed for your device version.
If lower version devices(like < Android 4.4.2 etc) are not able to connect due to TLS support, then try adding this to your Nginx config file,
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
Swift 3 / 4:
Here is a simple extension for Int/Double/Float/Bool key-value types that mimic the Optional-return behavior of the other types accessed through UserDefaults.
(Edit Aug 30 2018: Updated with more efficient syntax from Leo's suggestion.)
extension UserDefaults {
/// Convenience method to wrap the built-in .integer(forKey:) method in an optional returning nil if the key doesn't exist.
func integerOptional(forKey: String) -> Int? {
return self.object(forKey: forKey) as? Int
}
/// Convenience method to wrap the built-in .double(forKey:) method in an optional returning nil if the key doesn't exist.
func doubleOptional(forKey: String) -> Double? {
return self.object(forKey: forKey) as? Double
}
/// Convenience method to wrap the built-in .float(forKey:) method in an optional returning nil if the key doesn't exist.
func floatOptional(forKey: String) -> Float? {
return self.object(forKey: forKey) as? Float
}
/// Convenience method to wrap the built-in .bool(forKey:) method in an optional returning nil if the key doesn't exist.
func boolOptional(forKey: String) -> Bool? {
return self.object(forKey: forKey) as? Bool
}
}
They are now more consistent alongside the other built-in get methods (string, data, etc.). Just use the get methods in place of the old ones.
let AppDefaults = UserDefaults.standard
// assuming the key "Test" does not exist...
// old:
print(AppDefaults.integer(forKey: "Test")) // == 0
// new:
print(AppDefaults.integerOptional(forKey: "Test")) // == nil
**add the icon top button like this **
#copy_btn{_x000D_
align-items: center;_x000D_
position: absolute;_x000D_
width: 30px;_x000D_
height: 30px;_x000D_
background-color: Transparent;_x000D_
background-repeat:no-repeat;_x000D_
border: none;_x000D_
cursor:pointer;_x000D_
overflow: hidden;_x000D_
outline:none;_x000D_
}_x000D_
.icon_copy{_x000D_
position: absolute;_x000D_
padding: 0px;_x000D_
top:0;_x000D_
left: 0;_x000D_
width: 25px;_x000D_
height: 35px;_x000D_
_x000D_
}
_x000D_
<button id="copy_btn">_x000D_
_x000D_
<img class="icon_copy" src="./assest/copy.svg" alt="Copy Text">_x000D_
</button>
_x000D_
Why not do a recursive search to find all instances in sub directories:
grep -r 'text' *
This works like a charm.
Share Any File as below ( Kotlin ) :
first create a folder named xml
in the res
folder and create a new XML Resource File named provider_paths.xml
and put the below code inside it :
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path
name="files"
path="."/>
<external-path
name="external_files"
path="."/>
</paths>
now go to the manifests
folder and open the AndroidManifest.xml
and then put the below code inside the <application>
tag :
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" /> // provider_paths.xml file path in this example
</provider>
now you put the below code in the setOnLongClickListener
:
share_btn.setOnClickListener {
try {
val file = File("pathOfFile")
if(file.exists()) {
val uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file)
val intent = Intent(Intent.ACTION_SEND)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.setType("*/*")
intent.putExtra(Intent.EXTRA_STREAM, uri)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent)
}
} catch (e: java.lang.Exception) {
e.printStackTrace()
toast("Error")
}
}
In your specific case though it's probably easiest to use the -f
flag to seq
to get it to format the numbers as it outputs the list. For example:
for i in $(seq -f "%05g" 10 15)
do
echo $i
done
will produce the following output:
00010
00011
00012
00013
00014
00015
More generally, bash
has printf
as a built-in so you can pad output with zeroes as follows:
$ i=99
$ printf "%05d\n" $i
00099
You can use the -v
flag to store the output in another variable:
$ i=99
$ printf -v j "%05d" $i
$ echo $j
00099
Notice that printf
supports a slightly different format to seq
so you need to use %05d
instead of %05g
.
Here's an example of how to convert DATETIME
to UNIX timestamp:
SELECT UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p'))
Here's an example of how to change date format:
SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p')),'%m-%d-%Y %h:%i:%p')
Documentation: UNIX_TIMESTAMP
, FROM_UNIXTIME
This problem can be fixed by installing the C++ compiler (python27 or python26). Download it from Microsoft https://www.microsoft.com/en-us/download/details.aspx?id=44266 and re-run the command : pip install pycrypto
to run the gui web access when you kill the process of easy_install.exe
.
You can use too
style="overflow-y: scroll; height:150px; width: auto;"
It's works for me
Your understanding is slightly flawed. The diamond operator is a nice feature as you don't have to repeat yourself. It makes sense to define the type once when you declare the type but just doesn't make sense to define it again on the right side. The DRY principle.
Now to explain all the fuzz about defining types. You are right that the type is removed at runtime but once you want to retrieve something out of a List with type definition you get it back as the type you've defined when declaring the list otherwise it would lose all specific features and have only the Object features except when you'd cast the retrieved object to it's original type which can sometimes be very tricky and result in a ClassCastException.
Using List<String> list = new LinkedList()
will get you rawtype warnings.
The asker commented:
I figure that if I understand a problem well enough to write a program that can figure it out, I don't need to do the work manually.
If he's writing a math expression solver as a learning exercise, using eval()
isn't going to help. Plus it's terrible design.
You might consider making a calculator using Reverse Polish Notation instead of standard math notation. It simplifies the parsing considerably. It would still be a good exercise
You should use a DialogFragment instead.
check this is useful for you...
public void setCustomTitle (View customTitleView)
you get detail from following link.
CustomDialog.java
Dialog alert = new Dialog(this);
alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
alert.setContentView(R.layout.title);
TextView msg = (TextView)alert.findViewById(R.id.textView1);
msg.setText("Hello Friends.\nIP address : 111.111.1.111");
alert.show();
title.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set IP address"
android:textColor="#ff0000"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ImageView
android:layout_width="fill_parent"
android:layout_height="2dp"
android:layout_marginTop="5dp"
android:background="#00ff00"
/>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#775500"
android:textAppearance="?android:attr/textAppearanceLarge" />
Simple jQuery solution - find the <a>
element where href="x"
and click it:
$('a[href="#tabs-2"]').click();
There is no inherent reason that a simple batch file would run in XP but not Windows 10. It is possible you are referencing a command or a 3rd party utility that no longer exists. To know more about what is actually happening, you will need to do one of the following:
pause
to the batch file so that you can see what is happening before it exits.
.bat
files and select "edit". This will open the file in notepad.pause
.- OR -
.bat
files are located, hold down the "shift" key and right click in the white space.Once you have done this, I recommend creating a new question with the output you see after using one of the methods above.
This is a textbook case for a constructor function:
var myArray = [];
function myElement(id, value){
this.id = id
this.value = value
}
myArray[0] = new myElement(0,1)
myArray[1] = new myElement(2,3)
// or myArray.push(new myElement(1, 1))
import sys
print(sys.argv[0])
This will print foo.py
for python foo.py
, dir/foo.py
for python dir/foo.py
, etc. It's the first argument to python
. (Note that after py2exe it would be foo.exe
.)
You can also use the following command:
pylint --disable=C0321 test.py
My Pylint version is 0.25.1.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class readFile {
/**
* feel free to make any modification I have have been here so I feel you
*
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
File dir = new File(".");// read file from same directory as source //
if (dir.isDirectory()) {
File[] files = dir.listFiles();
for (File file : files) {
// if you wanna read file name with txt files
if (file.getName().contains("txt")) {
System.out.println(file.getName());
}
// if you want to open text file and read each line then
if (file.getName().contains("txt")) {
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(
file.getAbsolutePath());
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(
fileReader);
String line;
// get file details and get info you need.
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
// here you can say...
// System.out.println(line.substring(0, 10)); this
// prints from 0 to 10 indext
}
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '"
+ file.getName() + "'");
} catch (IOException ex) {
System.out.println("Error reading file '"
+ file.getName() + "'");
// Or we could just do this:
ex.printStackTrace();
}
}
}
}
}`enter code here`
}
Go to Android Manifest.xml
and be sure to add the <uses-permission tag >
inside the manifest tag but Outside of all other tags..
<manifest xlmns:android...>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>
This is an example of the permission of using Internet.
I didn't think this was possible: I had to delete flutter folder and reinstall it from scratch!
here's how:
import pygame
screen=pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
red=255
blue=0
green=0
left=50
top=50
width=90
height=90
filled=0
pygame.draw.rect(screen, [red, blue, green], [left, top, width, height], filled)
pygame.display.flip()
running=True
while running:
for event in pygame.event.get():
if event.type==pygame.QUIT:
running=False
pygame.quit()
To integrate the previous answers, there's an obvious advantage in declaring constant variables, apart from the performance reason: if you accidentally try to change or re-declare them in the code, the program will respectively not change the value or throw an error.
For example, compare:
// Will output 'SECRET'
const x = 'SECRET'
if (x = 'ANOTHER_SECRET') { // Warning! assigning a value variable in an if condition
console.log (x)
}
with:
// Will output 'ANOTHER_SECRET'
var y = 'SECRET'
if (y = 'ANOTHER_SECRET') {
console.log (y)
}
or
// Will throw TypeError: const 'x' has already been declared
const x = "SECRET"
/* complex code */
var x = 0
with
// Will reassign y and cause trouble
var y = "SECRET"
/* complex code */
var y = 0
During the preflight request, you should see the following two headers: Access-Control-Request-Method and Access-Control-Request-Headers. These request headers are asking the server for permissions to make the actual request. Your preflight response needs to acknowledge these headers in order for the actual request to work.
For example, suppose the browser makes a request with the following headers:
Origin: http://yourdomain.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-Custom-Header
Your server should then respond with the following headers:
Access-Control-Allow-Origin: http://yourdomain.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: X-Custom-Header
Pay special attention to the Access-Control-Allow-Headers response header. The value of this header should be the same headers in the Access-Control-Request-Headers request header, and it can not be '*'.
Once you send this response to the preflight request, the browser will make the actual request. You can learn more about CORS here: http://www.html5rocks.com/en/tutorials/cors/
setTimeout(function() { $location.path("/abc"); },0);
it should solve your problem.
Most of the time, these type of issues happen due to incorrect java version. Make sure your PATH and JAVA_HOME variables are pointing to the correct version.
To really get this clear, here's my for-beginners answer:
You inputed the arguments in the wrong order.
A keyword argument has this style:
nullable=True, unique=False
A fixed parameter should be defined: True, False, etc. A non-keyword argument is different:
name="Ricardo", fruit="chontaduro"
This syntax error asks you to first put name="Ricardo"
and all of its kind (non-keyword) before those like nullable=True.
cat file.log | wc -l | grep -oE '\d+'
grep -oE '\d+'
: In order to return the digit numbers ONLY."
is valid in both HTML5 and HTML4.
'
is valid in HTML5, but not HTML4. However, most browsers support '
for HTML4 anyway.