What about image.naturalHeight
and image.naturalWidth
properties?
Seems to work fine back quite a few versions in Chrome, Safari and Firefox, but not at all in IE8 or even IE9.
An asynchronously loaded script is likely going to run AFTER the document has been fully parsed and closed. Thus, you can't use document.write()
from such a script (well technically you can, but it won't do what you want).
You will need to replace any document.write()
statements in that script with explicit DOM manipulations by creating the DOM elements and then inserting them into a particular parent with .appendChild()
or .insertBefore()
or setting .innerHTML
or some mechanism for direct DOM manipulation like that.
For example, instead of this type of code in an inline script:
<div id="container">
<script>
document.write('<span style="color:red;">Hello</span>');
</script>
</div>
You would use this to replace the inline script above in a dynamically loaded script:
var container = document.getElementById("container");
var content = document.createElement("span");
content.style.color = "red";
content.innerHTML = "Hello";
container.appendChild(content);
Or, if there was no other content in the container that you needed to just append to, you could simply do this:
var container = document.getElementById("container");
container.innerHTML = '<span style="color:red;">Hello</span>';
For a number between 0 and 100.
Number.parseInt(Math.floor(Math.random() * 100))
I'm looking at a similar problem, and I've found some of the best references come from chemistry (from peaks finding in mass-spec data). For a good thorough review of peaking finding algorithms read this. This is one of the best clearest reviews of peak finding techniques that I've run across. (Wavelets are the best for finding peaks of this sort in noisy data.).
It looks like your peaks are clearly defined and aren't hidden in the noise. That being the case I'd recommend using smooth savtizky-golay derivatives to find the peaks (If you just differentiate the data above you'll have a mess of false positives.). This is a very effective technique and is pretty easy to implemented (you do need a matrix class w/ basic operations). If you simply find the zero crossing of the first S-G derivative I think you'll be happy.
There is not a Transparent color code, but there is an Opacity styling. Check out the documentation about it over at developer.mozilla.org
You will probably want to set the color of the element and then apply the opacity to it.
.transparent-style{
background-color: #ffffff;
opacity: .4;
}
You can use some online transparancy generatory which will also give you browser specific stylings. e.g. take a look at http://www.css-opacity.pascal-seven.de/
Note though that when you set the transparency of an element, any child element becomes transparent also. So you really need to overlay any other elements.
You may also want to try using an RGBA colour using the Alpha (A) setting to change the opacity. e.g.
.transparent-style{
background-color: rgba(255, 255, 255, .4);
}
Using RGBA over opacity
means that your child elements are not transparent.
try this
INSERT INTO TABLE1 (COL1 , COL2,COL3) values
('A STRING' , 5 , (select idTable2 from Table2) )
where ...
I think it's too late to answer this question but I faced the same problem recently my use case was to call the paginated JSON API and get all the data from each pagination and append it to a single array.
const https = require('https');
const apiUrl = "https://example.com/api/movies/search/?Title=";
let finaldata = [];
let someCallBack = function(data){
finaldata.push(...data);
console.log(finaldata);
};
const getData = function (substr, pageNo=1, someCallBack) {
let actualUrl = apiUrl + `${substr}&page=${pageNo}`;
let mydata = []
https.get(actualUrl, (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', async () => {
if (JSON.parse(data).total_pages!==null){
pageNo+=1;
somCallBack(JSON.parse(data).data);
await getData(substr, pageNo, someCallBack);
}
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
}
getData("spiderman", pageNo=1, someCallBack);
Like @ackuser mentioned we can use other module but In my use case I had to use the node https
. Hoping this will help others.
Guess @user3010492 tested it but I used this with fixed cell A5 --> $A$5 and fixed element of G7 --> $G7
=INDIRECT("'"&$A$5&"'!$G7")
Also works nested nicely in other formula if you enclose it in brackets.
Add:
using System.Linq;
to the top of your file.
And then:
Car[] carList = ...
var carMake =
from item in carList
where item.Model == "bmw"
select item.Make;
or if you prefer the fluent syntax:
var carMake = carList
.Where(item => item.Model == "bmw")
.Select(item => item.Make);
Things to pay attention to:
item.Make
in the select
clause instead if s.Make
as in your code.item
and .Model
in your where
clauseMutations expect two arguments: state
and payload
, where the current state of the store is passed by Vuex itself as the first argument and the second argument holds any parameters you need to pass.
The easiest way to pass a number of parameters is to destruct them:
mutations: {
authenticate(state, { token, expiration }) {
localStorage.setItem('token', token);
localStorage.setItem('expiration', expiration);
}
}
Then later on in your actions you can simply
store.commit('authenticate', {
token,
expiration,
});
Edit (2020.12.28): GitHub change default master branch to main branch since October 2020. See https://github.com/github/renaming
Update March 2013
Git 1.8.2 added the possibility to track branches.
"
git submodule
" started learning a new mode to integrate with the tip of the remote branch (as opposed to integrating with the commit recorded in the superproject's gitlink).
# add submodule to track master branch
git submodule add -b master [URL to Git repo];
# update your submodule
git submodule update --remote
If you had a submodule already present you now wish would track a branch, see "how to make an existing submodule track a branch".
Also see Vogella's tutorial on submodules for general information on submodules.
Note:
git submodule add -b . [URL to Git repo];
^^^
A special value of
.
is used to indicate that the name of the branch in the submodule should be the same name as the current branch in the current repository.
See commit b928922727d6691a3bdc28160f93f25712c565f6:
submodule add
: If --branch
is given, record it in .gitmodules
This allows you to easily record a
submodule.<name>.branch
option in.gitmodules
when you add a new submodule. With this patch,
$ git submodule add -b <branch> <repository> [<path>]
$ git config -f .gitmodules submodule.<path>.branch <branch>
reduces to
$ git submodule add -b <branch> <repository> [<path>]
This means that future calls to
$ git submodule update --remote ...
will get updates from the same branch that you used to initialize the submodule, which is usually what you want.
Signed-off-by: W. Trevor King [email protected]
Original answer (February 2012):
A submodule is a single commit referenced by a parent repo.
Since it is a Git repo on its own, the "history of all commits" is accessible through a git log
within that submodule.
So for a parent to track automatically the latest commit of a given branch of a submodule, it would need to:
gitslave (that you already looked at) seems to be the best fit, including for the commit operation.
It is a little annoying to make changes to the submodule due to the requirement to check out onto the correct submodule branch, make the change, commit, and then go into the superproject and commit the commit (or at least record the new location of the submodule).
Other alternatives are detailed here.
I've made a simple function for this.
The _case
function allows you to not only get the target, but also get the parent element where you bind the event on.
The callback function returns the event which holds the target (evt.target
) and the parent element matching the selector (this
). Here you can do the stuff you need after the element is clicked.
I've not yet decided which is better, the if-else
or the switch
var _case = function(evt, selector, cb) {_x000D_
var _this = evt.target.closest(selector);_x000D_
if (_this && _this.nodeType) {_x000D_
cb.call(_this, evt);_x000D_
return true;_x000D_
} else { return false; }_x000D_
}_x000D_
_x000D_
document.getElementById('ifelse').addEventListener('click', function(evt) {_x000D_
if (_case(evt, '.parent1', function(evt) {_x000D_
console.log('1: ', this, evt.target);_x000D_
})) return false;_x000D_
_x000D_
if (_case(evt, '.parent2', function(evt) {_x000D_
console.log('2: ', this, evt.target);_x000D_
})) return false;_x000D_
_x000D_
console.log('ifelse: ', this);_x000D_
})_x000D_
_x000D_
_x000D_
document.getElementById('switch').addEventListener('click', function(evt) {_x000D_
switch (true) {_x000D_
case _case(evt, '.parent3', function(evt) {_x000D_
console.log('3: ', this, evt.target);_x000D_
}): break;_x000D_
case _case(evt, '.parent4', function(evt) {_x000D_
console.log('4: ', this, evt.target);_x000D_
}): break;_x000D_
default:_x000D_
console.log('switch: ', this);_x000D_
break;_x000D_
}_x000D_
})
_x000D_
#ifelse {_x000D_
background: red;_x000D_
height: 100px;_x000D_
}_x000D_
#switch {_x000D_
background: yellow;_x000D_
height: 100px;_x000D_
}
_x000D_
<div id="ifelse">_x000D_
<div class="parent1">_x000D_
<div class="child1">Click me 1!</div>_x000D_
</div>_x000D_
<div class="parent2">_x000D_
<div class="child2">Click me 2!</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div id="switch">_x000D_
<div class="parent3">_x000D_
<div class="child3">Click me 3!</div>_x000D_
</div>_x000D_
<div class="parent4">_x000D_
<div class="child4">Click me 4!</div>_x000D_
</div>_x000D_
</div>
_x000D_
Hope it helps!
Just been doing that myself today... here is code I have working for me...
$data = array("a" => $a);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
$response = curl_exec($ch);
if (!$response)
{
return false;
}
src: http://www.lornajane.net/posts/2009/putting-data-fields-with-php-curl
Import DatePipe from angular/common and then use the below code:
var datePipe = new DatePipe();
this.setDob = datePipe.transform(userdate, 'dd/MM/yyyy');
where userdate will be your date string. See if this helps.
Make note of the lowercase for date and year :
d- date
M- month
y-year
EDIT
You have to pass locale
string as an argument to DatePipe, in latest angular. I have tested in angular 4.x
For Example:
var datePipe = new DatePipe('en-US');
The question is tagged SQL Server 2000 but for the benefit of people developing on the latest version I'll address that first.
SQL Server 2014
In addition to the methods of adding constraint based indexes discussed below SQL Server 2014 also allows non unique indexes to be specified directly with inline syntax on table variable declarations.
Example syntax for that is below.
/*SQL Server 2014+ compatible inline index syntax*/
DECLARE @T TABLE (
C1 INT INDEX IX1 CLUSTERED, /*Single column indexes can be declared next to the column*/
C2 INT INDEX IX2 NONCLUSTERED,
INDEX IX3 NONCLUSTERED(C1,C2) /*Example composite index*/
);
Filtered indexes and indexes with included columns can not currently be declared with this syntax however SQL Server 2016 relaxes this a bit further. From CTP 3.1 it is now possible to declare filtered indexes for table variables. By RTM it may be the case that included columns are also allowed but the current position is that they "will likely not make it into SQL16 due to resource constraints"
/*SQL Server 2016 allows filtered indexes*/
DECLARE @T TABLE
(
c1 INT NULL INDEX ix UNIQUE WHERE c1 IS NOT NULL /*Unique ignoring nulls*/
)
SQL Server 2000 - 2012
Can I create a index on Name?
Short answer: Yes.
DECLARE @TEMPTABLE TABLE (
[ID] [INT] NOT NULL PRIMARY KEY,
[Name] [NVARCHAR] (255) COLLATE DATABASE_DEFAULT NULL,
UNIQUE NONCLUSTERED ([Name], [ID])
)
A more detailed answer is below.
Traditional tables in SQL Server can either have a clustered index or are structured as heaps.
Clustered indexes can either be declared as unique to disallow duplicate key values or default to non unique. If not unique then SQL Server silently adds a uniqueifier to any duplicate keys to make them unique.
Non clustered indexes can also be explicitly declared as unique. Otherwise for the non unique case SQL Server adds the row locator (clustered index key or RID for a heap) to all index keys (not just duplicates) this again ensures they are unique.
In SQL Server 2000 - 2012 indexes on table variables can only be created implicitly by creating a UNIQUE
or PRIMARY KEY
constraint. The difference between these constraint types are that the primary key must be on non nullable column(s). The columns participating in a unique constraint may be nullable. (though SQL Server's implementation of unique constraints in the presence of NULL
s is not per that specified in the SQL Standard). Also a table can only have one primary key but multiple unique constraints.
Both of these logical constraints are physically implemented with a unique index. If not explicitly specified otherwise the PRIMARY KEY
will become the clustered index and unique constraints non clustered but this behavior can be overridden by specifying CLUSTERED
or NONCLUSTERED
explicitly with the constraint declaration (Example syntax)
DECLARE @T TABLE
(
A INT NULL UNIQUE CLUSTERED,
B INT NOT NULL PRIMARY KEY NONCLUSTERED
)
As a result of the above the following indexes can be implicitly created on table variables in SQL Server 2000 - 2012.
+-------------------------------------+-------------------------------------+
| Index Type | Can be created on a table variable? |
+-------------------------------------+-------------------------------------+
| Unique Clustered Index | Yes |
| Nonunique Clustered Index | |
| Unique NCI on a heap | Yes |
| Non Unique NCI on a heap | |
| Unique NCI on a clustered index | Yes |
| Non Unique NCI on a clustered index | Yes |
+-------------------------------------+-------------------------------------+
The last one requires a bit of explanation. In the table variable definition at the beginning of this answer the non unique non clustered index on Name
is simulated by a unique index on Name,Id
(recall that SQL Server would silently add the clustered index key to the non unique NCI key anyway).
A non unique clustered index can also be achieved by manually adding an IDENTITY
column to act as a uniqueifier.
DECLARE @T TABLE
(
A INT NULL,
B INT NULL,
C INT NULL,
Uniqueifier INT NOT NULL IDENTITY(1,1),
UNIQUE CLUSTERED (A,Uniqueifier)
)
But this is not an accurate simulation of how a non unique clustered index would normally actually be implemented in SQL Server as this adds the "Uniqueifier" to all rows. Not just those that require it.
Newer versions of Python come with py
, the Python Launcher, which is always in the PATH
.
Here is how to invoke pip
via py
:
py -m pip install <packagename>
py
allows having several versions of Python on the same machine.
As an example, here is how to invoke the pip
from Python 2.7:
py -2.7 -m pip install <packagename>
krosenvold's answer inspired the following script which does the following:
the script is restartable and checks the existence of the intermediate files. It also uses pv and qemu-img -p to show the progress of each step.
In my environment 2 x Ubuntu 12.04 LTS the steps took:
#!/bin/bash
# get a dd disk dump and convert it to vmware
# see http://stackoverflow.com/questions/454899/how-to-convert-flat-raw-disk-image-to-vmdk-for-virtualbox-or-vmplayer
# Author: wf 2014-10-1919
#
# get a dd dump from the given host's given disk and create a compressed
# image at the given target
#
# 1: host e.g. somehost.somedomain
# 2: disk e.g. sda
# 3: target e.g. image.gz
#
# http://unix.stackexchange.com/questions/132797/how-to-use-ssh-to-make-a-dd-copy-of-disk-a-from-host-b-and-save-on-disk-b
getdump() {
local l_host="$1"
local l_disk="$2"
local l_target="$3"
echo "getting disk dump of $l_disk from $l_host"
ssh $l_host sudo fdisk -l | egrep "^/dev/$l_disk"
if [ $? -ne 0 ]
then
echo "device $l_disk does not exist on host $l_host" 1>&2
exit 1
else
if [ ! -f $l_target ]
then
ssh $l_host "sudo dd if=/dev/$disk bs=1M | gzip -1 -" | pv | dd of=$l_target
else
echo "$l_target already exists"
fi
fi
}
#
# optionally install command from package if it is not available yet
# 1: command
# 2: package
#
opt_install() {
l_command="$1"
l_package="$2"
echo "checking that $l_command from package $l_package is installed ..."
which $l_command
if [ $? -ne 0 ]
then
echo "installing $l_package to make $l_command available ..."
sudo apt-get install $l_package
fi
}
#
# convert the given image to vmware
# 1: the dd dump image
# 2: the vmware image file to convert to
#
vmware_convert() {
local l_ddimage="$1"
local l_vmwareimage="$2"
echo "converting dd image $l_image to vmware $l_vmwareimage"
# convert to VMware disk format showing progess
# see http://manpages.ubuntu.com/manpages/precise/man1/qemu-img.1.html
qemu-img convert -p -O vmdk "$l_ddimage" "$l_vmwareimage"
}
#
# show usage
#
usage() {
echo "usage: $0 host device"
echo " host: the host to get the disk dump from e.g. frodo.lotr.org"
echo " you need ssh and sudo privileges on that host"
echo "
echo " device: the disk to dump from e.g. sda"
echo ""
echo " examples:
echo " $0 frodo.lotr.org sda"
echo " $0 gandalf.lotr.org sdb"
echo ""
echo " the needed packages pv and qemu-utils will be installed if not available"
echo " you need local sudo rights for this to work"
exit 1
}
# check arguments
if [ $# -lt 2 ]
then
usage
fi
# get the command line parameters
host="$1"
disk="$2"
# calculate the names of the image files
ts=`date "+%Y-%m-%d"`
# prefix of all images
# .gz the zipped dd
# .dd the disk dump file
# .vmware - the vmware disk file
image="${host}_${disk}_image_$ts"
echo "$0 $host/$disk -> $image"
# first check/install necessary packages
opt_install qemu-img qemu-utils
opt_install pv pv
# check if dd files was already loaded
# we don't want to start this tedious process twice if avoidable
if [ ! -f $image.gz ]
then
getdump $host $disk $image.gz
else
echo "$image.gz already downloaded"
fi
# check if the dd file was already uncompressed
# we don't want to start this tedious process twice if avoidable
if [ ! -f $image.dd ]
then
echo "uncompressing $image.gz"
zcat $image.gz | pv -cN zcat > $image.dd
else
echo "image $image.dd already uncompressed"
fi
# check if the vmdk file was already converted
# we don't want to start this tedious process twice if avoidable
if [ ! -f $image.vmdk ]
then
vmware_convert $image.dd $image.vmdk
else
echo "vmware image $image.vmdk already converted"
fi
Just go to Settings>>Compiler and Debugger, then click the Linker Settings tab and go over to the "Other linker options" edit control and paste: "-static-libgcc -static-libstdc++" to it, there is no compiler flag option in the Compiler Flags options for Code::Blocks so that's the way to solve that problem, I came here looking for a solution also and the one guy that posted about "-static-libgcc -static-libstdc++" gave the right idea, and I sort of figured the rest out by accident but it worked, the file is clickable now from outside Code::Blocks, works right from the desktop.
In my particular case I had a config file generated and cached into the bootstrap/cache/
directory so my steps where:
rm bootstrap/cache/*.php
Create a new laravel.log
file and apply the update of the permissions on the file using:
chmod -R 775 storage
You also could just throw new HttpMessageNotReadableException("error description")
to benefit from Spring's default error handling.
However, just as is the case with those default errors, no response body will be set.
I find these useful when rejecting requests that could reasonably only have been handcrafted, potentially indicating a malevolent intent, since they obscure the fact that the request was rejected based on a deeper, custom validation and its criteria.
Hth, dtk
I'm not sure what you consider "painless."
C strings are pretty painful. We can find the first non-whitespace character position trivially:
while (isspace(* p)) p++;
We can find the last non-whitespace character position with two similar trivial moves:
while (* q) q++; do { q--; } while (isspace(* q));
(I have spared you the pain of using the *
and ++
operators at the same time.)
The question now is what do you do with this? The datatype at hand isn't really a big robust abstract String
that is easy to think about, but instead really barely any more than an array of storage bytes. Lacking a robust data type, it is impossible to write a function that will do the same as PHperytonby's chomp
function. What would such a function in C return?
Here is the sample MYSQL Stored Procedure with delimiter and how to call..
DELIMITER $$
DROP PROCEDURE IF EXISTS `sp_user_login` $$
CREATE DEFINER=`root`@`%` PROCEDURE `sp_user_login`(
IN loc_username VARCHAR(255),
IN loc_password VARCHAR(255)
)
BEGIN
SELECT user_id,
user_name,
user_emailid,
user_profileimage,
last_update
FROM tbl_user
WHERE user_name = loc_username
AND password = loc_password
AND status = 1;
END $$
DELIMITER ;
and call by, mysql_connection specification and
$loginCheck="call sp_user_login('".$username."','".$password."');";
it will return the result from the procedure.
You don't have a Date
, you have a String
representation of a date. You should convert the String
into a Date
and then obtain the milliseconds. To convert a String
into a Date
and vice versa you should use SimpleDateFormat
class.
Here's an example of what you want/need to do (assuming time zone is not involved here):
String myDate = "2014/10/29 18:10:45";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse(myDate);
long millis = date.getTime();
Still, be careful because in Java the milliseconds obtained are the milliseconds between the desired epoch and 1970-01-01 00:00:00.
Using the new Date/Time API available since Java 8:
String myDate = "2014/10/29 18:10:45";
LocalDateTime localDateTime = LocalDateTime.parse(myDate,
DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss") );
/*
With this new Date/Time API, when using a date, you need to
specify the Zone where the date/time will be used. For your case,
seems that you want/need to use the default zone of your system.
Check which zone you need to use for specific behaviour e.g.
CET or America/Lima
*/
long millis = localDateTime
.atZone(ZoneId.systemDefault())
.toInstant().toEpochMilli();
That should be fine as long as you don't require the "remove" method to be atomic.
In other words, if the "do something" checks that the item appears more than once in the list for example, it is possible that the result of that check will be wrong by the time you reach the next line.
Also, make sure you synchronize on the list when iterating:
synchronized(list) {
for (Object o : list) {}
}
As mentioned by Peter Lawrey, CopyOnWriteArrayList can make your life easier and can provide better performance in a highly concurrent environment.
Semantically speaking, wouldn't it be best to use an ordered or unordered list and then style it appropriately using CSS?
<ul id="[UL_ID]">
<li><img src="[image1_url]" alt="img1" /></li>
<li><img src="[image2_url]" alt="img2" /></li>
<li><img src="[image3_url]" alt="img3" /></li>
<li><img src="[image4_url]" alt="img4" /></li>
<li><img src="[image5_url]" alt="img5" /></li>
<li><img src="[image6_url]" alt="img6" /></li>
</ul>
Using CSS, you'll be able to style this whatever way you want and remove the whitespace imbetween the books.
Sometimes this works;
sudo apt-get install mongodb-org --fix-missing --fix-broken
sudo apt-get autoremove mongodb-org --fix-missing --fix-broken
There is a library that provides a better ProcessBuilder, zt-exec. This library can do exactly what you are asking for and more.
Here's what your code would look like with zt-exec instead of ProcessBuilder :
add the dependency :
<dependency>
<groupId>org.zeroturnaround</groupId>
<artifactId>zt-exec</artifactId>
<version>1.11</version>
</dependency>
The code :
new ProcessExecutor()
.command("somecommand", "arg1", "arg2")
.redirectOutput(System.out)
.redirectError(System.err)
.execute();
Documentation of the library is here : https://github.com/zeroturnaround/zt-exec/
Difference between "querySelector" and "querySelectorAll"
//querySelector returns single element_x000D_
let listsingle = document.querySelector('li');_x000D_
console.log(listsingle);_x000D_
_x000D_
_x000D_
//querySelectorAll returns lit/array of elements_x000D_
let list = document.querySelectorAll('li');_x000D_
console.log(list);_x000D_
_x000D_
_x000D_
//Note : output will be visible in Console
_x000D_
<ul>_x000D_
<li class="test">ffff</li>_x000D_
<li class="test">vvvv</li>_x000D_
<li>dddd</li>_x000D_
<li class="test">ddff</li>_x000D_
</ul>
_x000D_
Correct solution is to copy or install to /usr/local/bin
not /usr/bin
.This is due to System Integrity Protection (SIP). SIP makes /usr/bin
read-only but leaves /usr/local
as read-write.
SIP should not be disabled as stated in the answer above because it adds another layer of protection against malware gaining root access. Here is a complete explanation of what SIP does and why it is useful.
As suggested in this answer one should not disable SIP (rootless mode) "It is not recommended to disable rootless mode! The best practice is to install custom stuff to "/usr/local" only."
In code first, you can have multiple DBContext and just one database. You just have to specify the connection string in the constructor.
public class MovieDBContext : DbContext
{
public MovieDBContext()
: base("DefaultConnection")
{
}
public DbSet<Movie> Movies { get; set; }
}
You need to store the psftp script (lines from open
to bye
) into a separate file and pass that to psftp
using -b
switch:
cd "C:\Program Files (x86)\PuTTY"
psftp -b "C:\path\to\script\script.txt"
Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-option-b
EDIT: For username+password: As you cannot use psftp
commands in a batch file, for the same reason, you cannot specify the username and the password as psftp
commands. These are inputs to the open
command. While you can specify the username with the open
command (open <user>@<IP>
), you cannot specify the password this way. This can be done on a psftp
command line only. Then it's probably cleaner to do all on the command-line:
cd "C:\Program Files (x86)\PuTTY"
psftp -b script.txt <user>@<IP> -pw <PW>
And remove the open
, <user>
and <PW>
lines from your script.txt
.
Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-starting
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-pw
What you are doing atm is that you run psftp
without any parameter or commands. Once you exit it (like by typing bye
), your batch file continues trying to run open
command (and others), what Windows shell obviously does not understand.
If you really want to keep everything in one file (the batch file), you can write commands to psftp standard input, like:
(
echo cd ...
echo lcd ...
echo put log.sh
) | psftp -b script.txt <user>@<IP> -pw <PW>
In my cases, I solved the problem when using the labs()
instead of abs()
.
In Fedora 25, it turned out to be an SE Linux issue, and the notification gave this solution which worked for me.
setsebool -P httpd_read_user_content 1
Here '~' refers to the root directory ,where Home is controller and Download_Excel_File is actionmethod
<a href="~/Home/Download_Excel_File" />
function URLIsValid($URL)
{
$exists = true;
$file_headers = @get_headers($URL);
$InvalidHeaders = array('404', '403', '500');
foreach($InvalidHeaders as $HeaderVal)
{
if(strstr($file_headers[0], $HeaderVal))
{
$exists = false;
break;
}
}
return $exists;
}
If you want this to be handled by UILabel and not UITextView, you can make UILabel subclass, like this one:
class LinkedLabel: UILabel {
fileprivate let layoutManager = NSLayoutManager()
fileprivate let textContainer = NSTextContainer(size: CGSize.zero)
fileprivate var textStorage: NSTextStorage?
override init(frame aRect:CGRect){
super.init(frame: aRect)
self.initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initialize()
}
func initialize(){
let tap = UITapGestureRecognizer(target: self, action: #selector(LinkedLabel.handleTapOnLabel))
self.isUserInteractionEnabled = true
self.addGestureRecognizer(tap)
}
override var attributedText: NSAttributedString?{
didSet{
if let _attributedText = attributedText{
self.textStorage = NSTextStorage(attributedString: _attributedText)
self.layoutManager.addTextContainer(self.textContainer)
self.textStorage?.addLayoutManager(self.layoutManager)
self.textContainer.lineFragmentPadding = 0.0;
self.textContainer.lineBreakMode = self.lineBreakMode;
self.textContainer.maximumNumberOfLines = self.numberOfLines;
}
}
}
func handleTapOnLabel(tapGesture:UITapGestureRecognizer){
let locationOfTouchInLabel = tapGesture.location(in: tapGesture.view)
let labelSize = tapGesture.view?.bounds.size
let textBoundingBox = self.layoutManager.usedRect(for: self.textContainer)
let textContainerOffset = CGPoint(x: ((labelSize?.width)! - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x, y: ((labelSize?.height)! - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y)
let locationOfTouchInTextContainer = CGPoint(x: locationOfTouchInLabel.x - textContainerOffset.x, y: locationOfTouchInLabel.y - textContainerOffset.y)
let indexOfCharacter = self.layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: self.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
self.attributedText?.enumerateAttribute(NSLinkAttributeName, in: NSMakeRange(0, (self.attributedText?.length)!), options: NSAttributedString.EnumerationOptions(rawValue: UInt(0)), using:{
(attrs: Any?, range: NSRange, stop: UnsafeMutablePointer<ObjCBool>) in
if NSLocationInRange(indexOfCharacter, range){
if let _attrs = attrs{
UIApplication.shared.openURL(URL(string: _attrs as! String)!)
}
}
})
}}
This class was made by reusing code from this answer. In order to make attributed strings check out this answer. And here you can find how to make phone urls.
These methods are in ObjectNode
: the division is such that most read operations are included in JsonNode
, but mutations in ObjectNode
and ArrayNode
.
Note that you can just change first line to be:
ObjectNode jNode = mapper.createObjectNode();
// version ObjectMapper has should return ObjectNode type
or
ObjectNode jNode = (ObjectNode) objectCodec.createObjectNode();
// ObjectCodec is in core part, must be of type JsonNode so need cast
XmlDocument doc = new XmlDocument();
doc.Load("MonFichierXML.xml");
XmlNode node = doc.SelectSingleNode("Magasin");
XmlNodeList prop = node.SelectNodes("Items");
foreach (XmlNode item in prop)
{
items Temp = new items();
Temp.AssignInfo(item);
lstitems.Add(Temp);
}
Only this snippet does not work for me:
background-image: url(image_path('transparent_2x2.png'));
But rename stylename.scss to stylename.css.scss helps me.
Here is a simpler answer that worked for me.
First, per a Python Dev's comment above, setuptools is not required:
package_data is also available to pure distutils setup scripts
since 2.3. – Éric Araujo
That's great because putting a setuptools requirement on your package means you will have to install it also. In short:
from distutils.core import setup
setup(
# ...snip...
packages = ['pkgname'],
package_data = {'pkgname': ['license.txt']},
)
Try using RUN /bin/sh
instead of bash.
The approach you're looking for is FillDown
. Another way so you don't have to kick your head off every time is to store formulas in an array of strings. Combining them gives you a powerful method of inputting formulas by the multitude. Code follows:
Sub FillDown()
Dim strFormulas(1 To 3) As Variant
With ThisWorkbook.Sheets("Sheet1")
strFormulas(1) = "=SUM(A2:B2)"
strFormulas(2) = "=PRODUCT(A2:B2)"
strFormulas(3) = "=A2/B2"
.Range("C2:E2").Formula = strFormulas
.Range("C2:E11").FillDown
End With
End Sub
Screenshots:
Result as of line: .Range("C2:E2").Formula = strFormulas
:
Result as of line: .Range("C2:E11").FillDown
:
Of course, you can make it dynamic by storing the last row into a variable and turning it to something like .Range("C2:E" & LRow).FillDown
, much like what you did.
Hope this helps!
You could use a separate file, like npm_globals.txt
, instead of package.json
. This file would contain each module on a new line like this,
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
Then in the command line run,
< npm_globals.txt xargs npm install -g
Check that they installed properly with,
npm list -g --depth=0
As for whether you should do this or not, I think it all depends on use case. For most projects, this isn't necessary; and having your project's package.json
encapsulate these tools and dependencies together is much preferred.
But nowadays I find that I'm always installing create-react-app
and other CLI's globally when I jump on a new machine. It's nice to have an easy way to install a global tool and its dependencies when versioning doesn't matter much.
And nowadays, I'm using npx
, an npm package runner, instead of installing packages globally.
I was having same issue, way i have resolved is:
opened the MySQL installer. i was having a Reconfigure link on MYSQL Server row.
Clicked on it, it does reinstalled MySQL Server. after that opened MySQL Workbench, and it was working fine.
Function is not a property/method from range.
If you want to sum values then use the following:
Range("A1").Value = Application.Sum(Range(Cells(2, 1), Cells(3, 2)))
EDIT:
if you want the formula then use as follows:
Range("A1").Formula = "=SUM(" & Range(Cells(2, 1), Cells(3, 2)).Address(False, False) & ")"
'The two false after Adress is to define the address as relative (A2:B3).
'If you omit the parenthesis clause or write True instead, you can set the address
'as absolute ($A$2:$B$3).
In case you are allways going to use the same range address then you can use as Rory sugested:
Range("A1").Formula ="=Sum(A2:B3)"
You can use the .prop(propertyName)
function to get a property from the first element in the jQuery object.
var savedIndex = $(selectElement).prop('selectedIndex');
This keeps your code within the jQuery realm and also avoids the other option of using a selector to find the selected option. You can then restore it using the overload:
$(selectElement).prop('selectedIndex', savedIndex);
I changed the import sequence without fixing the problem, until finally I installed moments and tempus dominius (Core and bootrap), using npm and include them in boostrap.js
try {
window.Popper = require('popper.js').default;
window.$ = window.jQuery = require('jquery');
require('moment'); /*added*/
require('bootstrap');
require('tempusdominus-bootstrap-4');/*added*/} catch (e) {}
People seemed to be against RegEx for this. Why?
(\s*'[^']+'|\s*[^,]+)(?=,|$)
Here's the code. I also made a fiddle.
String.prototype.splitCSV = function(sep) {
var regex = /(\s*'[^']+'|\s*[^,]+)(?=,|$)/g;
return matches = this.match(regex);
}
var string = "'string, duppi, du', 23, 'string, duppi, du', lala";
var parsed = string.splitCSV();
alert(parsed.join('|'));
Use Runtime to call Curl. This code works for both Ubuntu and Windows.
String[] commands = new String {"curl", "-X", "GET", "http://checkip.amazonaws.com"};
Process process = Runtime.getRuntime().exec(commands);
BufferedReader reader = new BufferedReader(new
InputStreamReader(process.getInputStream()));
String line;
String response;
while ((line = reader.readLine()) != null) {
response.append(line);
}
without mentioning schema also you can get the required details Try this query->
select column_name,data_type from information_schema.columns where table_name = 'table_name';
UPDATE: As of Mongo version 3.6, this answer is no longer valid as the mentioned issue was fixed and there are ways to achieve this. Please check other answers.
At this moment it is not possible to use the positional operator to update all items in an array. See JIRA http://jira.mongodb.org/browse/SERVER-1243
As a work around you can:
Use a function like this:
CREATE function [dbo].[list_to_table] (@list varchar(4000))
returns @tab table (item varchar(100))
begin
if CHARINDEX(',',@list) = 0 or CHARINDEX(',',@list) is null
begin
insert into @tab (item) values (@list);
return;
end
declare @c_pos int;
declare @n_pos int;
declare @l_pos int;
set @c_pos = 0;
set @n_pos = CHARINDEX(',',@list,@c_pos);
while @n_pos > 0
begin
insert into @tab (item) values (SUBSTRING(@list,@c_pos+1,@n_pos - @c_pos-1));
set @c_pos = @n_pos;
set @l_pos = @n_pos;
set @n_pos = CHARINDEX(',',@list,@c_pos+1);
end;
insert into @tab (item) values (SUBSTRING(@list,@l_pos+1,4000));
return;
end;
Instead of using like, you make an inner join with the table returned by the function:
select * from table_1 where id in ('a','b','c')
becomes
select * from table_1 a inner join [dbo].[list_to_table] ('a,b,c') b on (a.id = b.item)
In an unindexed 1M record table the second version took about half the time...
cheers
use cv::mat::setto
img.setTo(cv::Scalar(redVal,greenVal,blueVal))
You give the name of your file, the path of the directory to search, and let it make the job.
private static String getPath(String drl, String whereIAm) {
File dir = new File(whereIAm); //StaticMethods.currentPath() + "\\src\\main\\resources\\" +
for(File e : dir.listFiles()) {
if(e.isFile() && e.getName().equals(drl)) {return e.getPath();}
if(e.isDirectory()) {
String idiot = getPath(drl, e.getPath());
if(idiot != null) {return idiot;}
}
}
return null;
}
For some purposes, HtmlUtils:
import org.springframework.web.util.HtmlUtils;
[...]
HtmlUtils.htmlEscapeDecimal("&"); //gives &
HtmlUtils.htmlEscape("&"); //gives &
You can simply use the method change
of JQuery to get the value of the current radio checked with the following code:
$(document).on('change', '[type="radio"]', function() {
var currentlyValue = $(this).val(); // Get the radio checked value
alert('Currently value: '+currentlyValue); // Show a alert with the current value
});
You can change the selector '[type="radio"]'
for a class or id that you want.
I have learned it is also possible to do this with the exec-maven-plugin if you're doing a "standalone" java app.
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${maven.exec.plugin.version}</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>${exec.main-class}</mainClass>
<systemProperties>
<systemProperty>
<key>myproperty</key>
<value>myvalue</value>
</systemProperty>
</systemProperties>
</configuration>
</plugin>
There is a firefox plugin that saves the whole page's HTML, CSS, etc.. but I have not seen one that does a partial save.
I remember IE 5.5 had what you were looking for though ;)
You can create a unique index that accept multiple NULLs with a WHERE
clause. See the answer below.
You cannot create a UNIQUE constraint and allow NULLs. You need set a default value of NEWID().
Update the existing values to NEWID() where NULL before creating the UNIQUE constraint.
unset($array[$index]);
I've been wrestling with this, and I know there are other options, but I've come to the conclusion the safest pattern is:
create table destination_old as select * from destination;
drop table destination;
create table destination as select
d.*, s.country
from destination_old d left join source s
on d.id=s.id;
It's safe because you have a copy of destination
before you altered it. I suspect that update statements with joins weren't included in SQLite because they're powerful but a bit risky.
Using the pattern above you end up with two country
fields. You can avoid that by explicitly stating all of the columns you want to retrieve from destination_old
and perhaps using coalesce
to retrieve the values from destination_old
if the country
field in source
is null. So for example:
create table destination as select
d.field1, d.field2,...,coalesce(s.country,d.country) country
from destination_old d left join source s
on d.id=s.id;
BUT I would like to avoid the need of knowing the other branches names.
I don't think this is possible: a branch in Git is always based on another one or at least on another commit, as explained in "git diff doesn't show enough":
You need a reference point for your log to show the right commits.
As mentioned in "GIT - Where did I branch from?":
branches are simply pointers to certain commits in a DAG
So even if git log master..mybranch
is one answer, it would still show too many commits, if mybranch
is based on myotherbranch
, itself based on master
.
In order to find that reference (the origin of your branch), you can only parse commits and see in which branch they are, as seen in:
As mentionned in comments, this is the updated solution in favor of Icon object with documentation.
Use Icon object
var icon = {
url: "../res/sit_marron.png", // url
scaledSize: new google.maps.Size(50, 50), // scaled size
origin: new google.maps.Point(0,0), // origin
anchor: new google.maps.Point(0, 0) // anchor
};
posicion = new google.maps.LatLng(latitud,longitud)
marker = new google.maps.Marker({
position: posicion,
map: map,
icon: icon
});
I've done this with PowerShell:
function DownloadFromFtp($destination, $ftp_uri, $user, $pass){
$dirs = GetDirecoryTree $ftp_uri $user $pass
foreach($dir in $dirs){
$path = [io.path]::Combine($destination,$dir)
if ((Test-Path $path) -eq $false) {
"Creating $path ..."
New-Item -Path $path -ItemType Directory | Out-Null
}else{
"Exists $path ..."
}
}
$files = GetFilesTree $ftp_uri $user $pass
foreach($file in $files){
$source = [io.path]::Combine($ftp_uri,$file)
$dest = [io.path]::Combine($destination,$file)
"Downloading $source ..."
Get-FTPFile $source $dest $user $pass
}
}
function UploadToFtp($artifacts, $ftp_uri, $user, $pass){
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
foreach($item in Get-ChildItem -recurse $artifacts){
$relpath = [system.io.path]::GetFullPath($item.FullName).SubString([system.io.path]::GetFullPath($artifacts).Length + 1)
if ($item.Attributes -eq "Directory"){
try{
Write-Host Creating $item.Name
$makeDirectory = [System.Net.WebRequest]::Create($ftp_uri+$relpath);
$makeDirectory.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
$makeDirectory.Method = [System.Net.WebRequestMethods+FTP]::MakeDirectory;
$makeDirectory.GetResponse();
}catch [Net.WebException] {
Write-Host $item.Name probably exists ...
}
continue;
}
"Uploading $item..."
$uri = New-Object System.Uri($ftp_uri+$relpath)
$webclient.UploadFile($uri, $item.FullName)
}
}
function Get-FTPFile ($Source,$Target,$UserName,$Password)
{
$ftprequest = [System.Net.FtpWebRequest]::create($Source)
$ftprequest.Credentials = New-Object System.Net.NetworkCredential($username,$password)
$ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
$ftprequest.UseBinary = $true
$ftprequest.KeepAlive = $false
$ftpresponse = $ftprequest.GetResponse()
$responsestream = $ftpresponse.GetResponseStream()
$targetfile = New-Object IO.FileStream ($Target,[IO.FileMode]::Create)
[byte[]]$readbuffer = New-Object byte[] 1024
do{
$readlength = $responsestream.Read($readbuffer,0,1024)
$targetfile.Write($readbuffer,0,$readlength)
}
while ($readlength -ne 0)
$targetfile.close()
}
#task ListFiles {
#
# $files = GetFilesTree 'ftp://127.0.0.1/' "web" "web"
# $files | ForEach-Object {Write-Host $_ -foregroundcolor cyan}
#}
function GetDirecoryTree($ftp, $user, $pass){
$creds = New-Object System.Net.NetworkCredential($user,$pass)
$files = New-Object "system.collections.generic.list[string]"
$folders = New-Object "system.collections.generic.queue[string]"
$folders.Enqueue($ftp)
while($folders.Count -gt 0){
$fld = $folders.Dequeue()
$newFiles = GetAllFiles $creds $fld
$dirs = GetDirectories $creds $fld
foreach ($line in $dirs){
$dir = @($newFiles | Where { $line.EndsWith($_) })[0]
[void]$newFiles.Remove($dir)
$folders.Enqueue($fld + $dir + "/")
[void]$files.Add($fld.Replace($ftp, "") + $dir + "/")
}
}
return ,$files
}
function GetFilesTree($ftp, $user, $pass){
$creds = New-Object System.Net.NetworkCredential($user,$pass)
$files = New-Object "system.collections.generic.list[string]"
$folders = New-Object "system.collections.generic.queue[string]"
$folders.Enqueue($ftp)
while($folders.Count -gt 0){
$fld = $folders.Dequeue()
$newFiles = GetAllFiles $creds $fld
$dirs = GetDirectories $creds $fld
foreach ($line in $dirs){
$dir = @($newFiles | Where { $line.EndsWith($_) })[0]
[void]$newFiles.Remove($dir)
$folders.Enqueue($fld + $dir + "/")
}
$newFiles | ForEach-Object {
$files.Add($fld.Replace($ftp, "") + $_)
}
}
return ,$files
}
function GetDirectories($creds, $fld){
$dirs = New-Object "system.collections.generic.list[string]"
$operation = [System.Net.WebRequestMethods+Ftp]::ListDirectoryDetails
$reader = GetStream $creds $fld $operation
while (($line = $reader.ReadLine()) -ne $null) {
if ($line.Trim().ToLower().StartsWith("d") -or $line.Contains(" <DIR> ")) {
[void]$dirs.Add($line)
}
}
$reader.Dispose();
return ,$dirs
}
function GetAllFiles($creds, $fld){
$newFiles = New-Object "system.collections.generic.list[string]"
$operation = [System.Net.WebRequestMethods+Ftp]::ListDirectory
$reader = GetStream $creds $fld $operation
while (($line = $reader.ReadLine()) -ne $null) {
[void]$newFiles.Add($line.Trim())
}
$reader.Dispose();
return ,$newFiles
}
function GetStream($creds, $url, $meth){
$ftp = [System.Net.WebRequest]::Create($url)
$ftp.Credentials = $creds
$ftp.Method = $meth
$response = $ftp.GetResponse()
return New-Object IO.StreamReader $response.GetResponseStream()
}
Export-ModuleMember UploadToFtp, DownLoadFromFtp
Say, you have the following:
std::vector<myObject>::const_iterator first = vObj.begin();
Then the first object in the vector is: *first
. To get the address, use: &(*first)
.
However, in keeping with the STL design, I'd suggest return an iterator instead if you plan to pass it around later on to STL algorithms.
pep8 was recently added to PyPi.
It is now super easy to check your code against pep8.
One of the problem with this code is here :
name += contactName[];
This instruction won't insert anything in the array. Instead it will concatenate the current value of the variable name with the string representation of the contactName array.
Instead use this:
contactName[index] = name;
this instruction will store the variable name in the contactName array at the index index
.
The second problem you have is that you don't have the variable index
.
What you can do is a loop with 12 iterations to fill all your arrays. (and index
will be your iteration variable)
According to this posting by the lead Jenkins developer, Kohsuke Kawaguchi, in 2009, there is no group support for the built-in Jenkins user database. Group support is only usable when integrating Jenkins with LDAP or Active Directory. This appears to be the same in 2012.
However, as Vadim wrote in his answer, you don't need group support for the built-in Jenkins user database, thanks to the Role strategy plug-in.
I had a similar issue in windows 7 + ubuntu 12.04 as guest. I resolved by
For multiselect option:
$('#test').val()
returns list of selected values.
$('#test option').length
returns total number of options (both selected and not selected)
EDIT: Now you can use docker exec -it "id of running container" bash
(doc)
Previously, the answer to this question was:
If you really must and you are in a debug environment, you can do this: sudo lxc-attach -n <ID>
Note that the id needs to be the full one (docker ps -notrunc
).
However, I strongly recommend against this.
notice: -notrunc
is deprecated, it will be replaced by --no-trunc
soon.
Maybe you should have a look at Mapquests Traffic API: http://www.mapquestapi.com/traffic/
The webservice is unfortunately only available for some citys in the US, I think. But probably it solves your problem.
I always go back to this article SQL Server 2005 XQuery and XML-DML - Part 1 to know how to use the XML features in SQL Server 2005.
For basic XPath know-how, I'd recommend the W3Schools tutorial.
The primary purpose is to avoid chained indexing and eliminate the SettingWithCopyWarning
.
Here chained indexing is something like dfc['A'][0] = 111
The document said chained indexing should be avoided in Returning a view versus a copy. Here is a slightly modified example from that document:
In [1]: import pandas as pd
In [2]: dfc = pd.DataFrame({'A':['aaa','bbb','ccc'],'B':[1,2,3]})
In [3]: dfc
Out[3]:
A B
0 aaa 1
1 bbb 2
2 ccc 3
In [4]: aColumn = dfc['A']
In [5]: aColumn[0] = 111
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
In [6]: dfc
Out[6]:
A B
0 111 1
1 bbb 2
2 ccc 3
Here the aColumn
is a view and not a copy from the original DataFrame, so modifying aColumn
will cause the original dfc
be modified too. Next, if we index the row first:
In [7]: zero_row = dfc.loc[0]
In [8]: zero_row['A'] = 222
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
In [9]: dfc
Out[9]:
A B
0 111 1
1 bbb 2
2 ccc 3
This time zero_row
is a copy, so the original dfc
is not modified.
From these two examples above, we see it's ambiguous whether or not you want to change the original DataFrame. This is especially dangerous if you write something like the following:
In [10]: dfc.loc[0]['A'] = 333
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
In [11]: dfc
Out[11]:
A B
0 111 1
1 bbb 2
2 ccc 3
This time it didn't work at all. Here we wanted to change dfc
, but we actually modified an intermediate value dfc.loc[0]
that is a copy and is discarded immediately. It’s very hard to predict whether the intermediate value like dfc.loc[0]
or dfc['A']
is a view or a copy, so it's not guaranteed whether or not original DataFrame will be updated. That's why chained indexing should be avoided, and pandas generates the SettingWithCopyWarning
for this kind of chained indexing update.
Now is the use of .copy()
. To eliminate the warning, make a copy to express your intention explicitly:
In [12]: zero_row_copy = dfc.loc[0].copy()
In [13]: zero_row_copy['A'] = 444 # This time no warning
Since you are modifying a copy, you know the original dfc
will never change and you are not expecting it to change. Your expectation matches the behavior, then the SettingWithCopyWarning
disappears.
Note, If you do want to modify the original DataFrame, the document suggests you use loc
:
In [14]: dfc.loc[0,'A'] = 555
In [15]: dfc
Out[15]:
A B
0 555 1
1 bbb 2
2 ccc 3
To launch command prompt in administrator mode
attrib -h -r -s /s /d "location of the drive letter:" \*.*
You'll need to use the HTML()
or display()
functions from IPython's display module:
from IPython.display import display, HTML
# Assuming that dataframes df1 and df2 are already defined:
print "Dataframe 1:"
display(df1)
print "Dataframe 2:"
display(HTML(df2.to_html()))
Note that if you just print df1.to_html()
you'll get the raw, unrendered HTML.
You can also import from IPython.core.display
with the same effect
It's old question but just in case someone bump on this tread...
var input = document.getElementById("your_input");
var file = input.value.split("\\");
var fileName = file[file.length-1];
No need for regex, jQuery....
One solution is to use JavaScript to add the required CSS classes after the page is ready. For example, styling django form output with bootstrap classes (jQuery used for brevity):
<script type="text/javascript">
$(document).ready(function() {
$('#some_django_form_id').find("input[type='text'], select, textarea").each(function(index, element) {
$(element).addClass("form-control");
});
});
</script>
This avoids the ugliness of mixing styling specifics with your business logic.
You didn't say what you needed this list for. If something used as a blacklist for password checks is enough cracklib might be good for you. It contains over 1.5M words.
The good way to get all the members from a group is to, make the DN of the group as the searchDN and pass the "member" as attribute to get in the search function. All of the members of the group can now be found by going through the attribute values returned by the search. The filter can be made generic like (objectclass=*).
Inserting data into the middle of a text file is not a simple task. If possible, you should append it to the end of your file.
The easiest way to append data some text file is to use build-in fs.appendFile(filename, data[, options], callback)
function from fs
module:
var fs = require('fs')
fs.appendFile('log.txt', 'new data', function (err) {
if (err) {
// append failed
} else {
// done
}
})
But if you want to write data to log file several times, then it'll be best to use fs.createWriteStream(path[, options])
function instead:
var fs = require('fs')
var logger = fs.createWriteStream('log.txt', {
flags: 'a' // 'a' means appending (old data will be preserved)
})
logger.write('some data') // append string to your file
logger.write('more data') // again
logger.write('and more') // again
Node will keep appending new data to your file every time you'll call .write
, until your application will be closed, or until you'll manually close the stream calling .end
:
logger.end() // close string
While I hate actually having to use svn when dealing with git repos :/ I use this all the time;
function git-scp() (
URL="$1" && shift 1
svn export ${URL/blob\/master/trunk}
)
This allows you to copy out from the github url without modification. Usage;
--- /tmp » git-scp https://github.com/dgraph-io/dgraph/blob/master/contrib/config/kubernetes/helm 1 ?
A helm
A helm/Chart.yaml
A helm/README.md
A helm/values.yaml
Exported revision 6367.
--- /tmp » ls | grep helm
Permissions Size User Date Modified Name
drwxr-xr-x - anthony 2020-01-07 15:53 helm/
Try executing this in your browser console or in a node.js repl.
var string = ' ';
string ? true : false;
//-> true
string = '';
string ? true : false;
//-> false
Therefore, a simple branching construct will suffice for the test.
if(string) {
// string is not empty
}
I had the same issue recently and ended up creating a NuGet package for this.
This implements a standard heap-based priority queue. It also has all the usual niceties of the BCL collections: ICollection<T>
and IReadOnlyCollection<T>
implementation, custom IComparer<T>
support, ability to specify an initial capacity, and a DebuggerTypeProxy
to make the collection easier to work with in the debugger.
There is also an Inline version of the package which just installs a single .cs file into your project (useful if you want to avoid taking externally-visible dependencies).
More information is available on the github page.
take advantage of the methods offered by a Series:
>>> import pandas as pd
>>> y = [0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1]
>>> pd.Series(y).value_counts()
0 8
1 4
dtype: int64
A jsfiddle for custom tooltip pattern is Here
It is based on CSS Positioning and pseduo class selectors
Check MDN docs for cross-browser support of pseudo classes
<!-- HTML -->
<p>
<a href="http://www.google.com/" class="tooltip">
I am a
<span> (This website rocks) </span></a> a developer.
</p>
/*CSS*/
a.tooltip {
position: relative;
}
a.tooltip span {
display: none;
}
a.tooltip:hover span, a.tooltip:focus span {
display:block;
position:absolute;
top:1em;
left:1.5em;
padding: 0.2em 0.6em;
border:1px solid #996633;
background-color:#FFFF66;
color:#000;
}
public void selectImageAndResize(){
int returnVal = jFileChooser.showOpenDialog(this); //open jfilechooser
if (returnVal == jFileChooser.APPROVE_OPTION) { //select image
File file = jFileChooser.getSelectedFile(); //get the image
BufferedImage bi;
try {
//
//transforms selected file to buffer
//
bi=ImageIO.read(file);
ImageIcon iconimage = new ImageIcon(bi);
//
//get image dimensions
//
BufferedImage bi2 = new BufferedImage(iconimage.getIconWidth(), iconimage.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
iconimage.paintIcon(null, g, 0,0);
g.dispose();
//
//resize image according to jlabel
//
BufferedImage resizedimage=resize(bi,jLabel2.getWidth(), jLabel2.getHeight());
ImageIcon resizedicon=new ImageIcon(resizedimage);
jLabel2.setIcon(resizedicon);
} catch (Exception ex) {
System.out.println("problem accessing file"+file.getAbsolutePath());
}
}
else {
System.out.println("File access cancelled by user.");
}
}
int.from_bytes( bytes, byteorder, *, signed=False )
doesn't work with me I used function from this website, it works well
https://coderwall.com/p/x6xtxq/convert-bytes-to-int-or-int-to-bytes-in-python
def bytes_to_int(bytes):
result = 0
for b in bytes:
result = result * 256 + int(b)
return result
def int_to_bytes(value, length):
result = []
for i in range(0, length):
result.append(value >> (i * 8) & 0xff)
result.reverse()
return result
You can just make sure your css file parses AFTER boostrap.css , like so:
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/myFile.css" rel="stylesheet">
Principled Design of the Modern Web Architecture by Roy T. Fielding and Richard N. Taylor, i.e. sequence of works from all REST terminology came from, contains definition of client-server interaction:
All REST interactions are stateless. That is, each request contains all of the information necessary for a connector to understand the request, independent of any requests that may have preceded it.
This restriction accomplishes four functions, 1st and 3rd are important in this particular case:
And now lets go back to your security case. Every single request should contains all required information, and authorization/authentication is not an exception. How to achieve this? Literally send all required information over wires with every request.
One of examples how to archeive this is hash-based message authentication code or HMAC. In practice this means adding a hash code of current message to every request. Hash code calculated by cryptographic hash function in combination with a secret cryptographic key. Cryptographic hash function is either predefined or part of code-on-demand REST conception (for example JavaScript). Secret cryptographic key should be provided by server to client as resource, and client uses it to calculate hash code for every request.
There are a lot of examples of HMAC implementations, but I'd like you to pay attention to the following three:
If client knows the secret key, then it's ready to operate with resources. Otherwise he will be temporarily redirected (status code 307 Temporary Redirect) to authorize and to get secret key, and then redirected back to the original resource. In this case there is no need to know beforehand (i.e. hardcode somewhere) what the URL to authorize the client is, and it possible to adjust this schema with time.
Hope this will helps you to find the proper solution!
Using Spring Data JPA there is a provision to select specific columns from database
---- In DAOImpl ----
@Override
@Transactional
public List<Employee> getAllEmployee() throws Exception {
LOGGER.info("Inside getAllEmployee");
List<Employee> empList = empRepo.getNameAndCityOnly();
return empList;
}
---- In Repo ----
public interface EmployeeRepository extends CrudRepository<Employee,Integer> {
@Query("select e.name, e.city from Employee e" )
List<Employee> getNameAndCityOnly();
}
It worked 100% in my case. Thanks.
In case someone is interested in getting results as 60 becomes 01:00 hours, 120 becomes 02:00 hours, 150 becomes 02:30 hours, this function might help:
create FUNCTION [dbo].[MinutesToHHMM]
(
@minutes int
)
RETURNS varchar(30)
AS
BEGIN
declare @h int
set @h= @minutes / 60
declare @mins varchar(2)
set @mins= iif(@minutes%60<10,concat('0',cast((@minutes % 60) as varchar(2))),cast((@minutes % 60) as varchar(2)))
return iif(@h <10, concat('0', cast(@h as varchar(5)),':',@mins)
,concat(cast(@h as varchar(5)),':',@mins))
end
Take a look at the System
log in Windows EventViewer (eventvwr
from the command line).
You should see entries with source as 'Service Control Manager'. e.g. on my WinXP machine,
Event Type: Information
Event Source: Service Control Manager
Event Category: None
Event ID: 7036
Date: 7/1/2009
Time: 12:09:43 PM
User: N/A
Computer: MyMachine
Description:
The Background Intelligent Transfer Service service entered the running state.
For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
Maybe this will help.
var inputVal = $(this).closest('tr').find("td:eq(x) input").val();
Here is a link from developer.nokia.com wiki pages, which explains how to install Windows Phone 8 SDK on a Virtual Machine with Working Emulator
And another link here
AFAIK, it is not possible to directly install WP8 SDK in Windows 7, because WP8 sdk is VS 2012 supported and also its emulator works on a Hyper-V (which is integrated into the Windows 8).
Try this code:
<select name="wgtmsr" id="wgtmsr">
<option value="kg">Kg</option>
<option value="gm">Gm</option>
<option value="pound">Pound</option>
<option value="MetricTon">Metric ton</option>
<option value="litre">Litre</option>
<option value="ounce">Ounce</option>
</select>
CSS:
#wgtmsr{
width:150px;
}
If you want to change the width of the option you can do this in your css:
#wgtmsr option{
width:150px;
}
Maybe you have a conflict in your css rules that override the width of your select
Numeric.product
( or
reduce(lambda x,y:x*y,[3,4,5])
)
If you insist on using yum
, try yum install apt
.
As read on this site:
Link
use this
<div id="date">23/05/2013</div>
<script type="text/javascript">
$(document).ready(function(){
var x = $("#date").text();
x.text(x.substring(0, 2) + '<br />'+x.substring(3));
});
</script>
Properties has become legacy. Preferences class is preferred to Properties.
A node in a hierarchical collection of preference data. This class allows applications to store and retrieve user and system preference and configuration data. This data is stored persistently in an implementation-dependent backing store. Typical implementations include flat files, OS-specific registries, directory servers and SQL databases. The user of this class needn't be concerned with details of the backing store.
Unlike properties which are String based key-value pairs, The Preferences
class has several methods used to get and put primitive data in the Preferences data store. We can use only the following types of data:
To load the the properties file, either you can provide absolute path Or use getResourceAsStream()
if the properties file is present in your classpath.
package com.mypack.test;
import java.io.*;
import java.util.*;
import java.util.prefs.Preferences;
public class PreferencesExample {
public static void main(String args[]) throws FileNotFoundException {
Preferences ps = Preferences.userNodeForPackage(PreferencesExample.class);
// Load file object
File fileObj = new File("d:\\data.xml");
try {
FileInputStream fis = new FileInputStream(fileObj);
ps.importPreferences(fis);
System.out.println("Prefereces:"+ps);
System.out.println("Get property1:"+ps.getInt("property1",10));
} catch (Exception err) {
err.printStackTrace();
}
}
}
xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE preferences SYSTEM 'http://java.sun.com/dtd/preferences.dtd'>
<preferences EXTERNAL_XML_VERSION="1.0">
<root type="user">
<map />
<node name="com">
<map />
<node name="mypack">
<map />
<node name="test">
<map>
<entry key="property1" value="80" />
<entry key="property2" value="Red" />
</map>
</node>
</node>
</node>
</root>
</preferences>
Have a look at this article on internals of preferences store
Import paths are relative to your $GOPATH
and $GOROOT
environment variables. For example, with the following $GOPATH
:
GOPATH=/home/me/go
Packages located in /home/me/go/src/lib/common
and /home/me/go/src/lib/routers
are imported respectively as:
import (
"lib/common"
"lib/routers"
)
PHP uses one of two methods to keep track of sessions. If cookies are enabled, like in your case, it uses them.
If cookies are disabled, it uses the URL. Although this can be done securely, it's harder and it often, well, isn't. See, e.g., session fixation.
Search for it, you will get lots of SEO advice. The conventional wisdom is that you should use the cookies, but php will keep track of the session either way.
I use SwitchToThisWindow to bring the application to the forefront as in this example:
static class Program
{
[DllImport("User32.dll", SetLastError = true)]
static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
bool createdNew;
int iP;
Process currentProcess = Process.GetCurrentProcess();
Mutex m = new Mutex(true, "XYZ", out createdNew);
if (!createdNew)
{
// app is already running...
Process[] proc = Process.GetProcessesByName("XYZ");
// switch to other process
for (iP = 0; iP < proc.Length; iP++)
{
if (proc[iP].Id != currentProcess.Id)
SwitchToThisWindow(proc[0].MainWindowHandle, true);
}
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new form());
GC.KeepAlive(m);
}
Inspired by Michal B. answer. If you use bootstrap..
label.btn {_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
label.btn input {_x000D_
opacity: 0;_x000D_
position: absolute;_x000D_
}_x000D_
_x000D_
label.btn span {_x000D_
text-align: center;_x000D_
padding: 6px 12px;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
label.btn input:checked+span {_x000D_
background-color: rgb(80, 110, 228);_x000D_
color: #fff;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">_x000D_
<div>_x000D_
<label class="btn btn-outline-primary"><input type="radio" name="toggle"><span>One</span></label>_x000D_
<label class="btn btn-outline-primary"><input type="radio" name="toggle"><span>Two</span></label>_x000D_
<label class="btn btn-outline-primary"><input type="radio" name="toggle"><span>Three</span></label>_x000D_
</div>
_x000D_
Here's a good mnemonic. Apply uses Arrays and Always takes one or two Arguments. When you use Call you have to Count the number of arguments.
If you want to use a function form a package or module in python you have to import and reference them. For example normally you do the following to draw 5 points( [1,5],[2,4],[3,3],[4,2],[5,1]) in the space:
import matplotlib.pyplot
matplotlib.pyplot.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
matplotlib.pyplot.show()
In your solution
from matplotlib import*
This imports the package matplotlib and "plot is not defined" means there is no plot function in matplotlib you can access directly, but instead if you import as
from matplotlib.pyplot import *
plot([1,2,3,4,5],[5,4,3,2,1],"bx")
show()
Now you can use any function in matplotlib.pyplot without referencing them with matplotlib.pyplot.
I would recommend you to name imports you have, in this case you can prevent disambiguation and future problems with the same function names. The last and clean version of above example looks like:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
plt.show()
// This should be a function, because in certain JavaScript engines (V8, for
// example, try block kills many optimizations).
function isFunction(func) {
// For some reason, function constructor doesn't accept anonymous functions.
// Also, this check finds callable objects that aren't function (such as,
// regular expressions in old WebKit versions), as according to EcmaScript
// specification, any callable object should have typeof set to function.
if (typeof func === 'function')
return true
// If the function isn't a string, it's probably good idea to return false,
// as eval cannot process values that aren't strings.
if (typeof func !== 'string')
return false
// So, the value is a string. Try creating a function, in order to detect
// syntax error.
try {
// Create a function with string func, in order to detect whatever it's
// an actual function. Unlike examples with eval, it should be actually
// safe to use with any string (provided you don't call returned value).
Function(func)
return true
}
catch (e) {
// While usually only SyntaxError could be thrown (unless somebody
// modified definition of something used in this function, like
// SyntaxError or Function, it's better to prepare for unexpected.
if (!(e instanceof SyntaxError)) {
throw e
}
return false
}
}
DBContext.TestAddresses.Select(m => m.NAME).Distinct();
if you have multiple column do like this:
DBContext.TestAddresses.Select(m => new {m.NAME, m.ID}).Distinct();
In this example no duplicate CategoryId and no CategoryName i hope this will help you
You can use custom ActionFilter in Web Api to validate model:
public class DRFValidationFilters : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext.Request
.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
//BadRequest(actionContext.ModelState);
}
}
public override Task OnActionExecutingAsync(HttpActionContext actionContext,
CancellationToken cancellationToken)
{
return Task.Factory.StartNew(() =>
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext.Request
.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
}
});
}
public class AspirantModel
{
public int AspirantId { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string AspirantType { get; set; }
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$",
ErrorMessage = "Not a valid Phone number")]
public string MobileNumber { get; set; }
public int StateId { get; set; }
public int CityId { get; set; }
public int CenterId { get; set; }
[HttpPost]
[Route("AspirantCreate")]
[DRFValidationFilters]
public IHttpActionResult Create(AspirantModel aspirant)
{
if (aspirant != null)
{
}
else
{
return Conflict();
}
return Ok();
}
}
}
Register CustomAttribute class in webApiConfig.cs config.Filters.Add(new DRFValidationFilters());
Check here for the archived link originally used in this answer.
From that link:
In theory, the
onKeyDown
andonKeyUp
events represent keys being pressed or released, while theonKeyPress
event represents a character being typed. The implementation of the theory is not same in all browsers.
Try this (OS X only):
brew install homebrew/versions/gradle110
gradle build
You can use gradle tasks
to see all tasks available for the current project. No Android Studio
is needed here.
There isn't a 1-1 correspondence between IPv4 and IPv6 addresses (nor between IP addresses and devices), so what you're asking for generally isn't possible.
There is a particular range of IPv6 addresses that actually represent the IPv4 address space, but general IPv6 addresses will not be from this range.
From experience I'll just note that while it is the C++ way to put formerly-static functions into the anonymous namespace, older compilers can sometimes have problems with this. I currently work with a few compilers for our target platforms, and the more modern Linux compiler is fine with placing functions into the anonymous namespace.
But an older compiler running on Solaris, which we are wed to until an unspecified future release, will sometimes accept it, and other times flag it as an error. The error is not what worries me, it's what it might be doing when it accepts it. So until we go modern across the board, we are still using static (usually class-scoped) functions where we'd prefer the anonymous namespace.
Number of answer have been given even though I would like to give mine command . I used to frequently. It may help to someone.
mongoimport original.json -d databaseName -c yourcollectionName --jsonArray --drop
for finding out that user is new or old , Get user IP .
create a table for IPs and their visits timestamp .
check IF IP does not exists OR time()-saved_timestamp > 60*60*24 (for 1 day) ,edit the IP's timestamp to time()
(means now) and increase your view one .
else , do nothing .
FYI : user IP is stored in $_SERVER['REMOTE_ADDR']
variable
A typical best practice is not using long/int/short directly. Instead, according to specification of compilers and OS, wrap them into a header file to ensure they hold exactly the amount of bits that you want. Then use int8/int16/int32 instead of long/int/short. For example, on 32bit Linux, you could define a header like this
typedef char int8;
typedef short int16;
typedef int int32;
typedef unsigned int uint32;
This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.
There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.
The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like
1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host
EDIT
Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication
You have three options:
@Transient
method@PostLoad
entity listener@Formula
annotationWhile Hibernate allows you to use @Formula, with JPA, you can use the @PostLoad callback to populate a transient property with the result of some calculation:
@Column(name = "price")
private Double price;
@Column(name = "tax_percentage")
private Double taxes;
@Transient
private Double priceWithTaxes;
@PostLoad
private void onLoad() {
this.priceWithTaxes = price * taxes;
}
So, you can use the Hibernate @Formula
like this:
@Formula("""
round(
(interestRate::numeric / 100) *
cents *
date_part('month', age(now(), createdOn)
)
/ 12)
/ 100::numeric
""")
private double interestDollars;
The entity which has the table with foreign key in the database is the owning entity and the other table, being pointed at, is the inverse entity.
I'm not a big fan of Cygwin. It is good if you have some Unix code that requires a full POSIX system, I suppose. Even then, using it renders your programs GPL (due to the GPLed DLL), unless you pay Red Hat for a different license.
Most people should be using MinGW (and MSYS) instead. This gives you the Unix shell and utilities (even compilers, if you want them) without the purposely infectious DLL. Most of the folks using GNU compilers on Windows are using MinGW (although some don't realise it).
Just as importantly for your purposes, you can download the parts separately, rather than use the re-downloading installer.
The SourceForge download page is here. I'd suggest starting with the MSYS Base System package, which will give you the coreutils, Bash, make, tar, etc. If there's other stuff you need, you can pick and choose from the list of packages.
It really depends on what you're going for:
#if DEBUG
: The code in here won't even reach the IL on release.[Conditional("DEBUG")]
: This code will reach the IL, however calls to the method will be omitted unless DEBUG is set when the caller is compiled.Personally I use both depending on the situation:
Conditional("DEBUG") Example: I use this so that I don't have to go back and edit my code later during release, but during debugging I want to be sure I didn't make any typos. This function checks that I type a property name correctly when trying to use it in my INotifyPropertyChanged stuff.
[Conditional("DEBUG")]
[DebuggerStepThrough]
protected void VerifyPropertyName(String propertyName)
{
if (TypeDescriptor.GetProperties(this)[propertyName] == null)
Debug.Fail(String.Format("Invalid property name. Type: {0}, Name: {1}",
GetType(), propertyName));
}
You really don't want to create a function using #if DEBUG
unless you are willing to wrap every call to that function with the same #if DEBUG
:
#if DEBUG
public void DoSomething() { }
#endif
public void Foo()
{
#if DEBUG
DoSomething(); //This works, but looks FUGLY
#endif
}
versus:
[Conditional("DEBUG")]
public void DoSomething() { }
public void Foo()
{
DoSomething(); //Code compiles and is cleaner, DoSomething always
//exists, however this is only called during DEBUG.
}
#if DEBUG example: I use this when trying to setup different bindings for WCF communication.
#if DEBUG
public const String ENDPOINT = "Localhost";
#else
public const String ENDPOINT = "BasicHttpBinding";
#endif
In the first example, the code all exists, but is just ignored unless DEBUG is on. In the second example, the const ENDPOINT is set to "Localhost" or "BasicHttpBinding" depending on if DEBUG is set or not.
Update: I am updating this answer to clarify an important and tricky point. If you choose to use the ConditionalAttribute
, keep in mind that calls are omitted during compilation, and not runtime. That is:
MyLibrary.dll
[Conditional("DEBUG")]
public void A()
{
Console.WriteLine("A");
B();
}
[Conditional("DEBUG")]
public void B()
{
Console.WriteLine("B");
}
When the library is compiled against release mode (i.e. no DEBUG symbol), it will forever have the call to B()
from within A()
omitted, even if a call to A()
is included because DEBUG is defined in the calling assembly.
Also try directly startup:
sqlplus /nolog
conn / as sysdba
startup
As a workaround, you could use the timestamp (old and new) for checking though, that one is not updated when there are no changes to the row. (Possibly that is the source for confusion? Because that one is also called 'on update' but is not executed when no change occurs) Changes within one second will then not execute that part of the trigger, but in some cases that could be fine (like when you have an application that rejects fast changes anyway.)
For example, rather than
IF NEW.a <> OLD.a or NEW.b <> OLD.b /* etc, all the way to NEW.z <> OLD.z */
THEN
INSERT INTO bar (a, b) VALUES(NEW.a, NEW.b) ;
END IF
you could use
IF NEW.ts <> OLD.ts
THEN
INSERT INTO bar (a, b) VALUES(NEW.a, NEW.b) ;
END IF
Then you don't have to change your trigger every time you update the scheme (the issue you mentioned in the question.)
EDIT: Added full example
create table foo (a INT, b INT, ts TIMESTAMP);
create table bar (a INT, b INT);
INSERT INTO foo (a,b) VALUES(1,1);
INSERT INTO foo (a,b) VALUES(2,2);
INSERT INTO foo (a,b) VALUES(3,3);
DELIMITER ///
CREATE TRIGGER ins_sum AFTER UPDATE ON foo
FOR EACH ROW
BEGIN
IF NEW.ts <> OLD.ts THEN
INSERT INTO bar (a, b) VALUES(NEW.a, NEW.b);
END IF;
END;
///
DELIMITER ;
select * from foo;
+------+------+---------------------+
| a | b | ts |
+------+------+---------------------+
| 1 | 1 | 2011-06-14 09:29:46 |
| 2 | 2 | 2011-06-14 09:29:46 |
| 3 | 3 | 2011-06-14 09:29:46 |
+------+------+---------------------+
3 rows in set (0.00 sec)
-- UPDATE without change
UPDATE foo SET b = 3 WHERE a = 3;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1 Changed: 0 Warnings: 0
-- the timestamo didnt change
select * from foo WHERE a = 3;
+------+------+---------------------+
| a | b | ts |
+------+------+---------------------+
| 3 | 3 | 2011-06-14 09:29:46 |
+------+------+---------------------+
1 rows in set (0.00 sec)
-- the trigger didn't run
select * from bar;
Empty set (0.00 sec)
-- UPDATE with change
UPDATE foo SET b = 4 WHERE a=3;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
-- the timestamp changed
select * from foo;
+------+------+---------------------+
| a | b | ts |
+------+------+---------------------+
| 1 | 1 | 2011-06-14 09:29:46 |
| 2 | 2 | 2011-06-14 09:29:46 |
| 3 | 4 | 2011-06-14 09:34:59 |
+------+------+---------------------+
3 rows in set (0.00 sec)
-- and the trigger ran
select * from bar;
+------+------+---------------------+
| a | b | ts |
+------+------+---------------------+
| 3 | 4 | 2011-06-14 09:34:59 |
+------+------+---------------------+
1 row in set (0.00 sec)
It is working because of mysql's behavior on handling timestamps. The time stamp is only updated if a change occured in the updates.
Documentation is here:
https://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
desc foo;
+-------+-----------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-----------+------+-----+-------------------+-----------------------------+
| a | int(11) | YES | | NULL | |
| b | int(11) | YES | | NULL | |
| ts | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------+-----------+------+-----+-------------------+-----------------------------+
We can summarize by using summarize_at
, summarize_all
and summarize_if
on dplyr 0.7.4
. We can set the multiple columns and functions by using vars
and funs
argument as below code. The left-hand side of funs formula is assigned to suffix of summarized vars. In the dplyr 0.7.4
, summarise_each
(and mutate_each
) is already deprecated, so we cannot use these functions.
options(scipen = 100, dplyr.width = Inf, dplyr.print_max = Inf)
library(dplyr)
packageVersion("dplyr")
# [1] ‘0.7.4’
set.seed(123)
df <- data_frame(
a = sample(1:5, 10, replace=T),
b = sample(1:5, 10, replace=T),
c = sample(1:5, 10, replace=T),
d = sample(1:5, 10, replace=T),
grp = as.character(sample(1:3, 10, replace=T)) # For convenience, specify character type
)
df %>% group_by(grp) %>%
summarise_each(.vars = letters[1:4],
.funs = c(mean="mean"))
# `summarise_each()` is deprecated.
# Use `summarise_all()`, `summarise_at()` or `summarise_if()` instead.
# To map `funs` over a selection of variables, use `summarise_at()`
# Error: Strings must match column names. Unknown columns: mean
You should change to the following code. The following codes all have the same result.
# summarise_at
df %>% group_by(grp) %>%
summarise_at(.vars = letters[1:4],
.funs = c(mean="mean"))
df %>% group_by(grp) %>%
summarise_at(.vars = names(.)[1:4],
.funs = c(mean="mean"))
df %>% group_by(grp) %>%
summarise_at(.vars = vars(a,b,c,d),
.funs = c(mean="mean"))
# summarise_all
df %>% group_by(grp) %>%
summarise_all(.funs = c(mean="mean"))
# summarise_if
df %>% group_by(grp) %>%
summarise_if(.predicate = function(x) is.numeric(x),
.funs = funs(mean="mean"))
# A tibble: 3 x 5
# grp a_mean b_mean c_mean d_mean
# <chr> <dbl> <dbl> <dbl> <dbl>
# 1 1 2.80 3.00 3.6 3.00
# 2 2 4.25 2.75 4.0 3.75
# 3 3 3.00 5.00 1.0 2.00
You can also have multiple functions.
df %>% group_by(grp) %>%
summarise_at(.vars = letters[1:2],
.funs = c(Mean="mean", Sd="sd"))
# A tibble: 3 x 5
# grp a_Mean b_Mean a_Sd b_Sd
# <chr> <dbl> <dbl> <dbl> <dbl>
# 1 1 2.80 3.00 1.4832397 1.870829
# 2 2 4.25 2.75 0.9574271 1.258306
# 3 3 3.00 5.00 NA NA
You cannot. A basic numeric constant is considered an integer (or long if followed by a "L"), so you must explicitly downcast it to a byte to pass it as a parameter. As far as I know there is no shortcut.
FileInputStream fis = new FileInputStream(new File("C:/Test.xlsx"));
//create workbook instance
XSSFWorkbook wb = new XSSFWorkbook(fis);
//create a sheet object to retrieve the sheet
XSSFSheet sheet = wb.getSheetAt(0);
//to evaluate cell type
FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
for(Row row : sheet)
{
for(Cell cell : row)
{
switch(formulaEvaluator.evaluateInCell(cell).getCellTypeEnum())
{
case NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
default:
break;
}
}
System.out.println();
}
This code will work fine. Use getCellTypeEnum()
and to compare use just NUMERIC
or STRING
.
I also get the same error when i started my replicated zk, one of zkClient can not connect to localhost:2181, i checked the log file under apache-zookeeper-3.5.5-bin/logs directory, and found this:
2019-08-20 11:30:39,763 [myid:5] - WARN [QuorumPeermyid=5(secure=disabled):QuorumCnxManager@677] - Cannot open channel to 3 at election address /xxxx:3888 java.net.SocketTimeoutException: connect timed out at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:589) at org.apache.zookeeper.server.quorum.QuorumCnxManager.connectOne(QuorumCnxManager.java:648) at org.apache.zookeeper.server.quorum.QuorumCnxManager.connectOne(QuorumCnxManager.java:705) at org.apache.zookeeper.server.quorum.QuorumCnxManager.connectAll(QuorumCnxManager.java:733) at org.apache.zookeeper.server.quorum.FastLeaderElection.lookForLeader(FastLeaderElection.java:910) at org.apache.zookeeper.server.quorum.QuorumPeer.run(QuorumPeer.java:1247) 2019-08-20 11:30:44,768 [myid:5] - WARN [QuorumPeermyid=5(secure=disabled):QuorumCnxManager@677] - Cannot open channel to 4 at election address /xxxxxx:3888 java.net.SocketTimeoutException: connect timed out at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:589) at org.apache.zookeeper.server.quorum.QuorumCnxManager.connectOne(QuorumCnxManager.java:648) at org.apache.zookeeper.server.quorum.QuorumCnxManager.connectOne(QuorumCnxManager.java:705) at org.apache.zookeeper.server.quorum.QuorumCnxManager.connectAll(QuorumCnxManager.java:733) at org.apache.zookeeper.server.quorum.FastLeaderElection.lookForLeader(FastLeaderElection.java:910) at org.apache.zookeeper.server.quorum.QuorumPeer.run(QuorumPeer.java:1247) 2019-08-20 11:30:44,769 [myid:5] - INFO [QuorumPeermyid=5(secure=disabled):FastLeaderElection@919] - Notification time out: 51200
that means this zk server can not connect to other servers, and i found this server ping other servers fail, and after remove this server from the replica, the problem is solved.
hope this will be helpful.
nodeName
is the attribute you are looking for. For example:
var elt = document.getElementById('foo');
console.log(elt.nodeName);
Note that nodeName
returns the element name capitalized and without the angle brackets, which means that if you want to check if an element is an <div>
element you could do it as follows:
elt.nodeName == "DIV"
While this would not give you the expected results:
elt.nodeName == "<div>"
I think basic solutions to the question should be as below:
Supplier supplier=HashSet::new;
HashSet has=ls.stream().collect(Collectors.toCollection(supplier));
List lst = (List) ls.stream().filter(e->Collections.frequency(ls,e)>1).distinct().collect(Collectors.toList());
well, it is not recommended to perform a filter operation, but for better understanding, i have used it, moreover, there should be some custom filtration in future versions.
What you have initialized is a vector of vectors, so you definitely have to include a vector to be inserted("Pushed" in the terminology of vectors) in the original vector you have named matrix in your example.
One more thing, you cannot directly insert values in the vector using the operator "cin". Use a variable which takes input and then insert the same in the vector.
Please try this out :
int num;
for(int i=0; i<RR; i++){
vector<int>inter_mat; //Intermediate matrix to help insert(push) contents of whole row at a time
for(int j=0; j<CC; j++){
cin>>num; //Extra variable in helping push our number to vector
vin.push_back(num); //Inserting numbers in a row, one by one
}
v.push_back(vin); //Inserting the whole row at once to original 2D matrix
}
Building on the examples above I thought I'd throw in a way of transparently binding a controller variable to a service variable.
In the example below changes to the Controller $scope.count
variable will automatically be reflected in the Service count
variable.
In production we're actually using the this binding to update an id on a service which then asynchronously fetches data and updates its service vars. Further binding that means that controllers automagically get updated when the service updates itself.
The code below can be seen working at http://jsfiddle.net/xuUHS/163/
View:
<div ng-controller="ServiceCtrl">
<p> This is my countService variable : {{count}}</p>
<input type="number" ng-model="count">
<p> This is my updated after click variable : {{countS}}</p>
<button ng-click="clickC()" >Controller ++ </button>
<button ng-click="chkC()" >Check Controller Count</button>
</br>
<button ng-click="clickS()" >Service ++ </button>
<button ng-click="chkS()" >Check Service Count</button>
</div>
Service/Controller:
var app = angular.module('myApp', []);
app.service('testService', function(){
var count = 10;
function incrementCount() {
count++;
return count;
};
function getCount() { return count; }
return {
get count() { return count },
set count(val) {
count = val;
},
getCount: getCount,
incrementCount: incrementCount
}
});
function ServiceCtrl($scope, testService)
{
Object.defineProperty($scope, 'count', {
get: function() { return testService.count; },
set: function(val) { testService.count = val; },
});
$scope.clickC = function () {
$scope.count++;
};
$scope.chkC = function () {
alert($scope.count);
};
$scope.clickS = function () {
++testService.count;
};
$scope.chkS = function () {
alert(testService.count);
};
}
Generate all possible permutations
I'm using python3.4:
def calcperm(arr, size):
result = set([()])
for dummy_idx in range(size):
temp = set()
for dummy_lst in result:
for dummy_outcome in arr:
if dummy_outcome not in dummy_lst:
new_seq = list(dummy_lst)
new_seq.append(dummy_outcome)
temp.add(tuple(new_seq))
result = temp
return result
Test Cases:
lst = [1, 2, 3, 4]
#lst = ["yellow", "magenta", "white", "blue"]
seq = 2
final = calcperm(lst, seq)
print(len(final))
print(final)
If start time is a datetime type then you can use something like
SELECT BookingId, StartTime
FROM Booking
WHERE StartTime >= '2012-03-08 00:00:00.000'
AND StartTime <= '2012-03-08 01:00:00.000'
Obviously you would want to use your own values for the times but this should give you everything in that 1 hour period inclusive of both the upper and lower limit.
You can use the GETDATE() function to get todays current date.
You should generally try to avoid <b>
and <i>
. They were introduced for layouting the page (changing the way how it looks) in early HMTL versions prior to the creation of CSS, like the meanwhile removed font
tag, and were mainly kept for backward compatibility and because some forums allow inline HTML and that's an easy way to change the look of text (like BBCode using [i]
, you can use <i>
and so on).
Since the creation of CSS, layouting is actually nothing that should be done in HTML anymore, that's why CSS has been created in the first place (HTML == Structure, CSS == Layout). These tags may as well vanish in the future, after all you can just use CSS and span
tags to make text bold/italic if you need a "meaningless" font variation. HTML 5 still allows them but declares that marking text that way has no meaning.
<em>
and <strong>
on the other hand only says that something is "emphasized" or "strongly emphasized", it leaves it completely open to the browser how to render it. Most browsers will render em
as italic and strong
as bold as the standard suggests by default, but they are not forced to do that (they may use different colors, font sizes, fonts, whatever). You can use CSS to change the behavior the way you desire. You can make em
bold if you like and strong
bold and red, for example.
i have tried with craeting a new object without deleting the coulmns in Vue.js.
let data =this.selectedContactsDto[];
//selectedContactsDto[] = object with list of array objects created in my project
console.log(data); let newDataObj= data.map(({groupsList,customFields,firstname, ...item }) => item); console.log("newDataObj",newDataObj);
while(something.hasnext())
do something...
if(contains something to process){
do something...
break;
}
}
Just use the break statement;
For eg:this just prints "Breaking..."
while (true) {
if (true) {
System.out.println("Breaking...");
break;
}
System.out.println("Did this print?");
}
I found I could improve the situation a little with CSS dedicated to Webkit (Safari, Chrome). However, I had to set a fixed width and height on the field because the font change will resize the field.
@media screen and (-webkit-min-device-pixel-ratio:0){ /* START WEBKIT */
INPUT[type="password"]{
font-family:Verdana,sans-serif;
height:28px;
font-size:19px;
width:223px;
padding:5px;
}
} /* END WEBKIT */
Handler answer in Kotlin :
1 - Create a top-level function inside a file (for example a file that contains all your top-level functions) :
fun delayFunction(function: ()-> Unit, delay: Long) {
Handler().postDelayed(function, delay)
}
2 - Then call it anywhere you needed it :
delayFunction({ myDelayedFunction() }, 300)
Using a free certificate is a better idea if your developers use Firefox 3. Firefox 3 complains loudly about self-signed certificates, and it is a major annoyance.
There is no direct method,
Rename Local Branch,
My current branch is master
git branch -m master_renamed
#master_renamed is new name of master
Delete remote branch,
git push origin --delete master
#origin is remote_name
Push renamed branch into remote,
git push origin master_renamed
That's it...
Here's a total, copy and paste solution, with an
of every issue involved.
for the amazing find regarding keyPath statusBarWindow.statusBar
. Good one.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// handle the iOS bar!
// >>>>>NOTE<<<<<
// >>>>>NOTE<<<<<
// >>>>>NOTE<<<<<
// "Status Bar Style" refers to the >>>>>color of the TEXT<<<<<< of the Apple status bar,
// it does NOT refer to the background color of the bar. This causes a lot of confusion.
// >>>>>NOTE<<<<<
// >>>>>NOTE<<<<<
// >>>>>NOTE<<<<<
// our app is white, so we want the Apple bar to be white (with, obviously, black writing)
// make the ultimate window of OUR app actually start only BELOW Apple's bar....
// so, in storyboard, never think about the issue. design to the full height in storyboard.
let h = UIApplication.shared.statusBarFrame.size.height
let f = self.window?.frame
self.window?.frame = CGRect(x: 0, y: h, width: f!.size.width, height: f!.size.height - h)
// next, in your plist be sure to have this: you almost always want this anyway:
// <key>UIViewControllerBasedStatusBarAppearance</key>
// <false/>
// next - very simply in the app Target, select "Status Bar Style" to Default.
// Do nothing in the plist regarding "Status Bar Style" - in modern Xcode, setting
// the "Status Bar Style" toggle simply sets the plist for you.
// finally, method A:
// set the bg of the Apple bar to white. Technique courtesy Warif Akhand Rishi.
// note: self.window?.clipsToBounds = true-or-false, makes no difference in method A.
if let sb = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView {
sb.backgroundColor = UIColor.white
// if you prefer a light gray under there...
//sb.backgroundColor = UIColor(hue: 0, saturation: 0, brightness: 0.9, alpha: 1)
}
/*
// if you prefer or if necessary, method B:
// explicitly actually add a background, in our app, to sit behind the apple bar....
self.window?.clipsToBounds = false // MUST be false if you use this approach
let whiteness = UIView()
whiteness.frame = CGRect(x: 0, y: -h, width: f!.size.width, height: h)
whiteness.backgroundColor = UIColor.green
self.window!.addSubview(whiteness)
*/
return true
}
Oh, but that's ugly, non-object-oriented code. The moment you see "if/else" and "typeof", you should be thinking polymorphism. This is the wrong way to go. I think generics are your friend here.
How many types do you plan to deal with?
UPDATE:
If you're just talking about String and int, here's one way you might do it. Start with the interface XmlGenerator (enough with "foo"):
package generics;
public interface XmlGenerator<T>
{
String getXml(T value);
}
And the concrete implementation XmlGeneratorImpl:
package generics;
public class XmlGeneratorImpl<T> implements XmlGenerator<T>
{
private Class<T> valueType;
private static final int DEFAULT_CAPACITY = 1024;
public static void main(String [] args)
{
Integer x = 42;
String y = "foobar";
XmlGenerator<Integer> intXmlGenerator = new XmlGeneratorImpl<Integer>(Integer.class);
XmlGenerator<String> stringXmlGenerator = new XmlGeneratorImpl<String>(String.class);
System.out.println("integer: " + intXmlGenerator.getXml(x));
System.out.println("string : " + stringXmlGenerator.getXml(y));
}
public XmlGeneratorImpl(Class<T> clazz)
{
this.valueType = clazz;
}
public String getXml(T value)
{
StringBuilder builder = new StringBuilder(DEFAULT_CAPACITY);
appendTag(builder);
builder.append(value);
appendTag(builder, false);
return builder.toString();
}
private void appendTag(StringBuilder builder) { this.appendTag(builder, false); }
private void appendTag(StringBuilder builder, boolean isClosing)
{
String valueTypeName = valueType.getName();
builder.append("<").append(valueTypeName);
if (isClosing)
{
builder.append("/");
}
builder.append(">");
}
}
If I run this, I get the following result:
integer: <java.lang.Integer>42<java.lang.Integer>
string : <java.lang.String>foobar<java.lang.String>
I don't know if this is what you had in mind.
For Python 3
Remove the rb
argument and use either r
or don't pass argument (default read mode
).
with open( <path-to-file>, 'r' ) as theFile:
reader = csv.DictReader(theFile)
for line in reader:
# line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
# e.g. print( line[ 'workers' ] ) yields 'w0'
print(line)
For Python 2
import csv
with open( <path-to-file>, "rb" ) as theFile:
reader = csv.DictReader( theFile )
for line in reader:
# line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
# e.g. print( line[ 'workers' ] ) yields 'w0'
Python has a powerful built-in CSV handler. In fact, most things are already built in to the standard library.
Others already posted. but I give a simple example here so that can help some new comers.
Step-1: In your index.html file reference jquery cdn
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
Step-2: assume we want to show div or hide div on click of a button:
<input type="button" value="Add New" (click)="ShowForm();">
<div class="container">
//-----.HideMe{display:none;} is a css class----//
<div id="PriceForm" class="HideMe">
<app-pricedetails></app-pricedetails>
</div>
<app-pricemng></app-pricemng>
</div>
Step-3:In the component file bellow the import declare $ as bellow:
declare var $: any;
than create function like bellow:
ShowForm(){
$('#PriceForm').removeClass('HideMe');
}
It will work with latest Angular and JQuery
A 32-bit process is still limited to the same constraints in a 64-bit OS. The issue is that memory pointers are only 32-bits wide, so the program can't assign/resolve any memory address larger than 32 bits.
Add debouncing, for efficiency http://davidwalsh.name/javascript-debounce-function
Powerful tool for "Bulletproof Email Background Images" (VML for Outlook 2007/2010/2013, and HTML/CSS for Outlook 2000/2003, Gmail, Hotmail...)
as an exemple :
<div style="background-color:#f6f6f6;">
<!--[if gte mso 9]>
<v:background xmlns:v="urn:schemas-microsoft-com:vml" fill="t">
<v:fill type="tile" src="http://i.imgur.com/n8Q6f.png" color="#f6f6f6"/>
</v:background>
<![endif]-->
<table height="100%" width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td valign="top" align="left" background="http://i.imgur.com/n8Q6f.png">
</td>
</tr>
</table>
</div>
in order to have the specified background image to Full email body.
This link help to use the Vector Markup Language (VML)
Up until jQuery 1.11.1, you could use the following URLs to get the latest version of jQuery:
For example:
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
However, since jQuery 1.11.1, both jQuery and Google stopped updating these URL's; they will forever be fixed at 1.11.1. There is no supported alternative URL to use. For an explanation of why this is the case, see this blog post; Don't use jquery-latest.js.
Both hosts support https
as well as http
, so change the protocol as you see fit (or use a protocol relative URI)
See also: https://developers.google.com/speed/libraries/devguide
Short: Abstract classes are used for Modelling a class hierarchy of similar looking classes (For example Animal can be abstract class and Human , Lion, Tiger can be concrete derived classes)
AND
Interface is used for Communication between 2 similar / non similar classes which does not care about type of the class implementing Interface(e.g. Height can be interface property and it can be implemented by Human , Building , Tree. It does not matter if you can eat , you can swim you can die or anything.. it matters only a thing that you need to have Height (implementation in you class) ).
Here's how you do it.
First, decorate your list this way:
<div class="p">
<div class="text-bullet-centered">⁕</div>
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
</div>
<div class="p">
<div class="text-bullet-centered">⁕</div>
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
</div>
Add this CSS:
.p {
position: relative;
margin: 20px;
margin-left: 50px;
}
.text-bullet-centered {
position: absolute;
left: -40px;
top: 50%;
transform: translate(0%,-50%);
font-weight: bold;
}
And voila, it works. Resize a window, to see that it indeed works.
As a bonus, you can easily change font and color of bullets, which is very hard to do with normal lists.
.p {_x000D_
position: relative;_x000D_
margin: 20px;_x000D_
margin-left: 50px;_x000D_
}_x000D_
_x000D_
.text-bullet-centered {_x000D_
position: absolute;_x000D_
left: -40px;_x000D_
top: 50%;_x000D_
transform: translate(0%, -50%);_x000D_
font-weight: bold;_x000D_
}
_x000D_
<div class="p">_x000D_
<div class="text-bullet-centered">⁕</div>_x000D_
text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text_x000D_
text text text text text text text text text text text text text_x000D_
</div>_x000D_
<div class="p">_x000D_
<div class="text-bullet-centered">⁕</div>_x000D_
text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text_x000D_
text text text text text text text text text text text text text_x000D_
</div>
_x000D_
To answer a little more conceptually:
SelectedValuePath
defines which property (by its name) of the objects bound to the ListBox's ItemsSource
will be used as the item's SelectedValue
.
For example, if your ListBox is bound to a collection of Person
objects, each of which has Name
, Age
, and Gender
properties, SelectedValuePath=Name
will cause the value of the selected Person
's Name
property to be returned in SelectedValue
.
Note that if you override the ListBox's ControlTemplate (or apply a Style) that specifies what property should display, SelectedValuePath
cannot be used.
SelectedItem
, meanwhile, returns the entire Person
object currently selected.
(Here's a further example from MSDN, using TreeView)
Update: As @Joe pointed out, the DisplayMemberPath property is unrelated to the Selected* properties. Its proper description follows:
Note that these values are distinct from DisplayMemberPath
(which is defined on ItemsControl, not Selector), but that property has similar behavior to SelectedValuePath
: in the absence of a style/template, it identifies which property of the object bound to item should be used as its string representation.
If you are using cpp11 (enable with the -std=c++0x
flag if needed), then you can simply initialize the vector like this:
// static std::vector<std::string> v;
v = {"haha", "hehe"};
It depends on the kind of test double you want to interact with:
In other words, with mocking the only useful interactions with a collaborator are the ones that you provide. By default functions will return null, void methods do nothing.
np.random.uniform
fits your use case:
sampl = np.random.uniform(low=0.5, high=13.3, size=(50,))
Update Oct 2019:
While the syntax is still supported, it looks like the API changed with NumPy 1.17 to support greater control over the random number generator. Going forward the API has changed and you should look at https://docs.scipy.org/doc/numpy/reference/random/generated/numpy.random.Generator.uniform.html
The enhancement proposal is here: https://numpy.org/neps/nep-0019-rng-policy.html
Some fixes I've used for this problem:
Check if the connection you want to share is shareable.
a. Press Win-key + r and run ncpa.cpl
b. Right click on the connection you want to share and go to properties
c. Go to sharing tab and check if sharing is enabled
Run devmgmt.msc
from the run console.
a. Expand the network adapters list
b. Right click -> properties on the adapter of the connection you want to share
c. Go to power management tab and enable allow this computer to turn off this device to save power
. Restart your laptop if you've made changes.
Check if airplane mode is disabled. You can enable airplane mode and then turn on the wi-fi, you can never know. Do disable airplane mode if it is on.
Use admin command prompt to run this command.
You can do this using Escape Sequence.
\"
So you will have to write something like this :
String name = "\"john\"";
You can learn about Escape Sequences from here.
Just in case if a range of characters need to be picked:
# For example, to get the date part from the string
substrRightRange <- function(x, m, n){substr(x, nchar(x)-m+1, nchar(x)-m+n)}
value <- "REGNDATE:20170526RN"
substrRightRange(value, 10, 8)
[1] "20170526"
You can very easily do this by
hr{_x000D_
transform: rotate(90deg);_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<hr>_x000D_
</body> _x000D_
</html>
_x000D_
You can't use add_timestamps and null:false if you have existing records, so here is the solution :
def change
add_timestamps(:buttons, null: true)
Button.find_each { |b| b.update(created_at: Time.zone.now, updated_at: Time.zone.now) }
change_column_null(:buttons, :created_at, false)
change_column_null(:buttons, :updated_at, false)
end
float price = 4.30;
DecimalFormat format = new DecimalFormat("0.##"); // Choose the number of decimal places to work with in case they are different than zero and zero value will be removed
format.setRoundingMode(RoundingMode.DOWN); // Choose your Rounding Mode
System.out.println(format.format(price));
This is the result of some tests:
4.30 => 4.3
4.39 => 4.39 // Choose format.setRoundingMode(RoundingMode.UP) to get 4.4
4.000000 => 4
4 => 4
Right click your project--->Build path---->configure Build path----> Libraries Tab--->Add External jars--->(Navigate to the location where you have kept the sql driver jar)--->ok
You can define a Multi-module project structure, then you can set the configuration for sonar in one properties file in the root folder of your project, (Way #1
)
The latest dwr (http://directwebremoting.org/dwr/index.html) has ajax file uploads, complete with examples and nice stuff for users (like progress indicators and such).
It looks pretty nifty and dwr is fairly easy to use in general so this will be pretty good as well.
I've had the same problems including jpegs in LaTeX. The engine isn't really built to gather all the necessary size and scale information from JPGs. It is often better to take the JPEG and convert it into a PDF (on a mac) or EPS (on a PC). GraphicsConvertor on a mac will do that for you easily. Whereas a PDF includes DPI and size, a JPEG has only a size in terms of pixels.
( I know this is not the answer you wanted, but it's probably better to give them EPS/PDF that they can use than to worry about what happens when they try to scale your JPG).
as Itsproinc said, the REN
command works!
but if your file path/name has spaces, use quotes " "
example:
ren C:\Users\&username%\Desktop\my file.txt not my file.txt
add " "
ren "C:\Users\&username%\Desktop\my file.txt" "not my file.txt"
hope it helps
[HttpPost]
public string MyMethod([FromBody]JObject data)
{
Customer customer = data["customerData"].ToObject<Customer>();
Product product = data["productData"].ToObject<Product>();
Employee employee = data["employeeData"].ToObject<Employee>();
//... other class....
}
using referance
using Newtonsoft.Json.Linq;
Use Request for JQuery Ajax
var customer = {
"Name": "jhon",
"Id": 1,
};
var product = {
"Name": "table",
"CategoryId": 5,
"Count": 100
};
var employee = {
"Name": "Fatih",
"Id": 4,
};
var myData = {};
myData.customerData = customer;
myData.productData = product;
myData.employeeData = employee;
$.ajax({
type: 'POST',
async: true,
dataType: "json",
url: "Your Url",
data: myData,
success: function (data) {
console.log("Response Data ?");
console.log(data);
},
error: function (err) {
console.log(err);
}
});
you can achieve vertical aligning with display:table-cell
:
#section1 {
height: 90%;
text-align:center;
display:table;
width:100%;
}
#section1 h1 {display:table-cell; vertical-align:middle}
Update - CSS3
For an alternate way to vertical align, you can use the following css 3 which should be supported in all the latest browsers:
#section1 {
height: 90%;
width:100%;
display:flex;
align-items: center;
justify-content: center;
}
This is just torazaburo's answer, updated to use a MouseEvent object.
function click(x, y)
{
var ev = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true,
'screenX': x,
'screenY': y
});
var el = document.elementFromPoint(x, y);
el.dispatchEvent(ev);
}
constructor(private router:Router, private route:ActivatedRoute ) {
}
onReload(){
this.router.navigate(['/servers'],{relativeTo:this.route})
}
This fiddle shows how
ul, li {
display:inline
}
Great references on lists and css here:
Here's a more general, regex way of doing this:
re.sub(r'^.+/([^/]+)$', r'\1', url)
That's not possible in a portable manner in pure C++, because it depends too much on the terminal used that may be connected with stdin
(they are usually line buffered). You can, however use a library for that:
conio available with Windows compilers. Use the _getch()
function to give you a character without waiting for the Enter key. I'm not a frequent Windows developer, but I've seen my classmates just include <conio.h>
and use it. See conio.h
at Wikipedia. It lists getch()
, which is declared deprecated in Visual C++.
curses available for Linux. Compatible curses implementations are available for Windows too. It has also a getch()
function. (try man getch
to view its manpage). See Curses at Wikipedia.
I would recommend you to use curses if you aim for cross platform compatibility. That said, I'm sure there are functions that you can use to switch off line buffering (I believe that's called "raw mode", as opposed to "cooked mode" - look into man stty
). Curses would handle that for you in a portable manner, if I'm not mistaken.
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
This help me a lot
Answer below the dotted line below is the original that's now outdated.
Here is the latest information ( Thank you @deadfish ):
add &hl=<language>
like &hl=pl
or &hl=en
example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl
All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en
......................................................................
To change the actual local market:
Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html
To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720
The best solution (for python >= 3.4) when executing from any directory is:
from pathlib import Path
two_up = Path(__file__).resolve().parents[1]
Adding up to other answers you need to export the class to use in a different class. This is a typescript version of it.
//Constants.tsx
const DEBUG: boolean = true;
export class Constants {
static get DEBUG(): boolean {
return DEBUG;
}
}
//Anotherclass.tsx
import { Constants } from "Constants";
if (Constants.DEBUG) {
console.log("debug mode")
}
_x000D_
String loudScreaming = json.getJSONObject("LabelData").getString("slogan");
Possible repeated question from How to overcome the CORS issue in ReactJS
CORS works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser. This must be configured in the server to allow cross domain.
You can temporary solve this issue by a chrome plugin called CORS.
I solved my issue by doing this:
Strangely it started working again after that.
but during a soccer-match, or a concert what does it matter if you are a single minute behind the stream?
To some soccer fans, quite a bit. It has been remarked that delays of even a few seconds present in digital video streams due to encoding (or whatever) can be very annoying when, during high-profile events such as world cup matches, you can hear the cheers and groans from the guys next door (who are watching an undelyed analog program) before you get to see the game moves that caused them.
I think that to someone caring a lot about sports (and those are the biggest group of paying customers for digital TV, at least here in Germany), being a minute behind in a live video stream would be completely unacceptable (As in, they'd switch to your competitor where this doesn't happen).
You have to add the reference of the namespace : System.Windows.Forms to your project, because for some reason it is not already added, so you can add New Reference from Visual Studio menu.
Right click on "Reference" ? "Add New Reference" ? "System.Windows.Forms"
Here is an explanation : Hotspot caused exceptions to lose their stack traces in production – and the fix
I've tested it on Mac OS X
Java HotSpot(TM) 64-Bit Server VM (build 20.1-b02-383, mixed mode)
Object string = "abcd";
int i = 0;
while (i < 12289) {
i++;
try {
Integer a = (Integer) string;
} catch (Exception e) {
e.printStackTrace();
}
}
For this specific fragment of code, 12288 iterations (+frequency?) seems to be the limit where JVM has decided to use preallocated exception...
One option is to use M-x shell
in emacs
. That provides all editing facilities and keystrokes that emacs
has, so C-s
can be used to search the text option25
, for example.
(But I'd still prefer to be in the real terminal shell instead if someone can point me to good search and edit facilities.)
I had the same issue, and had to satisfy all these requirements:
I finally solved it as follows:
webpack.config.js:
const path = require('path');
const MinifyPlugin = require("babel-minify-webpack-plugin");
module.exports = getConfiguration;
function getConfiguration(env) {
var outFile;
var plugins = [];
if (env === 'prod') {
outFile = 'mylib.dev';
plugins.push(new MinifyPlugin());
} else {
if (env !== 'dev') {
console.log('Unknown env ' + env + '. Defaults to dev');
}
outFile = 'mylib.dev.debug';
}
var entry = {};
entry[outFile] = './src/mylib-entry.js';
return {
entry: entry,
plugins: plugins,
output: {
filename: '[name].js',
path: __dirname
}
};
}
package.json:
{
"name": "mylib.js",
...
"scripts": {
"build": "npm-run-all webpack-prod webpack-dev",
"webpack-prod": "npx webpack --env=prod",
"webpack-dev": "npx webpack --env=dev"
},
"devDependencies": {
...
"babel-minify-webpack-plugin": "^0.2.0",
"npm-run-all": "^4.1.2",
"webpack": "^3.10.0"
}
}
Then I can build by (Don't forget to npm install
before):
npm run-script build
ECMAScript 6 comes up with a new type of string literal, using the backtick as the delimiter. These literals do allow basic string interpolation expressions to be embedded, which are then automatically parsed and evaluated.
let person = {name: 'RajiniKanth', age: 68, greeting: 'Thalaivaaaa!' };
let usualHtmlStr = "<p>My name is " + person.name + ",</p>\n" +
"<p>I am " + person.age + " old</p>\n" +
"<strong>\"" + person.greeting + "\" is what I usually say</strong>";
let newHtmlStr =
`<p>My name is ${person.name},</p>
<p>I am ${person.age} old</p>
<p>"${person.greeting}" is what I usually say</strong>`;
console.log(usualHtmlStr);
console.log(newHtmlStr);
As you can see, we used the `
around a series of characters, which are interpreted as a string literal, but any expressions of the form ${..}
are parsed and evaluated inline immediately.
One really nice benefit of interpolated string literals is they are allowed to split across multiple lines:
var Actor = {"name": "RajiniKanth"};
var text =
`Now is the time for all good men like ${Actor.name}
to come to the aid of their
country!`;
console.log(text);
// Now is the time for all good men like RajiniKanth
// to come to the aid of their
// country!
Interpolated Expressions
Any valid expression is allowed to appear inside ${..}
in an interpolated string literal, including function calls, inline function expression calls, and even other interpolated string literals!
function upper(s) {
return s.toUpperCase();
}
var who = "reader"
var text =
`A very ${upper("warm")} welcome
to all of you ${upper(`${who}s`)}!`;
console.log(text);
// A very WARM welcome
// to all of you READERS!
Here, the inner `${who}s`
interpolated string literal was a little bit nicer convenience for us when combining the who
variable with the "s"
string, as opposed to who + "s"
. Also to keep an note is an interpolated string literal is just lexically scoped where it appears, not dynamically scoped in any way:
function foo(str) {
var name = "foo";
console.log(str);
}
function bar() {
var name = "bar";
foo(`Hello from ${name}!`);
}
var name = "global";
bar(); // "Hello from bar!"
Using the template literal for the HTML is definitely more readable by reducing the annoyance.
The plain old way:
'<div class="' + className + '">' +
'<p>' + content + '</p>' +
'<a href="' + link + '">Let\'s go</a>'
'</div>';
With ECMAScript 6:
`<div class="${className}">
<p>${content}</p>
<a href="${link}">Let's go</a>
</div>`
Tagged Template Literals
We can also tag a template string, when a template string is tagged, the literals and substitutions are passed to function which returns the resulting value.
function myTaggedLiteral(strings) {
console.log(strings);
}
myTaggedLiteral`test`; //["test"]
function myTaggedLiteral(strings, value, value2) {
console.log(strings, value, value2);
}
let someText = 'Neat';
myTaggedLiteral`test ${someText} ${2 + 3}`;
//["test", ""]
// "Neat"
// 5
We can use the spread operator here to pass multiple values. The first argument—we called it strings—is an array of all the plain strings (the stuff between any interpolated expressions).
We then gather up all subsequent arguments into an array called values using the ... gather/rest operator
, though you could of course have left them as individual named parameters following the strings parameter like we did above (value1
, value2
, etc.).
function myTaggedLiteral(strings, ...values) {
console.log(strings);
console.log(values);
}
let someText = 'Neat';
myTaggedLiteral`test ${someText} ${2 + 3}`;
//["test", ""]
// "Neat"
// 5
The argument(s) gathered into our values array are the results of the already evaluated interpolation expressions found in the string literal. A tagged string literal is like a processing step after the interpolations are evaluated, but before the final string value is compiled, allowing you more control over generating the string from the literal. Let's look at an example of creating reusable templates.
const Actor = {
name: "RajiniKanth",
store: "Landmark"
}
const ActorTemplate = templater`<article>
<h3>${'name'} is a Actor</h3>
<p>You can find his movies at ${'store'}.</p>
</article>`;
function templater(strings, ...keys) {
return function(data) {
let temp = strings.slice();
keys.forEach((key, i) => {
temp[i] = temp[i] + data[key];
});
return temp.join('');
}
};
const myTemplate = ActorTemplate(Actor);
console.log(myTemplate);
Raw Strings
Our tag functions receive a first argument we called strings, which is an array. But there’s an additional bit of data included: the raw unprocessed versions of all the strings. You can access those raw string values using the .raw
property, like this:
function showraw(strings, ...values) {
console.log(strings);
console.log(strings.raw);
}
showraw`Hello\nWorld`;
As you can see, the raw version of the string preserves the escaped \n
sequence, while the processed version of the string treats it like an unescaped real new-line. ECMAScript 6 comes with a built-in function that can be used as a string literal tag: String.raw(..)
. It simply passes through the raw versions of the strings:
console.log(`Hello\nWorld`);
/* "Hello
World" */
console.log(String.raw`Hello\nWorld`);
// "Hello\nWorld"
in my case the copyright notice in the footer of a wordpress web site needed updating.
thought simple, but involved a step or more thann anticipated.
Open footer.php
in your theme's folder.
Locate copyright text, expected this to be all hard coded but found:
<div id="copyright">
<?php the_field('copyright_disclaimer', 'options'); ?>
</div>
Now we know the year is written somewhere in WordPress admin so locate that to delete the year written text. In WP-Admin, go to Options
on the left main admin menu:
Then on next page go to the tab Disclaimers
:
and near the top you will find Copyright year:
DELETE the © symbol + year + the empty space following the year, then save your page with Update
button at top-right of page.
With text version of year now delete, we can go and add our year that updates automatically with PHP. Go back to chunk of code in STEP 2 found in footer.php
and update that to this:
<div id="copyright">
©<?php echo date("Y"); ?> <?php the_field('copyright_disclaimer', 'options'); ?>
</div>
Done! Just need to test to ensure changes have taken effect as expected.
this might not be the same case for many, however we've come across this pattern among quite a number of our client sites and thought it would be best to document here.
You can also use the data-interval attribute eg. <div class="carousel" data-interval="10000">
MSDN tells us:
The IntPtr type is designed to be an integer whose size is platform-specific. That is, an instance of this type is expected to be 32-bits on 32-bit hardware and operating systems, and 64-bits on 64-bit hardware and operating systems.
The IntPtr type can be used by languages that support pointers, and as a common means of referring to data between languages that do and do not support pointers.
IntPtr objects can also be used to hold handles. For example, instances of IntPtr are used extensively in the System.IO.FileStream class to hold file handles.
The IntPtr type is CLS-compliant, while the UIntPtr type is not. Only the IntPtr type is used in the common language runtime. The UIntPtr type is provided mostly to maintain architectural symmetry with the IntPtr type.
http://msdn.microsoft.com/en-us/library/system.intptr(VS.71).aspx
You need to print the result of the getText()
. You're currently printing the object TxtBoxContent
.
getText()
will only get the inner text of an element. To get the value, you need to use getAttribute()
.
WebElement TxtBoxContent = driver.findElement(By.id(WebelementID));
System.out.println("Printing " + TxtBoxContent.getAttribute("value"));
Finally found this method:
basename($_SERVER['REQUEST_URI']);
This will return all URLs with page name. (e.g.: index.php?id=1&name=rr&class=10
).
If you want to display text inside your own page, you can use the <pre>
tag.
document.querySelector('textarea').addEventListener('keyup', function() {_x000D_
document.querySelector('pre').innerText = this.value;_x000D_
});
_x000D_
<textarea placeholder="type text here"></textarea>_x000D_
<pre style="font-family: inherits">_x000D_
The_x000D_
new lines will_x000D_
be respected_x000D_
and spaces too_x000D_
</pre>
_x000D_
The code downloaded may require you to install dependencies first. Try commands(in app.js directory): npm install
then node app.js
. This should install dependencies and then start the app.
Option 1. Use Visual Basic to iterate through each column and format each column as Text.
Use the Text-to-Columns menu, don't change the delimination, and change "General" to "Text"
You can use the dynamic object ViewBag
to pass data from Controllers to Views.
Add the following to your controller:
ViewBag.MyList = myList;
Then you can acces it from your view:
@ViewBag.MyList
// e.g.
@foreach (var item in ViewBag.MyList) { ... }
You must sort your data according your needs (es. in reverse order) and use select top query
both are fine.
text/xxx means that in case the program does not understand xxx it makes sense to show the file to the user as plain text. application/xxx means that it is pointless to show it.
Please note that those content-types were originally defined for E-Mail attachment before they got later used in Web world.
make sure your controller extends Symfony\Bundle\FrameworkBundle\Controller\Controller;
you should also check app/console debug:router
in terminal to see what name symfony has named the route
in my case it used a minus instead of an underscore
i.e blog-show
$uri = $this->generateUrl('blog-show', ['slug' => 'my-blog-post']);
If you want to delete rows based on multiple values of the column, you could use:
df[(df.line_race != 0) & (df.line_race != 10)]
To drop all rows with values 0 and 10 for line_race
.