In order to install Compass on Yosemite you need to set up the Ruby environment and to install the Xcode Command Line Tools. But, most important thing, after updating Xcode, be sure to launch the Xcode application and accept the Apple license terms. It will complete the installation of the components. After that, you can install Compass: sudo gem install compass
the warning or error of kind IMPLICIT DECLARATION is that the compiler is expecting a Function Declaration/Prototype..
It might either be a header file or your own function Declaration..
summation
and your other functions are defined after they're used in main
, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.
You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.
Either move the function bodies before main
, or include method signatures before main
, e.g.:
#include <stdio.h>
int summation(int *, int *, int *);
int main()
{
// ...
This is an improved version of Anne's answer -- if you use perl, you can do the edit on the file 'in-place' rather than generating a new file:
perl -pi -e 's/\r\n|\n|\r/\r\n/g' file-to-convert # Convert to DOS
perl -pi -e 's/\r\n|\n|\r/\n/g' file-to-convert # Convert to UNIX
Nodemon emits events upon every change in state; start, restart crash, etc. You can add a Nodemon configuration file (nodemon.json) like so:
{
"events": {
"start": "npm run *your_file*"
}
}
Read more in Nodemon events — run tasks at server start, restart, crash, exit.
The short answer: no.
The long answer:
Fixed formats work better for HTML emails. In my experience you're best off pretending it's 1999 when it comes to HTML emails. Be explicit and use HTML attributes (width="650") where ever possible in your table definitions, not CSS (style="width:650px"). Use fixed widths, no percentages. A table width of 650 pixels wide is a safe bet. Use inline CSS to set text properties.
It's not a matter of what works in "HTML emails", but rather the plethora of email clients and their limited (and sometimes deliberately so in the case of Gmail, Hotmail etc) ability to render HTML.
An alternative solution uses the stash:
Before:
~/dev/gitpro $git stash list
~/dev/gitpro $git log --oneline -3
* 7049dd5 (HEAD -> master) c111
* 3f1fa3d c222
* 0a0f6c4 c333
note you cannot run 'git stash pop' without specifying the stash@{1} entry. The stash is a LIFO stack -- not FIFO -- so that would incorrectly pop the stash@{0} entry with c222's changes (instead of stash@{1} with c111's changes).
note if there are conflicting chunks between commits 111 and 222, then you'll be forced to resolve them when attempting to pop. (This would be the case if you went with an alternative rebase solution as well.)
After:
~/dev/gitpro $git stash list
stash@{0}: On master: c222
~/dev/gitpro $git log -2 --oneline
* edbd9e8 (HEAD -> master) c111
* 0a0f6c4 c333
If you want to deploy your application on machines of customers, rather than using your application only yourself, we find that the LIBS+= -Lxxx -lyyy
method can lead to confusion if not problems.
We develop applications for Linux, Mac and Windows using Qt. We ship complete, stand-alone applications. So all non-system libraries should be included in the deployment package. We want our customers to be able to run the application from the same USB stick for all OSs. For reasons of platform compatibility the USB stick must then be formatted as FAT32, which does not support (Linux) symlinks.
We found the LIBS+= -Lxxx -lyyy
idiom too much of a black box:
We do not exactly know what the filepath is of the (static or dynamic) library that has been found by the linker. This is inconvenient. Our Mac linker regularly found libs different from the ones we thought that should be used. This happened several times with OpenSSL libraries where the Mac linker found and used its own - older, incompatible - OpenSSL version rather than our requested version.
We cannot afford that the linker uses symlinks to libraries as this would break the deployment package.
We want to see from the name of the library whether we link a static or a dynamic library.
So for our particular case we use only absolute filepaths and check whether they exist. We remove all symlinks.
First we find out what operating system we are using and put this in the CONFIG variable. And, for instance for Linux 64bit, then:
linux64 {
LIBSSL= $$OPENSSLPATH/linux64/lib/libssl.a
!exists($$LIBSSL): error ("Not existing $$LIBSSL")
LIBS+= $$LIBSSL
LIBCRYPTO= $$OPENSSLPATH/linux64/lib/libcrypto.a
!exists($$LIBCRYPTO): error ("Not existing $$LIBCRYPTO")
LIBS+= $$LIBCRYPTO
}
All the dependencies can be copied into deployment package as we know their filepaths.
1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math
2: Yes: But you already know it:
`^`(x,y)
#[1] 1024
In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math
.
Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply
and sapply
:
> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4
https://www.programmableweb.com/ -- Great collection of all category API's across web. It not only show cases the API's , but also Developers who use those API's in their applications and code samples, rating of the API and much more. They have more than apis they also have sdk and libraries too.
In modern browsers (and some legacy browsers), you can do
Array.isArray(obj)
(Supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5)
If you need to support older versions of IE, you can use es5-shim to polyfill Array.isArray; or add the following
# only implement if no native implementation is available
if (typeof Array.isArray === 'undefined') {
Array.isArray = function(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
};
If you use jQuery you can use jQuery.isArray(obj)
or $.isArray(obj)
. If you use underscore you can use _.isArray(obj)
If you don't need to detect arrays created in different frames you can also just use instanceof
obj instanceof Array
Note: the arguments
keyword that can be used to access the argument of a function isn't an Array, even though it (usually) behaves like one:
var func = function() {_x000D_
console.log(arguments) // [1, 2, 3]_x000D_
console.log(arguments.length) // 3_x000D_
console.log(Array.isArray(arguments)) // false !!!_x000D_
console.log(arguments.slice) // undefined (Array.prototype methods not available)_x000D_
console.log([3,4,5].slice) // function slice() { [native code] } _x000D_
}_x000D_
func(1, 2, 3)
_x000D_
For my Apache2.4 + php5-fpm installation to start working, I needed to activate the following Apache modules:
sudo a2enmod proxy
sudo a2enmod proxy_fcgi
No need for proxy_http
, and this is what sends all .php
files straight to php5-fpm:
<FilesMatch \.php$>
SetHandler "proxy:unix:/var/run/php5-fpm.sock|fcgi://localhost"
</FilesMatch>
You're declaring a virtual
function and not defining it:
virtual void calculateCredits();
Either define it or declare it as:
virtual void calculateCredits() = 0;
Or simply:
virtual void calculateCredits() { };
Read more about vftable: http://en.wikipedia.org/wiki/Virtual_method_table
If you have the test
binary installed or ksh
has a matching built-in function, you could use it to perform your checks. Usually /bin/[
is a symbolic link to test
:
if [ -e "$file_name" ]; then
echo "File exists"
fi
if [ -z "$used_var" ]; then
echo "Variable is empty"
fi
The question is little unclear because the title of the question is asking about string and set conversion but then the question at the end asks how do I serialize ? !
let me refresh the concept of Serialization is the process of encoding an object, including the objects it refers to, as a stream of byte data.
If interested to serialize you can use:
json.dumps -> serialize
json.loads -> deserialize
If your question is more about how to convert set to string and string to set then use below code (it's tested in Python 3)
String to Set
set('abca')
Set to String
''.join(some_var_set)
example:
def test():
some_var_set=set('abca')
print("here is the set:",some_var_set,type(some_var_set))
some_var_string=''.join(some_var_set)
print("here is the string:",some_var_string,type(some_var_string))
test()
# Open a connection to the file
with open('world_dev_ind.csv') as file:
# Skip the column names
file.readline()
# Initialize an empty dictionary: counts_dict
counts_dict = {}
# Process only the first 1000 rows
for j in range(0, 1000):
# Split the current line into a list: line
line = file.readline().split(',')
# Get the value for the first column: first_col
first_col = line[0]
# If the column value is in the dict, increment its value
if first_col in counts_dict.keys():
counts_dict[first_col] += 1
# Else, add to the dict and set value to 1
else:
counts_dict[first_col] = 1
# Print the resulting dictionary
print(counts_dict)
Your code does work (tested with cpython 2.4, 2.5, 2.6, 2.7, 3.1 and 3.2):
>>> a = set(["Blah", "Hello"])
>>> a = list(a) # You probably wrote a = list(a()) here or list = set() above
>>> a
['Blah', 'Hello']
Check that you didn't overwrite list
by accident:
>>> assert list == __builtins__.list
In your case you can use __FILE__
variable !
It should help.
It is one of predefined.
Read more about predefined constants in PHP http://php.net/manual/en/language.constants.predefined.php
As Jakub Vrána (The creator or Adminer and NotORM) mentions in the comments, to select the current timezone offset in TIME
use:
SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP);
It will return: 02:00:00
if your timezone is +2:00 for that date
I made a cheatsheet here: Should MySQL have its timezone set to UTC?
Have you tried the following?:
textbox1.text = System.DateTime.Today.ToString("MM/dd/yy");
Be aware that 2 digit years could be bad in the future...
to stop IIS manually:
you get a search result for the manager (Internet Information Services (IIS) manager, on the right side of it there are restart/stop/start buttons.
If you don't want IIS to start on startup because its really annoying..:
oh and IIS and xampp basically do the same thing just in a bit different way. ANd if you have Xampp for your projects then its not really all that nessecary to leave it on if you don't ever use it anyways.
There is one additional step to Amber's answer if you're using a centralized repository:
git push -f
to force the update of the central repository.
Be careful that there are not a lot of people working on the same branch because it can ruin consistency.
You may need to know the status during the file download or use credentials before making the request.
Here is an example that covers these options:
Uri ur = new Uri("http://remotehost.do/images/img.jpg");
using (WebClient client = new WebClient()) {
//client.Credentials = new NetworkCredential("username", "password");
String credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("Username" + ":" + "MyNewPassword"));
client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}";
client.DownloadProgressChanged += WebClientDownloadProgressChanged;
client.DownloadDataCompleted += WebClientDownloadCompleted;
client.DownloadFileAsync(ur, @"C:\path\newImage.jpg");
}
And the callback's functions implemented as follows:
void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);
// updating the UI
Dispatcher.Invoke(() => {
progressBar.Value = e.ProgressPercentage;
});
}
void WebClientDownloadCompleted(object sender, DownloadDataCompletedEventArgs e)
{
Console.WriteLine("Download finished!");
}
(Ver 2) - Lambda notation: other possible option for handling the events
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(delegate(object sender, DownloadProgressChangedEventArgs e) {
Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);
// updating the UI
Dispatcher.Invoke(() => {
progressBar.Value = e.ProgressPercentage;
});
});
client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(delegate(object sender, DownloadDataCompletedEventArgs e){
Console.WriteLine("Download finished!");
});
(Ver 3) - We can do better
client.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) =>
{
Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);
// updating the UI
Dispatcher.Invoke(() => {
progressBar.Value = e.ProgressPercentage;
});
};
client.DownloadDataCompleted += (object sender, DownloadDataCompletedEventArgs e) =>
{
Console.WriteLine("Download finished!");
};
(Ver 4) - Or
client.DownloadProgressChanged += (o, e) =>
{
Console.WriteLine($"Download status: {e.ProgressPercentage}%.");
// updating the UI
Dispatcher.Invoke(() => {
progressBar.Value = e.ProgressPercentage;
});
};
client.DownloadDataCompleted += (o, e) =>
{
Console.WriteLine("Download finished!");
};
If you want to be able to handle an error instead of blindly exiting, instead of using set -e
, use a trap
on the ERR
pseudo signal.
#!/bin/bash
f () {
errorCode=$? # save the exit code as the first thing done in the trap function
echo "error $errorCode"
echo "the command executing at the time of the error was"
echo "$BASH_COMMAND"
echo "on line ${BASH_LINENO[0]}"
# do some error handling, cleanup, logging, notification
# $BASH_COMMAND contains the command that was being executed at the time of the trap
# ${BASH_LINENO[0]} contains the line number in the script of that command
# exit the script or return to try again, etc.
exit $errorCode # or use some other value or do return instead
}
trap f ERR
# do some stuff
false # returns 1 so it triggers the trap
# maybe do some other stuff
Other traps can be set to handle other signals, including the usual Unix signals plus the other Bash pseudo signals RETURN
and DEBUG
.
Please use regex to remove anything before |
example
dsfdf | fdfsfsf
dsdss|gfghhghg
dsdsds |dfdsfsds
Use find and replace in notepad++
find: .+(\|)
replace: \1
output
| fdfsfsf
|gfghhghg
|dfdsfsds
As shell command:
< /dev/zero head -c 1048576 > output
You do not need to install or update any software for the JUnit. it is the part of Java Development tools and comes with almost most of the latest versions in Eclipse.
Go to your project. Right click onto that->Select buildpath->add library->select JUnit from the list ->select the version you want to work with-> done
build you project again to see the errors gone:)
You can attach a SLOT to the
void aboutToQuit();
signal of your QApplication. This signal should be raised just before app closes.
SELECT DATE_FORMAT(somedate, "%d/%m/%Y") AS formatted_date
..........
ORDER BY formatted_date DESC
People don't see the nice cool Stream producers all over the Java libs.
public static double[] list(){
return new Random().ints().asDoubleStream().toArray();
}
First string date is converted to js date format and converted into string format again, then it is compared with original string.
function dateValidation(){
var dateString = "34/05/2019"
var dateParts = dateString.split("/");
var date= new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]);
var isValid = isValid( dateString, date );
console.log("Is valid date: " + isValid);
}
function isValidDate(dateString, date) {
var newDateString = ( date.getDate()<10 ? ('0'+date.getDate()) : date.getDate() )+ '/'+ ((date.getMonth() + 1)<10? ('0'+(date.getMonth() + 1)) : (date.getMonth() + 1) ) + '/' + date.getFullYear();
return ( dateString == newDateString);
}
$ aws configure
and use the new key and secret.Run the command again:
serverless invoke local --function create --path mocks/create-event.json
Do you have to use @Test(expected=SomeException.class)
? When we have to assert the actual message of the exception, this is what we do.
@Test
public void myTestMethod()
{
try
{
final Integer employeeId = null;
new Employee(employeeId);
fail("Should have thrown SomeException but did not!");
}
catch( final SomeException e )
{
final String msg = "Employee ID is null";
assertEquals(msg, e.getMessage());
}
}
You can use white-space: pre-line to preserve line breaks in formatting. There is no need to manually insert html elements.
.popover {
white-space: pre-line;
}
or add to your html element style="white-space: pre-line;"
I usually use a helper class I once wrote for this task:
import java.util.zip.*;
import java.io.*;
public class ZipExample {
public static void main(String[] args){
ZipHelper zippy = new ZipHelper();
try {
zippy.zipDir("folderName","test.zip");
} catch(IOException e2) {
System.err.println(e2);
}
}
}
class ZipHelper
{
public void zipDir(String dirName, String nameZipFile) throws IOException {
ZipOutputStream zip = null;
FileOutputStream fW = null;
fW = new FileOutputStream(nameZipFile);
zip = new ZipOutputStream(fW);
addFolderToZip("", dirName, zip);
zip.close();
fW.close();
}
private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip) throws IOException {
File folder = new File(srcFolder);
if (folder.list().length == 0) {
addFileToZip(path , srcFolder, zip, true);
}
else {
for (String fileName : folder.list()) {
if (path.equals("")) {
addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip, false);
}
else {
addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip, false);
}
}
}
}
private void addFileToZip(String path, String srcFile, ZipOutputStream zip, boolean flag) throws IOException {
File folder = new File(srcFile);
if (flag) {
zip.putNextEntry(new ZipEntry(path + "/" +folder.getName() + "/"));
}
else {
if (folder.isDirectory()) {
addFolderToZip(path, srcFile, zip);
}
else {
byte[] buf = new byte[1024];
int len;
FileInputStream in = new FileInputStream(srcFile);
zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len);
}
}
}
}
}
Place this in the ~/.m2/settings.xml
or custom file to be run with $ mvn -s custom-settings.xml install
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
https://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository>${user.home}/.m2/repository</localRepository>
<interactiveMode/>
<offline/>
<pluginGroups/>
<profiles>
<profile>
<repositories>
<repository>
<id>mvnrepository</id>
<name>mvnrepository</name>
<url>http://www.mvnrepository.com</url>
</repository>
</repositories>
</profile>
</profiles>
<activeProfiles>
<activeProfile>mvnrepository</activeProfile>
</activeProfiles>
</settings>
If you can possibly help it, DO NOT USE .scrollHeight.
.scrollHeight does not yield the same kind of results in different browsers in certain circumstances (most prominently while scrolling).
For example:
<div id='outer' style='width:100px; height:350px; overflow-y:hidden;'>
<div style='width:100px; height:150px;'></div>
<div style='width:100px; height:150px;'></div>
<div style='width:100px; height:150px;'></div>
<div style='width:100px; height:150px;'></div>
<div style='width:100px; height:150px;'></div>
<div style='width:100px; height:150px;'></div>
</div>
If you do
console.log($('#outer').scrollHeight);
you'll get 900px in Chrome, FireFox and Opera. That's great.
But, if you attach a wheelevent / wheel event to #outer, when you scroll it, Chrome will give you a constant value of 900px (correct) but FireFox and Opera will change their values as you scroll down (incorrect).
A very simple way to do this is like so (a bit of a cheat, really). (This example works while dynamically adding content to #outer as well):
$('#outer').css("height", "auto");
var outerContentsHeight = $('#outer').height();
$('#outer').css("height", "350px");
console.log(outerContentsHeight); //Should get 900px in these 3 browsers
The reason I pick these three browsers is because all three can disagree on the value of .scrollHeight in certain circumstances. I ran into this issue making my own scrollpanes. Hope this helps someone.
ERROR: Linux / Centos:
Job for jenkins.service failed because the control process exited with error code. See "systemctl status jenkins.service" and "journalctl -xe" for details.
Solution:
Edit the Jenkins init file by doing
sudo vi /etc/init.d/jenkins
Add your own Java path, for example:
/opt/oracle/product/java/jdk1.8.0_45/bin/java
Restart the service:
sudo service jenkins start
sudo service jenkins status
sudo service jenkins stop
I think best method is to query pg_setting
view:
select s.name, s.setting, s.short_desc from pg_settings s where s.name='data_directory';
Output:
name | setting | short_desc
----------------+------------------------+-----------------------------------
data_directory | /var/lib/pgsql/10/data | Sets the server's data directory.
(1 row)
Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.
-
is the 'binary operator' your error is referencing, and either CurrentDay
or MA
(or both) are non-numeric.
A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). +
is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).
R only knows how to apply +
(and other binary operators, such as -
) to numeric arguments:
> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator
When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.
EDIT:
Your error lies in the use of [
instead of [[
. Because Day
is a list, subsetting with [
will return a list, not a numeric vector. [[
, however, returns an object of the class of the item contained in the list:
> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator
> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3
Transaction
, as you've defined it, returns a list of two vectors. Above, Day
is a list contain one vector. Day2
, however, is simply a vector.
This happened to me when I was trying to push the develop branch (I am using git flow). Someone had push updates to master. to fix it I did:
git co master
git pull
Which fetched those changes. Then,
git co develop
git pull
Which didn't do anything. I think the develop branch already pushed despite the error message. Everything is up to date now and no errors.
You can run the following query as a mysql root user
drop tablespace `tableName`
Check this:
alert(window.location.hostname);
this will return host name as www.domain.com
and:
window.location.host
will return domain name with port like www.example.com:80
For complete reference check Mozilla developer site.
I got around the proxy using https... some proxies don't even check https.
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
c:\git\meantest>git clone http://github.com/linnovate/mean.git
Cloning into 'mean'...
fatal: unable to access 'http://github.com/linnovate/mean.git/': Failed connect
to github.com:80; No error
c:\git\meantest>git clone https://github.com/linnovate/mean.git
Cloning into 'mean'...
remote: Reusing existing pack: 2587, done.
remote: Counting objects: 27, done.
remote: Compressing objects: 100% (24/24), done.
rRemote: Total 2614 (delta 3), reused 4 (delta 0)eceiving objects: 98% (2562/26
Receiving objects: 100% (2614/2614), 1.76 MiB | 305.00 KiB/s, done.
Resolving deltas: 100% (1166/1166), done.
Checking connectivity... done
Well, first, you need to actually define a function before you can run it (and it doesn't need to be called main
). For instance:
class Example(object):
def run(self):
print "Hello, world!"
if __name__ == '__main__':
Example().run()
You don't need to use a class, though - if all you want to do is run some code, just put it inside a function and call the function, or just put it in the if
block:
def main():
print "Hello, world!"
if __name__ == '__main__':
main()
or
if __name__ == '__main__':
print "Hello, world!"
Substrings with ${variablename:0:5}
are a bash feature, not available in basic shells. Are you sure you're running this under bash? Check the shebang line (at the beginning of the script), and make sure it's #!/bin/bash
, not #!/bin/sh
. And make sure you don't run it with the sh
command (i.e. sh scriptname
), since that overrides the shebang.
display: table;
h1 {_x000D_
display: table; /* keep the background color wrapped tight */_x000D_
margin: 0px auto 0px auto; /* keep the table centered */_x000D_
padding:5px;font-size:20px;background-color:green;color:#ffffff;_x000D_
}
_x000D_
<h1>The Last Will and Testament of Eric Jones</h1>
_x000D_
fiddle
http://jsfiddle.net/J7VBV/293/
more
display: table
tells the element to behave as a normal HTML table would.
More about it at w3schools, CSS Tricks and here
display: inline-flex;
text-align: center;
on parent.container {_x000D_
text-align: center; /* center the child */_x000D_
}_x000D_
h1 {_x000D_
display: inline-flex; /* keep the background color wrapped tight */_x000D_
padding:5px;font-size:20px;background-color:green;color:#ffffff;_x000D_
}
_x000D_
<div class="container">_x000D_
<h1>The Last Will and Testament of Eric Jones</h1>_x000D_
</div>
_x000D_
display: flex;
.container {_x000D_
display: flex;_x000D_
justify-content: center; /* center the child */_x000D_
}_x000D_
h1 {_x000D_
display: flex;_x000D_
/* margin: 0 auto; or use auto left/right margin instead of justify-content center */_x000D_
padding:5px;font-size:20px;background-color:green;color:#ffffff;_x000D_
}
_x000D_
<div class="container">_x000D_
<h1>The Last Will and Testament of Eric Jones</h1>_x000D_
</div>
_x000D_
about
Probably the most popular guide to Flexbox and one I reference constantly is at CSS Tricks
display: block;
.container {_x000D_
display: flex;_x000D_
justify-content: center; /* centers child */_x000D_
}_x000D_
h1 {_x000D_
display: block;_x000D_
padding:5px;font-size:20px;background-color:green;color:#ffffff;_x000D_
}
_x000D_
<div class="container">_x000D_
<h1>The Last Will and Testament of Eric Jones</h1>_x000D_
</div>
_x000D_
::before
h1 {_x000D_
display: flex; /* set a flex box */_x000D_
justify-content: center; /* so you can center the content like this */_x000D_
}_x000D_
_x000D_
h1::before {_x000D_
content:'The Last Will and Testament of Eric Jones'; /* the content */_x000D_
padding: 5px;font-size: 20px;background-color: green;color: #ffffff;_x000D_
}
_x000D_
<h1></h1>
_x000D_
fiddle
http://jsfiddle.net/J7VBV/457/
about
More about css pseudo elements ::before and ::after at CSS Tricks and pseudo elements in general at w3schools
display: inline-block;
centering with position: absolute
and translateX
requires a position: relative
parent
.container {_x000D_
position: relative; /* required for absolute positioned child */_x000D_
}_x000D_
h1 {_x000D_
display: inline-block; /* keeps container wrapped tight to content */_x000D_
position: absolute; /* to absolutely position element */_x000D_
top: 0;_x000D_
left: 50%; /* part1 of centering with translateX/Y */_x000D_
transform: translateX(-50%); /* part2 of centering with translateX/Y */_x000D_
white-space: nowrap; /* text lines will collapse without this */_x000D_
padding:5px;font-size:20px;background-color:green;color:#ffffff;_x000D_
}
_x000D_
<h1>The Last Will and Testament of Eric Jones</h1>
_x000D_
about
More on centering with transform: translate();
(and centering in general) in this CSS tricks article
text-shadow:
and box-shadow:
h1, h2, h3, h4, h5 {display: table;margin: 10px auto;padding: 5px;font-size: 20px;color: #ffffff;overflow:hidden;}_x000D_
h1 {_x000D_
text-shadow: 0 0 5px green,0 0 5px green,_x000D_
0 0 5px green,0 0 5px green,_x000D_
0 0 5px green,0 0 5px green,_x000D_
0 0 5px green,0 0 5px green;_x000D_
}_x000D_
h2 {_x000D_
text-shadow: -5px -5px 5px green,-5px 5px 5px green,_x000D_
5px -5px 5px green,5px 5px 5px green;_x000D_
}_x000D_
h3 {_x000D_
color: hsla(0, 0%, 100%, 0.8);_x000D_
text-shadow: 0 0 10px hsla(120, 100%, 25%, 0.5),_x000D_
0 0 10px hsla(120, 100%, 25%, 0.5),_x000D_
0 0 10px hsla(120, 100%, 25%, 0.5),_x000D_
0 0 5px hsla(120, 100%, 25%, 1),_x000D_
0 0 5px hsla(120, 100%, 25%, 1),_x000D_
0 0 5px hsla(120, 100%, 25%, 1);_x000D_
}_x000D_
h4 { /* overflow:hidden is the key to this one */_x000D_
text-shadow: 0px 0px 35px green,0px 0px 35px green,_x000D_
0px 0px 35px green,0px 0px 35px green;_x000D_
}_x000D_
h5 { /* set the spread value to something larger than you'll need to use as I don't believe percentage values are accepted */_x000D_
box-shadow: inset 0px 0px 0px 1000px green;_x000D_
}
_x000D_
<h1>The First Will and Testament of Eric Jones</h1>_x000D_
<h2>The 2nd Will and Testament of Eric Jones</h2>_x000D_
<h3>The 3rd Will and Testament of Eric Jones</h3>_x000D_
<h4>The Last Will and Testament of Eric Jones</h4>_x000D_
<h5>The Last Box and Shadow of Eric Jones</h5>
_x000D_
fiddle
https://jsfiddle.net/Hastig/t8L9Ly8o/
There are a few other ways to go about this by combining the different display options and centering methods above.
I cannot help you much without a small (possibly reduced) snippit of the problem. If the problem is what I think it is then it's because a div by default takes up 100% width, and as such cannot be aligned.
What you may be after is to align the inline elements inside the div (such as text) with text-align:center; otherwise you may consider setting the div to display:inline-block;
If you do go down the inline-block route then you may have to consider my favorite IE hack.
width:100px;
display:inline-block;
zoom:1; //IE only
*display:inline; //IE only
Happy Coding :)
Here's a way to do it without formulas or macros:
(from http://www.lenashore.com/2012/04/how-to-add-quotes-to-your-cells-in-excel-automatically/)
Please try the below XAML snippet:
<Button Width="300" Height="50">
<StackPanel Orientation="Horizontal">
<Image Source="Pictures/img.jpg" Width="20" Height="20"/>
<TextBlock Text="Blablabla" VerticalAlignment="Center" />
</StackPanel>
</Button>
In XAML elements are in a tree structure. So you have to add the child control to its parent control. The below code snippet also works fine. Give a name for your XAML root grid as 'MainGrid'.
Image img = new Image();
img.Source = new BitmapImage(new Uri(@"foo.png"));
StackPanel stackPnl = new StackPanel();
stackPnl.Orientation = Orientation.Horizontal;
stackPnl.Margin = new Thickness(10);
stackPnl.Children.Add(img);
Button btn = new Button();
btn.Content = stackPnl;
MainGrid.Children.Add(btn);
input[type="text"], textarea {
background-color : #d1d1d1;
}
Hope that helps :)
Edit: working example, http://jsfiddle.net/C5WxK/
this code will work with OI File Manager :
File root = new File(Environment.getExternalStorageDirectory().getPath()
+ "/myFolder/");
Uri uri = Uri.fromFile(root);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setData(uri);
startActivityForResult(intent, 1);
you can get OI File manager here : http://www.openintents.org/en/filemanager
Like this:
$date = '08/04/2010 22:15:00';
echo date('h:i A', strtotime($date));
Result:
10:15 PM
More Info:
If you normalize your data first, then you can avoid all the very complex regular expressions required to validate phone numbers. From my experience, complicated regex patterns can have two unwanted side effects: (1) they can have unexpected behavior that would be a pain to debug later, and (2) they can be slower than simpler regex patterns, which may become noticeable when you are executing regex in a loop.
By keeping your regular expressions as simple as possible, you reduce these risks and your code will be easier for others to follow, partly because it will be more predictable. To use your phone number example, first we can normalize the value by stripping out all non-digits like this:
value = $.trim(value).replace(/\D/g, '');
Now your regex pattern for a US phone number (or any other locale) can be much simpler:
/^1?\d{10}$/
Not only is the regular expression much simpler, it is also easier to follow what's going on: a value optionally leading with number one (US country code) followed by ten digits. If you want to format the validated value to make it look pretty, then you can use this slightly longer regex pattern:
/^1?(\d{3})(\d{3})(\d{4})$/
This means an optional leading number one followed by three digits, another three digits, and ending with four digits. With each group of numbers memorized, you can output it any way you want. Here's a codepen using jQuery Validation to illustrate this for two locales (Singapore and US):
App Passwords helped me.
try yo write document.getElementById('id').style.visibility="hidden";
You must have some virtual function declared in one of the parent classes and never implemented in any of the child classes. Make sure that all virtual functions are implemented somewhere in the inheritence chain. If a class's definition includes a pure virtual function that is never implemented, an instance of that class cannot ever be constructed.
pip has mirror support
pip --use-mirrors install yolk
As of version 1.5, this option will be removed:
1.5 (unreleased)
BACKWARD INCOMPATIBLE pip no longer supports the --use-mirrors, -M, and --mirrors flags. The mirroring support has been removed. In order to use a mirror specify it as the primary index with -i or --index-url, or as an additional index with --extra-index-url. (Pull #1098, CVE-2013-5123)
BACKWARD INCOMPATIBLE pip no longer will scrape insecure external urls by default nor will it install externally hosted files by default. Users may opt into installing externally hosted or insecure files or urls using --allow-external PROJECT and --allow-insecure PROJECT. (Pull #1055)
Added colors to the logging output in order to draw attention to important warnings and errors. (Pull #1109)
Added warnings when using an insecure index, find-link, or dependency link. (Pull #1121)
I believe GUIDs are constrained to 16-byte lengths (or 32 bytes for an ASCII hex equivalent).
Just add @Transactional
annotation on top of your test:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"testContext.xml"})
@Transactional
public class StudentSystemTest {
By default Spring will start a new transaction surrounding your test method and @Before
/@After
callbacks, rolling back at the end. It works by default, it's enough to have some transaction manager in the context.
From: 10.3.5.4 Transaction management (bold mine):
In the TestContext framework, transactions are managed by the TransactionalTestExecutionListener. Note that
TransactionalTestExecutionListener
is configured by default, even if you do not explicitly declare@TestExecutionListeners
on your test class. To enable support for transactions, however, you must provide aPlatformTransactionManager
bean in the application context loaded by@ContextConfiguration
semantics. In addition, you must declare@Transactional
either at the class or method level for your tests.
Because templates are compiled when required, this forces a restriction for multi-file projects: the implementation (definition) of a template class or function must be in the same file as its declaration. That means that we cannot separate the interface in a separate header file, and that we must include both interface and implementation in any file that uses the templates.
Stefan Haustein function for xamarin/c#:
public string GetFilenameFromURI(Android.Net.Uri uri)
{
string result = null;
if (uri.Scheme == "content")
{
using (var cursor = Application.Context.ContentResolver.Query(uri, null, null, null, null))
{
try
{
if (cursor != null && cursor.MoveToFirst())
{
result = cursor.GetString(cursor.GetColumnIndex(OpenableColumns.DisplayName));
}
}
finally
{
cursor.Close();
}
}
}
if (result == null)
{
result = uri.Path;
int cut = result.LastIndexOf('/');
if (cut != -1)
{
result = result.Substring(cut + 1);
}
}
return result;
}
You can call sortable
on a <tbody>
instead of on the individual rows.
<table>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
</tbody>
</table>?
<script>
$('tbody').sortable();
</script>
$(function() {_x000D_
$( "tbody" ).sortable();_x000D_
});
_x000D_
_x000D_
table {_x000D_
border-spacing: collapse;_x000D_
border-spacing: 0;_x000D_
}_x000D_
td {_x000D_
width: 50px;_x000D_
height: 25px;_x000D_
border: 1px solid black;_x000D_
}
_x000D_
_x000D_
_x000D_
<link href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet">_x000D_
<script src="//code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>_x000D_
_x000D_
<table>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td>2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3</td>_x000D_
<td>4</td>_x000D_
</tr>_x000D_
<tr> _x000D_
<td>5</td>_x000D_
<td>6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>7</td>_x000D_
<td>8</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>9</td> _x000D_
<td>10</td>_x000D_
</tr> _x000D_
</tbody> _x000D_
</table>
_x000D_
IP addresses are part of the Network layer in the "seven-layer stack". The Network layer can do whatever it wants to do with the IP address. That's what happens with a proxy server, NAT, relay, or whatever.
The Application layer should not depend on the IP address in any way. In particular, an IP Address is not meant to be an identifier of anything other than the idenfitier of one end of a network connection. As soon as a connection is closed, you should expect the IP address (of the same user) to change.
I think the answer is here (possibly duplicate):
How to test if a file is a directory in a batch script?
IF EXIST %VAR%\NUL ECHO It's a directory
Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.
As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)
if exist "c:\folder\" echo folder exists
should be enough for modern windows.
This worked like a charm for me, of-course it requires super-user privileges :-)
# hcitool cc <target-bdaddr>; hcitool auth <target-bdaddr>
To get <target-bdaddr>
you may issue below command:
$ hcitool scan
Note: Exclude #
& $
as they are command line prompts.
Definitely svn
, since Windows is—at best—a second-class citizen in the world of git
(see http://en.wikipedia.org/wiki/Git_(software)#Portability for more details).
UPDATE: Sorry for the broken link, but I've given up trying to get SO to work with URIs that contain parentheses. [link fixed now. -ed]
From the Security
point of view we can use this practical example:
DBCursor makeConnection(String IP,String PORT,String USER,String PASS,String TABLE) {
// if strings were mutable IP,PORT,USER,PASS can be changed by validate function
Boolean validated = validate(IP,PORT,USER,PASS);
// here we are not sure if IP, PORT, USER, PASS changed or not ??
if (validated) {
DBConnection conn = doConnection(IP,PORT,USER,PASS);
}
// rest of the code goes here ....
}
Use this - http://jgilfelt.github.io/android-actionbarstylegenerator/
Good tool to customize your actionbar with a live preview in couple of minutes.
if you put your full code here so i can help you. if your setting the listener in XML and calling the set background color on View so it will change the background color of the view means it ur Botton so put ur listener in ur activity and then change the color of your view
Almost by definition, the client-side JavaScript is not at the receiving end of a http request, so it has no headers to read. Most commonly, your JavaScript is the result of an http response. If you are trying to get the values of the http request that generated your response, you'll have to write server side code to embed those values in the JavaScript you produce.
It gets a little tricky to have server-side code generate client side code, so be sure that is what you need. For instance, if you want the User-agent information, you might find it sufficient to get the various values that JavaScript provides for browser detection. Start with navigator.appName and navigator.appVersion.
How do I check if something is (not) in a list in Python?
The cheapest and most readable solution is using the in
operator (or in your specific case, not in
). As mentioned in the documentation,
The operators
in
andnot in
test for membership.x in s
evaluates toTrue
ifx
is a member ofs
, andFalse
otherwise.x not in s
returns the negation ofx in s
.
Additionally,
The operator
not in
is defined to have the inverse true value ofin
.
y not in x
is logically the same as not y in x
.
Here are a few examples:
'a' in [1, 2, 3]
# False
'c' in ['a', 'b', 'c']
# True
'a' not in [1, 2, 3]
# True
'c' not in ['a', 'b', 'c']
# False
This also works with tuples, since tuples are hashable (as a consequence of the fact that they are also immutable):
(1, 2) in [(3, 4), (1, 2)]
# True
If the object on the RHS defines a __contains__()
method, in
will internally call it, as noted in the last paragraph of the Comparisons section of the docs.
...
in
andnot in
, are supported by types that are iterable or implement the__contains__()
method. For example, you could (but shouldn't) do this:
[3, 2, 1].__contains__(1)
# True
in
short-circuits, so if your element is at the start of the list, in
evaluates faster:
lst = list(range(10001))
%timeit 1 in lst
%timeit 10000 in lst # Expected to take longer time.
68.9 ns ± 0.613 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
178 µs ± 5.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
If you want to do more than just check whether an item is in a list, there are options:
list.index
can be used to retrieve the index of an item. If that element does not exist, a ValueError
is raised.list.count
can be used if you want to count the occurrences.set
s?Ask yourself these questions:
hash
on them?If you answered "yes" to these questions, you should be using a set
instead. An in
membership test on list
s is O(n) time complexity. This means that python has to do a linear scan of your list, visiting each element and comparing it against the search item. If you're doing this repeatedly, or if the lists are large, this operation will incur an overhead.
set
objects, on the other hand, hash their values for constant time membership check. The check is also done using in
:
1 in {1, 2, 3}
# True
'a' not in {'a', 'b', 'c'}
# False
(1, 2) in {('a', 'c'), (1, 2)}
# True
If you're unfortunate enough that the element you're searching/not searching for is at the end of your list, python will have scanned the list upto the end. This is evident from the timings below:
l = list(range(100001))
s = set(l)
%timeit 100000 in l
%timeit 100000 in s
2.58 ms ± 58.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
101 ns ± 9.53 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
As a reminder, this is a suitable option as long as the elements you're storing and looking up are hashable. IOW, they would either have to be immutable types, or objects that implement __hash__
.
You can use std::to_string in C++11
float val = 2.5;
std::string my_val = std::to_string(val);
Use set()
:
woduplicates = set(lseparatedOrblist)
Returns a set without duplicates. If you, for some reason, need a list back:
woduplicates = list(set(lseperatedOrblist))
This will, however, have a different order than your original list.
Maybe not very elegant, but it does the job:
exec(open("script.py").read())
give id to submit button
<button id="btnSave" type="submit" class="btn btn-success"><i class="glyphicon glyphicon-trash"></i> Save</button>
$('#btnSave').click(function() {
$('#StudentModal').modal('hide');
});
Also you forgot to close last div.
</div>
Hope this helps.
There's a nice article which may answer your question /only it prints the paths instead of collecting them/. Please note that you can experiment with the C++/Python samples in the online IDE.
http://www.geeksforgeeks.org/find-paths-given-source-destination/
So you are asking for ArgMin
or ArgMax
. C# doesn't have a built-in API for those.
I've been looking for a clean and efficient (O(n) in time) way to do this. And I think I found one:
The general form of this pattern is:
var min = data.Select(x => (key(x), x)).Min().Item2;
^ ^ ^
the sorting key | take the associated original item
Min by key(.)
Specially, using the example in original question:
For C# 7.0 and above that supports value tuple:
var youngest = people.Select(p => (p.DateOfBirth, p)).Min().Item2;
For C# version before 7.0, anonymous type can be used instead:
var youngest = people.Select(p => new {age = p.DateOfBirth, ppl = p}).Min().ppl;
They work because both value tuple and anonymous type have sensible default comparers: for (x1, y1) and (x2, y2), it first compares x1
vs x2
, then y1
vs y2
. That's why the built-in .Min
can be used on those types.
And since both anonymous type and value tuple are value types, they should be both very efficient.
NOTE
In my above ArgMin
implementations I assumed DateOfBirth
to take type DateTime
for simplicity and clarity. The original question asks to exclude those entries with null DateOfBirth
field:
Null DateOfBirth values are set to DateTime.MaxValue in order to rule them out of the Min consideration (assuming at least one has a specified DOB).
It can be achieved with a pre-filtering
people.Where(p => p.DateOfBirth.HasValue)
So it's immaterial to the question of implementing ArgMin
or ArgMax
.
NOTE 2
The above approach has a caveat that when there are two instances that have the same min value, then the Min()
implementation will try to compare the instances as a tie-breaker. However, if the class of the instances does not implement IComparable
, then a runtime error will be thrown:
At least one object must implement IComparable
Luckily, this can still be fixed rather cleanly. The idea is to associate a distanct "ID" with each entry that serves as the unambiguous tie-breaker. We can use an incremental ID for each entry. Still using the people age as example:
var youngest = Enumerable.Range(0, int.MaxValue)
.Zip(people, (idx, ppl) => (ppl.DateOfBirth, idx, ppl)).Min().Item3;
I encounted this error and found that it was because the "strict" parameter was set to true in the tsconfig.json file. Just set it "false" (obviously). In my case I had generated the tsconfig file from the cmd prompt and simply missed the "strict" parameter, which was located further down in the file.
From the man
page:
-d delim The first character of delim is used to terminate the input line, rather than newline.
You are using -d,
which will terminate the input line on the comma. It will not read the rest of the line. That's why $y is empty.
Observables are often compared to promises. Here are some key differences:
Observables are declarative; computation does not start until subscription. Promises execute immediately on creation. This makes observables useful for defining recipes that can be run whenever you need the result.
Observables provide many values. Promises provide one. This makes observables useful for getting multiple values over time.
Observables differentiate between chaining and subscription. Promises only have .then() clauses. This makes observables useful for creating complex transformation recipes to be used by other parts of the system, without causing the work to be executed.
Observables subscribe() is responsible for handling errors. Promises push errors to the child promises. This makes observables useful for centralized and predictable error handling.
That is the most simplest difference that you may found on ANGULAR.IO docs. rest answer is given by most is correct at its own place
"%f"
is the (or at least one) correct format for a double. There is no format for a float
, because if you attempt to pass a float
to printf
, it'll be promoted to double
before printf
receives it1. "%lf"
is also acceptable under the current standard -- the l
is specified as having no effect if followed by the f
conversion specifier (among others).
Note that this is one place that printf
format strings differ substantially from scanf
(and fscanf
, etc.) format strings. For output, you're passing a value, which will be promoted from float
to double
when passed as a variadic parameter. For input you're passing a pointer, which is not promoted, so you have to tell scanf
whether you want to read a float
or a double
, so for scanf
, %f
means you want to read a float
and %lf
means you want to read a double
(and, for what it's worth, for a long double
, you use %Lf
for either printf
or scanf
).
1. C99, §6.5.2.2/6: "If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions." In C++ the wording is somewhat different (e.g., it doesn't use the word "prototype") but the effect is the same: all the variadic parameters undergo default promotions before they're received by the function.
Be aware of the Input::all()
, it will Include the previous ?page=
values again and again in each page you open !
for example if you are in ?page=1
and you open the next page, it will open ?page=1&page=2
So the last value page takes will be the page you see ! not the page you want to see
Solution : use Input::except(array('page'))
Using wget
, which is usually part of default system installation:
bash <(wget -qO- http://mywebsite.com/myscript.txt)
I was also getting the same error.
nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)
and when i typed the localhost in the browser, then i was getting
It works!
This is the default web page for this server.
The web server software is running but no content has been added, yet. instead of nginx welcome page, apache2 is running on the same port,
find the apache2 ports.conf file
sudo /etc/apache2/ports.conf
change the port other then 80
, i make it as 70
save the file
restart your system
it will works for you also, if you type the localhost in the browser, you will get nginx welcome page
In Java, what's the difference between a keystore and a truststore?
Here's the description from the Java docs at Java Secure Socket Extension (JSSE) Reference Guide. I don't think it tells you anything different from what others have said. But it does provide the official reference.
keystore/truststore
A keystore is a database of key material. Key material is used for a variety of purposes, including authentication and data integrity. Various types of keystores are available, including PKCS12 and Oracle's JKS.
Generally speaking, keystore information can be grouped into two categories: key entries and trusted certificate entries. A key entry consists of an entity's identity and its private key, and can be used for a variety of cryptographic purposes. In contrast, a trusted certificate entry contains only a public key in addition to the entity's identity. Thus, a trusted certificate entry cannot be used where a private key is required, such as in a javax.net.ssl.KeyManager. In the JDK implementation of JKS, a keystore may contain both key entries and trusted certificate entries.
A truststore is a keystore that is used when making decisions about what to trust. If you receive data from an entity that you already trust, and if you can verify that the entity is the one that it claims to be, then you can assume that the data really came from that entity.
An entry should only be added to a truststore if the user trusts that entity. By either generating a key pair or by importing a certificate, the user gives trust to that entry. Any entry in the truststore is considered a trusted entry.
It may be useful to have two different keystore files: one containing just your key entries, and the other containing your trusted certificate entries, including CA certificates. The former contains private information, whereas the latter does not. Using two files instead of a single keystore file provides a cleaner separation of the logical distinction between your own certificates (and corresponding private keys) and others' certificates. To provide more protection for your private keys, store them in a keystore with restricted access, and provide the trusted certificates in a more publicly accessible keystore if needed.
You can use FolderBrowserDialog instead of FileDialog and get the path from the OK result.
FolderBrowserDialog browser = new FolderBrowserDialog();
string tempPath ="";
if (browser.ShowDialog() == DialogResult.OK)
{
tempPath = browser.SelectedPath; // prints path
}
The reverse() is used to adhere the django DRY principle i.e if you change the url in future then you can reference that url using reverse(urlname).
It should be noted that if you try to set the environment variable to a bash evaluation it won't store what you expect. Example:
from os import environ
environ["JAVA_HOME"] = "$(/usr/libexec/java_home)"
This won't evaluate it like it does in a shell, so instead of getting /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home
as a path you will get the literal expression $(/usr/libexec/java_home)
.
Make sure to evaluate it before setting the environment variable, like so:
from os import environ
from subprocess import Popen, PIPE
bash_variable = "$(/usr/libexec/java_home)"
capture = Popen(f"echo {bash_variable}", stdout=PIPE, shell=True)
std_out, std_err = capture.communicate()
return_code = capture.returncode
if return_code == 0:
evaluated_env = std_out.decode().strip()
environ["JAVA_HOME"] = evaluated_env
else:
print(f"Error: Unable to find environment variable {bash_variable}")
$('#field-function_purpose')
will get you the element with ID field-function_purpose
, which is your div element. text()
returns you the content of the div.
var x = $('#field-function_purpose').text();
To delete all directories with the name foo
, run:
find -type d -name foo -a -prune -exec rm -rf {} \;
The other answers are missing an important thing: the -prune
option. Without -prune
, GNU find will delete the directory with the matching name and then try to recurse into it to find more directories that match. The -prune
option tells it to not recurse into a directory that matched the conditions.
To redirect your logs output to a file, you need to use the FileAppender and need to define other file details in your log4j.properties/xml file. Here is a sample properties file for the same:
# Root logger option
log4j.rootLogger=INFO, file
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\loging.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
Follow this tutorial to learn more about log4j usage:
http://www.mkyong.com/logging/log4j-log4j-properties-examples/
I had the same issue. Tried all the solutions mentioned here but nothing worked. So i rebooted my device and suddenly the issue solved.
try this ^^
$(document).ready(function() {
$("form").bind("keypress", function(e) {
if (e.keyCode == 13) {
return false;
}
});
});
Hope this helps
You can't run this particular piece of code in the interactive interpreter. You'll need to save it into a file first so that you can pass the argument to it like this
$ python hello.py user338690
Taken from that page, this will unset all of the cookies for your domain:
// unset cookies
if (isset($_SERVER['HTTP_COOKIE'])) {
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
foreach($cookies as $cookie) {
$parts = explode('=', $cookie);
$name = trim($parts[0]);
setcookie($name, '', time()-1000);
setcookie($name, '', time()-1000, '/');
}
}
if (myReader.HasRows) //The key Word is **.HasRows**
{
ltlAdditional.Text = "Contains data";
}
else
{
ltlAdditional.Text = "Is null Or Empty";
}
You can try as.vector(t(test))
. Please note that, if you want to do it by columns you should use unlist(test)
.
So, your goal is to search and replace?
According to the Official Visual Studio's keyboard shotcuts pdf, you can press Ctrl + H on Windows and Linux, or ??F on Mac to enable search and replace tool:
If you mean to disable the code, you just have to put <h1>
in search, and replace to ####
.
But if you want to use this regex instead, you may enable it in the icon: and use the regex: <h1>(.+?)<\/h1>
and replace to: #### $1
.
And as @tpartee suggested, here is some more information about Visual Studio's engine if you would like to learn more:
I found the below code very useful, it might help anyone who comes searching here
<html>_x000D_
<body>_x000D_
<div style="width: 50%; height: 50%; background-color: green; float:left;">-</div>_x000D_
<div style="width: 50%; height: 50%; background-color: blue; float:right;">-</div>_x000D_
<div style="width: 100%; height: 50%; background-color: red; clear:both">-</div>_x000D_
</body>_x000D_
</html>
_x000D_
@Jason is correct in a way but not entirely.
update
Update the registered submodules, i.e. clone missing submodules and checkout the commit specified in the index of the containing repository. This will make the submodules HEAD be detached unless --rebase or --merge is specified or the key submodule.$name.update is set to rebase or merge.
So, git submodule update
does checkout, but it is to the commit in the index of the containing repository. It does not yet know of the new commit upstream at all. So go to your submodule, get the commit you want and commit the updated submodule state in the main repository and then do the git submodule update
.
Use like this (source):
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie = c_name+"="+c_value+"; path=/";
}
Node : http://www.w3schools.com/js/js_htmldom_nodes.asp
The Node object represents a single node in the document tree. A node can be an element node, an attribute node, a text node, or any other of the node types explained in the Node Types chapter.
Element : http://www.w3schools.com/js/js_htmldom_elements.asp
The Element object represents an element in an XML document. Elements may contain attributes, other elements, or text. If an element contains text, the text is represented in a text-node.
duplicate :
If you want to run a task that's associated with a host, but on different host, you should try delegate_to.
In your case, you should delegate to your localhost (ansible master) and calling ansible-playbook
command
You could write a script to update the FK's for you.. check out this blog: http://multunus.com/2011/03/how-to-easily-merge-two-identical-mysql-databases/
They have a clever script to use the information_schema tables to get the "id" columns:
SET @db:='id_new';
select @max_id:=max(AUTO_INCREMENT) from information_schema.tables;
select concat('update ',table_name,' set ', column_name,' = ',column_name,'+',@max_id,' ; ') from information_schema.columns where table_schema=@db and column_name like '%id' into outfile 'update_ids.sql';
use id_new
source update_ids.sql;
You can do the same with .ix
, like this:
In [1]: df = pd.DataFrame(np.random.randn(5,4), columns=list('abcd'))
In [2]: df
Out[2]:
a b c d
0 -0.323772 0.839542 0.173414 -1.341793
1 -1.001287 0.676910 0.465536 0.229544
2 0.963484 -0.905302 -0.435821 1.934512
3 0.266113 -0.034305 -0.110272 -0.720599
4 -0.522134 -0.913792 1.862832 0.314315
In [3]: df.ix[df.a>0, ['b','c']] = 0
In [4]: df
Out[4]:
a b c d
0 -0.323772 0.839542 0.173414 -1.341793
1 -1.001287 0.676910 0.465536 0.229544
2 0.963484 0.000000 0.000000 1.934512
3 0.266113 0.000000 0.000000 -0.720599
4 -0.522134 -0.913792 1.862832 0.314315
EDIT
After the extra information, the following will return all columns - where some condition is met - with halved values:
>> condition = df.a > 0
>> df[condition][[i for i in df.columns.values if i not in ['a']]].apply(lambda x: x/2)
I hope this helps!
That on code behind redirect to the same page.
Response.Redirect(Request.RawUrl);
This worked
apt-get install php7.0-zip
and no need to restart php7.0-fpm
manually.
Unpacking
php7.0-zip
(7.0.16-4+deb.sury.org~trusty+1
) ...
Processing triggers forphp7.0-fpm
(7.0.11-1+deb.sury.org~trusty+1
) ...
php7.0-fpm
stop/waiting
php7.0-fpm
start/running, process 1572
php7.0-fpm
stop/waiting
php7.0-fpm
start/running, process 1777
Setting upphp7.0-zip
(7.0.16-4+deb.sury.org~trusty+1
) ...
locale: Cannot setLC_ALL
to default locale: No such file or directoryCreating config file
/etc/php/7.0/mods-available/zip.ini
with new version
Processing triggers forphp7.0-fpm
(7.0.11-1+deb.sury.org~trusty+1
) ...
php7.0-fpm
stop/waiting
php7.0-fpm
start/running, process 2354
php7.0-fpm
stop/waiting
php7.0-fpm
start/running, process 2397
As Marc says, you run it exactly like you would from the command line. See Creating SQL Server Agent Jobs on MSDN.
You could also use the CountDownLatch
object like explained here.
Please don´t forget to check the obj parameter against null
when overriding Equals()
.
And also compare the type.
public override bool Equals(object obj)
{
Foo fooItem = obj as Foo;
if (fooItem == null)
{
return false;
}
return fooItem.FooId == this.FooId;
}
The reason for this is: Equals
must return false on comparison to null
. See also http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx
Base on @Jonik answer I have created fully functional extension to ArrayAdapter
class SpinnerArrayAdapter<T> : ArrayAdapter<T> {
private val selectText : String
private val resource: Int
private val fieldId : Int
private val inflater : LayoutInflater
constructor(context: Context?, resource: Int, objects: Array<T>, selectText : String? = null) : super(context, resource, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = 0
this.inflater = LayoutInflater.from(context)
}
constructor(context: Context?, resource : Int, objects: List<T>, selectText : String? = null) : super(context, resource, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = 0
this.inflater = LayoutInflater.from(context)
}
constructor(context: Context?, resource: Int, textViewResourceId: Int, objects: Array<T>, selectText : String? = null) : super(context, resource, textViewResourceId, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = textViewResourceId
this.inflater = LayoutInflater.from(context)
}
constructor(context: Context?, resource : Int, textViewResourceId: Int, objects: List<T>, selectText : String? = null) : super(context, resource, textViewResourceId, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = textViewResourceId
this.inflater = LayoutInflater.from(context)
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup?): View {
if(position == 0) {
return initialSelection(true)
}
return createViewFromResource(inflater, position -1, convertView, parent, resource)
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
if(position == 0) {
return initialSelection(false)
}
return createViewFromResource(inflater, position -1, convertView, parent, resource)
}
override fun getCount(): Int {
return super.getCount() + 1 // adjust for initial selection
}
private fun initialSelection(inDropDown: Boolean) : View {
// Just simple TextView as initial selection.
val view = TextView(context)
view.setText(selectText)
view.setPadding(8, 0, 8, 0)
if(inDropDown) {
// Hide when dropdown is open
view.height = 0
}
return view
}
private fun createViewFromResource(inflater: LayoutInflater, position: Int,
@Nullable convertView: View?, parent: ViewGroup?, resource: Int): View {
val view: View
val text: TextView?
if (convertView == null || (convertView is TextView)) {
view = inflater.inflate(resource, parent, false)
} else {
view = convertView
}
try {
if (fieldId === 0) {
// If no custom field is assigned, assume the whole resource is a TextView
text = view as TextView
} else {
// Otherwise, find the TextView field within the layout
text = view.findViewById(fieldId)
if (text == null) {
throw RuntimeException("Failed to find view with ID "
+ context.getResources().getResourceName(fieldId)
+ " in item layout")
}
}
} catch (e: ClassCastException) {
Log.e("ArrayAdapter", "You must supply a resource ID for a TextView")
throw IllegalStateException(
"ArrayAdapter requires the resource ID to be a TextView", e)
}
val item = getItem(position)
if (item is CharSequence) {
text.text = item
} else {
text.text = item!!.toString()
}
return view
}
I know Stack Overflow frowns on pasting URLs without explanations, but this particular page has a few really good options:
http://www.oratechinfo.co.uk/delimited_lists_to_collections.html
I particularly like this one, which converts the delimited list into a temporary table you can run queries against:
/* Create the output TYPE, here using a VARCHAR2(100) nested table type */
SQL> CREATE TYPE test_type AS TABLE OF VARCHAR2(100);
2 /
Type created.
/* Now, create the function.*/
SQL> CREATE OR REPLACE FUNCTION f_convert(p_list IN VARCHAR2)
2 RETURN test_type
3 AS
4 l_string VARCHAR2(32767) := p_list || ',';
5 l_comma_index PLS_INTEGER;
6 l_index PLS_INTEGER := 1;
7 l_tab test_type := test_type();
8 BEGIN
9 LOOP
10 l_comma_index := INSTR(l_string, ',', l_index);
11 EXIT WHEN l_comma_index = 0;
12 l_tab.EXTEND;
13 l_tab(l_tab.COUNT) := SUBSTR(l_string, l_index, l_comma_index - l_index);
14 l_index := l_comma_index + 1;
15 END LOOP;
16 RETURN l_tab;
17 END f_convert;
18 /
Function created.
/* Prove it works */
SQL> SELECT * FROM TABLE(f_convert('AAA,BBB,CCC,D'));
COLUMN_VALUE
--------------------------------------------------------------------------------
AAA
BBB
CCC
D
4 rows selected.
This is how it is done using the fluent interface of the op4j Java library (1.1. was released Dec '10) :-
List<String> names = Op.onListFor("Ryan", "Julie", "Bob").get();
It's a very cool library that saves you a tonne of time.
For obtaining a reversed copy of an array, look at danielpunkass' solution using reverseObjectEnumerator
.
For reversing a mutable array, you can add the following category to your code:
@implementation NSMutableArray (Reverse)
- (void)reverse {
if ([self count] <= 1)
return;
NSUInteger i = 0;
NSUInteger j = [self count] - 1;
while (i < j) {
[self exchangeObjectAtIndex:i
withObjectAtIndex:j];
i++;
j--;
}
}
@end
If you don't have an image with that name locally, docker will try to pull it from docker hub, but there's no such image on docker hub. Or simply try "docker login".
this is my solution to the problem. I used it in a chatbot to replace the different words at once.
def mass_replace(text, dct):
new_string = ""
old_string = text
while len(old_string) > 0:
s = ""
sk = ""
for k in dct.keys():
if old_string.startswith(k):
s = dct[k]
sk = k
if s:
new_string+=s
old_string = old_string[len(sk):]
else:
new_string+=old_string[0]
old_string = old_string[1:]
return new_string
print mass_replace("The dog hunts the cat", {"dog":"cat", "cat":"dog"})
this will become The cat hunts the dog
The easiest way to add a text to a JFrame:
JFrame window = new JFrame("JFrame with text");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(new BorderLayout());
window.add(new JLabel("Hello World"), BorderLayout.CENTER);
window.pack();
window.setVisible(true);
window.setLocationRelativeTo(null);
Assert also gives you another opportunity to chuckle at Microsoft's UI design skills. I mean: a dialog with three buttons Abort, Retry, Ignore, and an explanation of how to interpret them in the title bar!
I had to specify user name to work on 1.7.1 git version:
git remote set-url origin https://[email protected]/org/project.git
decimalVar.ToString ("#.##"); // returns "" when decimalVar == 0
or
decimalVar.ToString ("0.##"); // returns "0" when decimalVar == 0
Using Blob
as a source for an img
:
template:
<img [src]="url">
component:
public url : SafeResourceUrl;
constructor(private http: HttpClient, private sanitizer: DomSanitizer) {
this.getImage('/api/image.jpg').subscribe(x => this.url = x)
}
public getImage(url: string): Observable<SafeResourceUrl> {
return this.http
.get(url, { responseType: 'blob' })
.pipe(
map(x => {
const urlToBlob = window.URL.createObjectURL(x) // get a URL for the blob
return this.sanitizer.bypassSecurityTrustResourceUrl(urlToBlob); // tell Anuglar to trust this value
}),
);
}
Further reference about trusting save values
This works for me,
db.student.find({},{"roll":1})
no condition in where clause i.e., inside first curly braces. inside next curly braces: list of projection field names to be needed in the result and 1 indicates particular field is the part of the query result
Incase all the answer given does not work, kindly try
String myString = null;
if(myString.trim().equalsIgnoreCase("null")){
//do something
}
This will do
foreach($results['data'] as $result) {
echo $result['type'], '<br>';
}
Does not work for multidimensional arrays, because references are used here.
import numpy as np
# swaps
data = np.random.random(2)
print(data)
data[0], data[1] = data[1], data[0]
print(data)
# does not swap
data = np.random.random((2, 2))
print(data)
data[0], data[1] = data[1], data[0]
print(data)
See also Swap slices of Numpy arrays
Or you can change position of specific
div
using class name
$(document).scroll(function(e){
var scrollTop = $(document).scrollTop();
if(scrollTop > 0){
//console.log(scrollTop);
$('.header').css("position","fixed");
} else {
$('.header').css("position","relative");
}
});
I came across the same issue recently. I had to insert new rows in a document with hidden rows and faced the same issues with you. After some search and some emails in apache poi list, it seems like a bug in shiftrows() when a document has hidden rows.
The approach of @AzharShaikh works fine.
android:ellipsize="end"
android:maxLines="1"
But I realize a trouble that TextView will be truncated by word (in default). Show if we have a text like:
test long_line_without_any_space_abcdefgh
the TextView will display:
test...
And I found solution to handle this trouble, replace spaces with the unicode no-break space character, it makes TextView wrap on characters instead of words:
yourString.replace(" ", "\u00A0");
The result:
test long_line_without_any_space_abc...
As of the current JRE implementation, Function.identity()
will always return the same instance while each occurrence of identifier -> identifier
will not only create its own instance but even have a distinct implementation class. For more details, see here.
The reason is that the compiler generates a synthetic method holding the trivial body of that lambda expression (in the case of x->x
, equivalent to return identifier;
) and tell the runtime to create an implementation of the functional interface calling this method. So the runtime sees only different target methods and the current implementation does not analyze the methods to find out whether certain methods are equivalent.
So using Function.identity()
instead of x -> x
might save some memory but that shouldn’t drive your decision if you really think that x -> x
is more readable than Function.identity()
.
You may also consider that when compiling with debug information enabled, the synthetic method will have a line debug attribute pointing to the source code line(s) holding the lambda expression, therefore you have a chance of finding the source of a particular Function
instance while debugging. In contrast, when encountering the instance returned by Function.identity()
during debugging an operation, you won’t know who has called that method and passed the instance to the operation.
In my case the problem was the 32/64 bit driver which I solved by configuring the properties of the sql server job:
If the Node
is not just any node, but actually an Element
(it could also be e.g. an attribute or a text node), you can cast it to Element
and use getElementsByTagName
.
Yeah it suck to get stuck in Scale View.
Host+Home will popup the Virtual machine settings. (by default Host is Right Control)
From there you can change the view settings, as the Menu bar is hidden in Scale View.
Had the same issue, especially when you checked the box not to show the 'Switch to Scale view' dialog.
This you can do while the VM is running.
You could try using the <col>
tag manage table styling for all rows but you will need to set the table-layout:fixed
style on the <table>
or the tables css class and set the overflow
style for the cells
http://www.w3schools.com/TAGS/tag_col.asp
<table class="fixed">
<col width="20px" />
<col width="30px" />
<col width="40px" />
<tr>
<td>text</td>
<td>text</td>
<td>text</td>
</tr>
</table>
and this be your CSS
table.fixed { table-layout:fixed; }
table.fixed td { overflow: hidden; }
str_replace("'", "\'", $mystringWithSingleQuotes);
@Override
public void onDraw(Canvas canvas){
canvas.drawCircle(xPos, yPos,radius, paint);
}
Above is the code to render a circle. Tweak the parameters to your suiting.
Personally I prefer this way.
Modify the .csproj
to add
<ItemGroup>
<ContentWithTargetPath Include="ConfigFiles\MyFirstConfigFile.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<TargetPath>%(Filename)%(Extension)</TargetPath>
</ContentWithTargetPath>
</ItemGroup>
or generalizing, if you want to copy all subfolders and files, you could do:
<ItemGroup>
<ContentWithTargetPath Include="ConfigFiles\**">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<TargetPath>%(RecursiveDir)\%(Filename)%(Extension)</TargetPath>
</ContentWithTargetPath>
</ItemGroup>
BIRT, the Eclipse Business Intelligence and Reporting Tool is open source.
BIRT is an open source Eclipse-based reporting system that integrates with your Java/J2EE application to produce compelling reports. BIRT provides core reporting features such as report layout, data access and scripting.
Easiest way is to hit up the information_schemas...
SELECT *
FROM information_schema.Tables
WHERE [Table_Name]='????'
SELECT *
FROM information_schema.Views
WHERE [Table_Name]='????'
SELECT *
FROM information_schema.Routines
WHERE [Routine_Name]='????'
In one of the INSERT
statements you are attempting to insert a too long string into a string (varchar
or nvarchar
) column.
If it's not obvious which INSERT
is the offender by a mere look at the script, you could count the <1 row affected>
lines that occur before the error message. The obtained number plus one gives you the statement number. In your case it seems to be the second INSERT that produces the error.
In /etc/hosts:
your-ip-address your-host-name
example: 192.168.1.8 master
In /etc/hosts:
Delete the line with 127.0.1.1 (This will cause loopback)
In your core-site, change localhost to your-ip or your-hostname
Now, restart the cluster.
Start your XAMPP server by using:
{XAMPP}\xampp-control.exe
{XAMPP}\apache_start.bat
Then you have to use the URI http://localhost/index.html
because htdocs
is the document root of the Apache server.
If you're getting redirected to http://localhost/xampp/*
, then index.php
located in the htdocs
folder is the problem because index.php files have a higher priority than index.html files.
You could temporarily rename index.php.
Or as a single command:
git push -u origin master:my_test
Pushes the commits from your local master branch to a (possibly new) remote branch my_test
and sets up master
to track origin/my_test
.
I hope is will work for you.
/**
* Image re-size
* @param int $width
* @param int $height
*/
function ImageResize($width, $height, $img_name)
{
/* Get original file size */
list($w, $h) = getimagesize($_FILES['logo_image']['tmp_name']);
/*$ratio = $w / $h;
$size = $width;
$width = $height = min($size, max($w, $h));
if ($ratio < 1) {
$width = $height * $ratio;
} else {
$height = $width / $ratio;
}*/
/* Calculate new image size */
$ratio = max($width/$w, $height/$h);
$h = ceil($height / $ratio);
$x = ($w - $width / $ratio) / 2;
$w = ceil($width / $ratio);
/* set new file name */
$path = $img_name;
/* Save image */
if($_FILES['logo_image']['type']=='image/jpeg')
{
/* Get binary data from image */
$imgString = file_get_contents($_FILES['logo_image']['tmp_name']);
/* create image from string */
$image = imagecreatefromstring($imgString);
$tmp = imagecreatetruecolor($width, $height);
imagecopyresampled($tmp, $image, 0, 0, $x, 0, $width, $height, $w, $h);
imagejpeg($tmp, $path, 100);
}
else if($_FILES['logo_image']['type']=='image/png')
{
$image = imagecreatefrompng($_FILES['logo_image']['tmp_name']);
$tmp = imagecreatetruecolor($width,$height);
imagealphablending($tmp, false);
imagesavealpha($tmp, true);
imagecopyresampled($tmp, $image,0,0,$x,0,$width,$height,$w, $h);
imagepng($tmp, $path, 0);
}
else if($_FILES['logo_image']['type']=='image/gif')
{
$image = imagecreatefromgif($_FILES['logo_image']['tmp_name']);
$tmp = imagecreatetruecolor($width,$height);
$transparent = imagecolorallocatealpha($tmp, 0, 0, 0, 127);
imagefill($tmp, 0, 0, $transparent);
imagealphablending($tmp, true);
imagecopyresampled($tmp, $image,0,0,0,0,$width,$height,$w, $h);
imagegif($tmp, $path);
}
else
{
return false;
}
return true;
imagedestroy($image);
imagedestroy($tmp);
}
I found that some solution didn't work for me in the Simulator within Xcode. Instead, this works:
NSString *deviceModel = (NSString*)[UIDevice currentDevice].model;
if ([[deviceModel substringWithRange:NSMakeRange(0, 4)] isEqualToString:@"iPad"]) {
DebugLog(@"iPad");
} else {
DebugLog(@"iPhone or iPod Touch");
}
if UIDevice.current.model.hasPrefix("iPad") {
print("iPad")
} else {
print("iPhone or iPod Touch")
}
Also in the 'Other Examples' in Xcode the device model comes back as 'iPad Simulator' so the above tweak should sort that out.
Old style using ResultSet
@Transactional(readOnly=true)
public void accessUser() {
EntityManager em = this.getEntityManager();
org.hibernate.Session session = em.unwrap(org.hibernate.Session.class);
session.doWork(new Work() {
@Override
public void execute(Connection con) throws SQLException {
try (PreparedStatement stmt = con.prepareStatement(
"SELECT u.username, u.name, u.email, 'blabla' as passe, login_type as loginType FROM users u")) {
ResultSet rs = stmt.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
System.out.print(rsmd.getColumnName(i) + " (" + rsmd.getColumnTypeName(i) + ") / ");
}
System.out.println("");
while (rs.next()) {
System.out.println("Found username " + rs.getString("USERNAME") + " name " + rs.getString("NAME") + " email " + rs.getString("EMAIL") + " passe " + rs.getString("PASSE") + " email " + rs.getInt("LOGIN_TYPE"));
}
}
}
});
}
If the schema of id is not of type ObjectId you cannot operate with function : findbyId()
A TreeMap
is always sorted by the keys, anything else is impossible. A Comparator
merely allows you to control how the keys are sorted.
If you want the sorted values, you have to extract them into a List
and sort that.
Try this On window load submit your form.
window.onload = function(){
document.forms['member_signup'].submit();
}
Create directory bin
in
D:\sqldeveloper\jdk\
Copy
msvcr100.dll
from
D:\sqldeveloper\jdk\jre\bin
to
D:\sqldeveloper\jdk\bin
Once I faced with the issue when I did not know which the element currently stored in my variable (svg or html) but I needed to get it width and height. I created this function and want to share it:
function computeDimensions(selection) {
var dimensions = null;
var node = selection.node();
if (node instanceof SVGGraphicsElement) { // check if node is svg element
dimensions = node.getBBox();
} else { // else is html element
dimensions = node.getBoundingClientRect();
}
console.log(dimensions);
return dimensions;
}
Little demo in the hidden snippet below. We handle click on the blue div and on the red svg circle with the same function.
var svg = d3.select('svg')
.attr('width', 50)
.attr('height', 50);
function computeDimensions(selection) {
var dimensions = null;
var node = selection.node();
if (node instanceof SVGElement) {
dimensions = node.getBBox();
} else {
dimensions = node.getBoundingClientRect();
}
console.clear();
console.log(dimensions);
return dimensions;
}
var circle = svg
.append("circle")
.attr("r", 20)
.attr("cx", 30)
.attr("cy", 30)
.attr("fill", "red")
.on("click", function() { computeDimensions(circle); });
var div = d3.selectAll("div").on("click", function() { computeDimensions(div) });
_x000D_
* {
margin: 0;
padding: 0;
border: 0;
}
body {
background: #ffd;
}
.div {
display: inline-block;
background-color: blue;
margin-right: 30px;
width: 30px;
height: 30px;
}
_x000D_
<h3>
Click on blue div block or svg circle
</h3>
<svg></svg>
<div class="div"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.min.js"></script>
_x000D_
I know I'm super late to the party here, but I came up with a fairly flexible pattern that should allow some really interesting and versatile implementations.
Set up your class as you normally would, with whatever variables you like.
class MyClass{
protected $myVar1;
protected $myVar2;
public function __construct($obj = null){
if($obj){
foreach (((object)$obj) as $key => $value) {
if(isset($value) && in_array($key, array_keys(get_object_vars($this)))){
$this->$key = $value;
}
}
}
}
}
When you make your object just pass an associative array with the keys of the array the same as the names of your vars, like so...
$sample_variable = new MyClass([
'myVar2'=>123,
'i_dont_want_this_one'=> 'This won\'t make it into the class'
]);
print_r($sample_variable);
The print_r($sample_variable);
after this instantiation yields the following:
MyClass Object ( [myVar1:protected] => [myVar2:protected] => 123 )
Because we've initialize $group
to null in our __construct(...)
, it is also valid to pass nothing whatsoever into the constructor as well, like so...
$sample_variable = new MyClass();
print_r($sample_variable);
Now the output is exactly as expected:
MyClass Object ( [myVar1:protected] => [myVar2:protected] => )
The reason I wrote this was so that I could directly pass the output of json_decode(...)
to my constructor, and not worry about it too much.
This was executed in PHP 7.1. Enjoy!
I had the same question as the OP, and none of those answers fitted my needs. I needed a simple condition, for a simple need.
Here's my answer:
if ($("#myoverflowingelement").prop('scrollWidth') > $("#myoverflowingelement").width() ) {
alert("this element is overflowing !!");
}
else {
alert("this element is not overflowing!!");
}
Also, you can change scrollWidth
by scrollHeight
if you need to test the either case.
Yes, your conclusion is correct. socket.recv
is a blocking call.
socket.recv(1024)
will read at most 1024 bytes, blocking if no data is waiting to be read. If you don't read all data, an other call to socket.recv
won't block.
socket.recv
will also end with an empty string if the connection is closed or there is an error.
If you want a non-blocking socket, you can use the select module (a bit more complicated than just using sockets) or you can use socket.setblocking
.
I had issues with socket.setblocking
in the past, but feel free to try it if you want.
in every version of bootstrap,you can do it manually
this do most things that you want for rtl
Say you have a list such as:
a = [9,8,7]
The following two methods are pretty compact ways to get a tuple with the minimum element and its index. Both take a similar time to process. I better like the zip method, but that is my taste.
element, index = min(list(zip(a, range(len(a)))))
min(list(zip(a, range(len(a)))))
(7, 2)
timeit min(list(zip(a, range(len(a)))))
1.36 µs ± 107 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
index, element = min(list(enumerate(a)), key=lambda x:x[1])
min(list(enumerate(a)), key=lambda x:x[1])
(2, 7)
timeit min(list(enumerate(a)), key=lambda x:x[1])
1.45 µs ± 78.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
You can add it as script file. save the txt file with js suffix
in the head section add
<script src="fileName.js"></script>
_x000D_
We can mock list properly for foreach loop. Please find below code snippet and explanation.
This is my actual class method where I want to create test case by mocking list.
this.nameList
is a list object.
public void setOptions(){
// ....
for (String str : this.nameList) {
str = "-"+str;
}
// ....
}
The foreach loop internally works on iterator, so here we crated mock of iterator.
Mockito framework has facility to return pair of values on particular method call by using Mockito.when().thenReturn()
, i.e. on hasNext()
we pass 1st true and on second call false, so that our loop will continue only two times. On next()
we just return actual return value.
@Test
public void testSetOptions(){
// ...
Iterator<SampleFilter> itr = Mockito.mock(Iterator.class);
Mockito.when(itr.hasNext()).thenReturn(true, false);
Mockito.when(itr.next()).thenReturn(Mockito.any(String.class);
List mockNameList = Mockito.mock(List.class);
Mockito.when(mockNameList.iterator()).thenReturn(itr);
// ...
}
In this way we can avoid sending actual list to test by using mock of list.
The short answer: when you create a ListView you pass it a reference to the data. Now, whenever this data will be altered, it will affect the list view and thus add the item to it, after you'll call adapter.notifyDataSetChanged();.
If you're using a RecyclerView, update only the last element (if you've added it at the end of the list of objs) to save memory with: mAdapter.notifyItemInserted(mItems.size() - 1);
public static void main(String[] args) {
try{
// factory = new Configuration().configure().buildSessionFactory();
factory = new AnnotationConfiguration().
configure().
//addPackage("com.xyz") //add package if used.
addAnnotatedClass(Employee.class).
buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}//you can write like this in your test class inside main method.this way you will be able to do the things using annotaions only
Another solution is to use a state and lifecycle hooks in the routed component and a search statement in the to
property of the <Link />
component. The search parameters can later be accessed via new URLSearchParams()
;
<Link
key={id}
to={{
pathname: this.props.match.url + '/' + foo,
search: '?foo=' + foo
}} />
<Route path="/details/:foo" component={DetailsPage}/>
export default class DetailsPage extends Component {
state = {
foo: ''
}
componentDidMount () {
this.parseQueryParams();
}
componentDidUpdate() {
this.parseQueryParams();
}
parseQueryParams () {
const query = new URLSearchParams(this.props.location.search);
for (let param of query.entries()) {
if (this.state.foo!== param[1]) {
this.setState({foo: param[1]});
}
}
}
render() {
return(
<div>
<h2>{this.state.foo}</h2>
</div>
)
}
}
If you replace the double ampersand with a single ampersand, the scripts will run concurrently.
I was able to fix the sub-menu's always pinning to the top of the parent menu from Andres's answer with the following addition:
.dropdown-menu li {
position: relative;
}
I also add an icon "icon-chevron-right" on items which contain menu sub-menus, and change the icon from black to white on hover (to compliment the text changing to white and look better with the selected blue background).
Here is the full less/css change (replace the above with this):
.dropdown-menu li {
position: relative;
[class^="icon-"] {
float: right;
}
&:hover {
// Switch to white icons on hover
[class^="icon-"] {
background-image: url("../img/glyphicons-halflings-white.png");
}
}
}
The windows object has a windows field in which it is cloned and stores the date of the open window, close should be called on this field:
window.open("", '_self').window.close();
Just run below command:
SELECT setval('my_table_seq', (SELECT max(id) FROM my_table));
Yes and no. Self signed certificates result in that warning message because the certificate was not signed by a trusted Certificate Authority. There are a few options that you can consider to remove this warning on your local machine. See the highest ranked answers to this question for details:
What do I need to do to get Internet Explorer 8 to accept a self signed certificate?
Hope this helps!
EDIT:
Sorry, I wasn't initially aware that you were constrained to localhost. You can attempt to follow the directions on the the link below to "Generate a Self Signed Certificate with the Correct Common Name."
http://www.sslshopper.com/article-how-to-create-a-self-signed-certificate-in-iis-7.html
Well, we can eliminate code error because I tested the code on my own server (PHP 5).
Here's what to check for:
Are you calling session_unset() or session_destroy() anywhere? These functions will delete the session data immediately. If I put these at the end of my script, it begins behaving exactly like you describe.
Does it act the same in all browsers? If it works on one browser and not another, you may have a configuration problem on the nonfunctioning browser (i.e. you turned off cookies and forgot to turn them on, or are blocking cookies by mistake).
Is the session folder writable? You can't test this with is_writable(), so you'll need to go to the folder (from phpinfo() it looks like /var/php_sessions) and make sure sessions are actually getting created.
For future Googlers i've a different approach to check if it's last element. It's similar to last lines in OP question.
This directly compares elements rather than just checking index numbers.
$yourset.each(function() {
var $this = $(this);
if($this[0] === $yourset.last()[0]) {
//$this is the last one
}
});
You need its pid... use "ps -A" to find it.
I will demonstrate with code that does not use classes:
def state_init(state):
state['field'] = 'init'
def state_add(state, x):
state['field'] += x
def state_mult(state, x):
state['field'] *= x
def state_getField(state):
return state['field']
myself = {}
state_init(myself)
state_add(myself, 'added')
state_mult(myself, 2)
print( state_getField(myself) )
#--> 'initaddedinitadded'
Classes are just a way to avoid passing in this "state" thing all the time (and other nice things like initializing, class composition, the rarely-needed metaclasses, and supporting custom methods to override operators).
Now let's demonstrate the above code using the built-in python class machinery, to show how it's basically the same thing.
class State(object):
def __init__(self):
self.field = 'init'
def add(self, x):
self.field += x
def mult(self, x):
self.field *= x
s = State()
s.add('added') # self is implicitly passed in
s.mult(2) # self is implicitly passed in
print( s.field )
[migrated my answer from duplicate closed question]
HashSet hs = new HashSet();
hs.addAll(arrayList);
arrayList.clear();
arrayList.addAll(hs);
Trim in array_map change type if you have NULL in value.
Better way to do it:
$result = array_map(function($v){
return is_string($v)?trim($v):$v;
}, $array);
!members.find()
I think now the best way to solve this issue is code above. It works since Groovy 1.8.1 http://docs.groovy-lang.org/docs/next/html/groovy-jdk/java/util/Collection.html#find(). Examples:
def lst1 = []
assert !lst1.find()
def lst2 = [null]
assert !lst2.find()
def lst3 = [null,2,null]
assert lst3.find()
def lst4 = [null,null,null]
assert !lst4.find()
def lst5 = [null, 0, 0.0, false, '', [], 42, 43]
assert lst5.find() == 42
def lst6 = null;
assert !lst6.find()
$ ( cd /; umask 0; setsid your_script.sh </dev/null &>/dev/null & ) &
See the CSS 2.1 standard, section 17.5.3. When you use display:table-row
, the height of the DIV is solely determined by the height of the table-cell
elements in it. Thus, margin, padding, and height on those elements have no effect.
You just missed a little bit.
To get an embedded resource from any assembly, you have to mention the assembly name with your file name as I have mentioned here:
Assembly asm = Assembly.GetExecutingAssembly();
Stream iconStream = asm.GetManifestResourceStream(asm.GetName().Name + "." + "Desert.jpg");
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = iconStream;
bitmap.EndInit();
image1.Source = bitmap;
To fix this issue simply upgrade react-scripts package (check latest version with npm info react-scripts version
):
"react-scripts": "^3.x.x"
with "react-scripts": "^3.4.1"
(or the latest available version)npm install
or yarn install
Some people reported that this issue was caused by running npm audit fix
(avoid it!).
One additional option, is use equals
of Ramda library:
const c = {a: 1, b: 2};
const d = {b: 2, a: 1};
R.equals(c, d); //=> true
I've been trying to activate 'active' class manually with javascript. It's not as usable as a complete library, but for easy cases seems to be enough:
var button = $('#myToggleButton');
button.on('click', function () {
$(this).toggleClass('active');
});
If you think carefully, 'active' class is used by bootstrap when the button is being pressed, not before or after that (our case), so there's no conflict in reuse the same class.
Try this example and tell me if it fails: http://jsbin.com/oYoSALI/1/edit?html,js,output
The format string attack on printf you mentioned isn't specific to the "%x" formatting - in any case where printf has more formatting parameters than passed variables, it will read values from the stack that do not belong to it. You will get the same issue with %d for example. %x is useful when you want to see those values as hex.
As explained in previous answers, %08x will produce a 8 digits hex number, padded by preceding zeros.
Using the formatting in your code example in printf, with no additional parameters:
printf ("%08x %08x %08x %08x");
Will fetch 4 parameters from the stack and display them as 8-digits padded hex numbers.
One more:
def month_converter(month):
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
return months.index(month) + 1
Use File.ReadAllText and File.WriteAllText.
MSDN example excerpt:
// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);
...
// Open the file to read from.
string readText = File.ReadAllText(path);
Use file
. Examples:
> file --mime-type image.png
image.png: image/png
> file -b --mime-type image.png
image/png
> file -i FILE_NAME
image.png: image/png; charset=binary
(For future reference.)
Quite possibly the fastest way to do this would be to use memory mapped files (so primarily copying memory, and the OS handling the file reads/writes via its paging/memory management).
Memory Mapped files are supported in managed code in .NET 4.0.
But as noted, you need to profile, and expect to switch to native code for maximum performance.
Here's my solution using URL
and try with resources
phrase to catch the exceptions.
/**
* Created by mona on 5/27/16.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class ReadFromWeb {
public static void readFromWeb(String webURL) throws IOException {
URL url = new URL(webURL);
InputStream is = url.openStream();
try( BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
catch (MalformedURLException e) {
e.printStackTrace();
throw new MalformedURLException("URL is malformed!!");
}
catch (IOException e) {
e.printStackTrace();
throw new IOException();
}
}
public static void main(String[] args) throws IOException {
String url = "https://madison.craigslist.org/search/sub";
readFromWeb(url);
}
}
You could additionally save it to file based on your needs or parse it using XML
or HTML
libraries.
As a hack, you could consider having a special handling on the client side, converting 'Null' string to something that will never occur, for example, XXNULLXX and converting back on the server.
It is not pretty, but it may solve the issue for such a boundary case.
I used this and it worked for me in Laravel 5.3.18:
<?php echo URL::to('resources/assets/css/yourcssfile.css') ?>
IMPORTANT NOTE: This will only work when you have already removed "public" from your URL. To do this, you may check out this helpful tutorial.
In my case setting Java Max Heap Size from 2g to 1g worked.
Add following to application module's build.gradle file
android {
dexOptions {
javaMaxHeapSize "1g"
}
}
There are two intents to call/start calling: ACTION_CALL and ACTION_DIAL.
ACTION_DIAL
will only open the dialer with the number
filled in, but allows the user to actually call or reject the call
. ACTION_CALL
will immediately call the number and requires an extra permission.
So make sure you have the permission
uses-permission android:name="android.permission.CALL_PHONE"
in your AndroidManifest.xml
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dbm.pkg"
android:versionCode="1"
android:versionName="1.0">
<!-- NOTE! Your uses-permission must be outside the "application" tag
but within the "manifest" tag. -->
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:icon="@drawable/icon"
android:label="@string/app_name">
<!-- Insert your other stuff here -->
</application>
<uses-sdk android:minSdkVersion="9" />
</manifest>
If when you set disabled="disabled" immediately after the user clicks the button, and the form doesn't submit because of that, you could try two things:
//First choice [given myForm = your form]:
myInputButton.disabled = "disabled";
myForm.submit()
//Second choice:
setTimeout(disableFunction, 1);
//so the form will submit and then almost instantly, the button will be disabled
Although I honestly bet there will be a better way to do this, than that.
This is the solution that I ended up using:
import pip
def install(package):
# Debugging
# pip.main(["install", "--pre", "--upgrade", "--no-index",
# "--find-links=.", package, "--log-file", "log.txt", "-vv"])
pip.main(["install", "--upgrade", "--no-index", "--find-links=.", package])
if __name__ == "__main__":
install("mypackagename")
raw_input("Press Enter to Exit...\n")
I pieced this together from pip install examples as well as from Rikard's answer on another question. The "--pre" argument lets you install non-production versions. The "--no-index" argument avoids searching the PyPI indexes. The "--find-links=." argument searches in the local folder (this can be relative or absolute). I used the "--log-file", "log.txt", and "-vv" arguments for debugging. The "--upgrade" argument lets you install newer versions over older ones.
I also found a good way to uninstall them. This is useful when you have several different Python environments. It's the same basic format, just using "uninstall" instead of "install", with a safety measure to prevent unintended uninstalls:
import pip
def uninstall(package):
response = raw_input("Uninstall '%s'? [y/n]:\n" % package)
if "y" in response.lower():
# Debugging
# pip.main(["uninstall", package, "-vv"])
pip.main(["uninstall", package])
pass
if __name__ == "__main__":
uninstall("mypackagename")
raw_input("Press Enter to Exit...\n")
The local folder contains these files: install.py, uninstall.py, mypackagename-1.0.zip
You cannot and should not rely on the ordering of elements within a JSON object.
From the JSON specification at http://www.json.org/
An object is an unordered set of name/value pairs
As a consequence, JSON libraries are free to rearrange the order of the elements as they see fit. This is not a bug.
(See update at end of answer.)
You can get a NodeList
of all of the input
elements via getElementsByTagName
(DOM specification, MDC, MSDN), then simply loop through it:
var inputs, index;
inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
// deal with inputs[index] element.
}
There I've used it on the document
, which will search the entire document. It also exists on individual elements (DOM specification), allowing you to search only their descendants rather than the whole document, e.g.:
var container, inputs, index;
// Get the container element
container = document.getElementById('container');
// Find its child `input` elements
inputs = container.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
// deal with inputs[index] element.
}
...but you've said you don't want to use the parent form
, so the first example is more applicable to your question (the second is just there for completeness, in case someone else finding this answer needs to know).
Update: getElementsByTagName
is an absolutely fine way to do the above, but what if you want to do something slightly more complicated, like just finding all of the checkboxes instead of all of the input
elements?
That's where the useful querySelectorAll
comes in: It lets us get a list of elements that match any CSS selector we want. So for our checkboxes example:
var checkboxes = document.querySelectorAll("input[type=checkbox]");
You can also use it at the element level. For instance, if we have a div
element in our element
variable, we can find all of the span
s with the class foo
that are inside that div
like this:
var fooSpans = element.querySelectorAll("span.foo");
querySelectorAll
and its cousin querySelector
(which just finds the first matching element instead of giving you a list) are supported by all modern browsers, and also IE8.
You convert type np.dot(X, T)
to float32 like this:
z=np.array(np.dot(X, T),dtype=np.float32)
def sigmoid(X, T):
return (1.0 / (1.0 + np.exp(-z)))
Hopefully it will finally work!
Try $(this).attr("src", urlAbsolute);
This post will go through the following topics:
merge
has shortcomings here)Oftentimes, the situation arises when multiple DataFrames are to be merged together. Naively, this can be done by chaining merge
calls:
df1.merge(df2, ...).merge(df3, ...)
However, this quickly gets out of hand for many DataFrames. Furthermore, it may be necessary to generalise for an unknown number of DataFrames.
Here I introduce pd.concat
for multi-way joins on unique keys, and DataFrame.join
for multi-way joins on non-unique keys. First, the setup.
# Setup.
np.random.seed(0)
A = pd.DataFrame({'key': ['A', 'B', 'C', 'D'], 'valueA': np.random.randn(4)})
B = pd.DataFrame({'key': ['B', 'D', 'E', 'F'], 'valueB': np.random.randn(4)})
C = pd.DataFrame({'key': ['D', 'E', 'J', 'C'], 'valueC': np.ones(4)})
dfs = [A, B, C]
# Note, the "key" column values are unique, so the index is unique.
A2 = A.set_index('key')
B2 = B.set_index('key')
C2 = C.set_index('key')
dfs2 = [A2, B2, C2]
If your keys (here, the key could either be a column or an index) are unique, then you can use pd.concat
. Note that pd.concat
joins DataFrames on the index.
# merge on `key` column, you'll need to set the index before concatenating
pd.concat([
df.set_index('key') for df in dfs], axis=1, join='inner'
).reset_index()
key valueA valueB valueC
0 D 2.240893 -0.977278 1.0
# merge on `key` index
pd.concat(dfs2, axis=1, sort=False, join='inner')
valueA valueB valueC
key
D 2.240893 -0.977278 1.0
Omit join='inner'
for a FULL OUTER JOIN. Note that you cannot specify LEFT or RIGHT OUTER joins (if you need these, use join
, described below).
concat
is fast, but has its shortcomings. It cannot handle duplicates.
A3 = pd.DataFrame({'key': ['A', 'B', 'C', 'D', 'D'], 'valueA': np.random.randn(5)})
pd.concat([df.set_index('key') for df in [A3, B, C]], axis=1, join='inner')
ValueError: Shape of passed values is (3, 4), indices imply (3, 2)
In this situation, we can use join
since it can handle non-unique keys (note that join
joins DataFrames on their index; it calls merge
under the hood and does a LEFT OUTER JOIN unless otherwise specified).
# join on `key` column, set as the index first
# For inner join. For left join, omit the "how" argument.
A.set_index('key').join(
[df.set_index('key') for df in (B, C)], how='inner').reset_index()
key valueA valueB valueC
0 D 2.240893 -0.977278 1.0
# join on `key` index
A3.set_index('key').join([B2, C2], how='inner')
valueA valueB valueC
key
D 1.454274 -0.977278 1.0
D 0.761038 -0.977278 1.0
Jump to other topics in Pandas Merging 101 to continue learning:
* you are here
document.getElementsByClassName
returns an HTMLCollection
(an array-like object) of all elements matching the class name. The style
property is defined for Element
not for HTMLCollection
. You should access the first element using the bracket(subscript) notation.
document.getElementsByClassName('appBanner')[0].style.visibility = 'hidden';
To change the style rules of all elements matching the class, using the Selectors API:
[].forEach.call(document.querySelectorAll('.appBanner'), function (el) {
el.style.visibility = 'hidden';
});
If for...of
is available:
for (let el of document.querySelectorAll('.appBanner')) el.style.visibility = 'hidden';
Try this:
open /etc/apache2/envvars
sudo gedit /etc/apache2/envvars
replace www-data
with your your_username
"export APACHE_RUN_USER=www-data"
replace with
export APACHE_RUN_USER='your_username'
This is more pythonic
my_list = [0, 1, 2, 3, 4, 5] # some list
my_list_copy = list(my_list) # my_list_copy and my_list does not share reference now.
NOTE: This is not safe with a list of referenced objects
One checkbox to rule them all
For people still looking for plugin to control checkboxes through one that's lightweight, has out-of-the-box support for UniformJS and iCheck and gets unchecked when at least one of controlled checkboxes is unchecked (and gets checked when all controlled checkboxes are checked of course) I've created a jQuery checkAll plugin.
Feel free to check the examples on documentation page.
For this question example all you need to do is:
$( '#select_all' ).checkall({
target: 'input[type="checkbox"][name="select"]'
});
Isn't that clear and simple?
If you want to execute a local script remotely without saving that script remotely you can do it like this:
cat local_script.sh | ssh user@remotehost 'bash -'
It works like a charm for me.
I do that even from Windows to Linux given that you have MSYS installed on your Windows computer.