Save Dataframe to csv directly to s3 Python
I found a very simple solution that seems to be working :
s3 = boto3.client("s3")
s3.put_object(
Body=open("filename.csv").read(),
Bucket="your-bucket",
Key="your-key"
)
Hope that helps !
S3 - Access-Control-Allow-Origin Header
I was having a similar problem with loading web fonts, when I clicked on 'add CORS configuration', in the bucket properties, this code was already there:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>HEAD</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>
I just clicked save and it worked a treat, my custom web fonts were loading in IE & Firefox. I'm no expert on this, I just thought this might help you out.
How to write a file or data to an S3 object using boto3
In boto 3, the 'Key.set_contents_from_' methods were replaced by
For example:
import boto3
some_binary_data = b'Here we have some data'
more_binary_data = b'Here we have some more data'
# Method 1: Object.put()
s3 = boto3.resource('s3')
object = s3.Object('my_bucket_name', 'my/key/including/filename.txt')
object.put(Body=some_binary_data)
# Method 2: Client.put_object()
client = boto3.client('s3')
client.put_object(Body=more_binary_data, Bucket='my_bucket_name', Key='my/key/including/anotherfilename.txt')
Alternatively, the binary data can come from reading a file, as described in the official docs comparing boto 2 and boto 3:
Storing Data
Storing data from a file, stream, or string is easy:
# Boto 2.x
from boto.s3.key import Key
key = Key('hello.txt')
key.set_contents_from_file('/tmp/hello.txt')
# Boto 3
s3.Object('mybucket', 'hello.txt').put(Body=open('/tmp/hello.txt', 'rb'))
How can I tell how many objects I've stored in an S3 bucket?
Following is how you can do it using java client.
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.11.519</version>
</dependency>
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ObjectListing;
public class AmazonS3Service {
private static final String S3_ACCESS_KEY_ID = "ACCESS_KEY";
private static final String S3_SECRET_KEY = "SECRET_KEY";
private static final String S3_ENDPOINT = "S3_URL";
private AmazonS3 amazonS3;
public AmazonS3Service() {
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setProtocol(Protocol.HTTPS);
clientConfiguration.setSignerOverride("S3SignerType");
BasicAWSCredentials credentials = new BasicAWSCredentials(S3_ACCESS_KEY_ID, S3_SECRET_KEY);
AWSStaticCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
AmazonS3ClientBuilder.EndpointConfiguration endpointConfiguration = new AmazonS3ClientBuilder.EndpointConfiguration(S3_ENDPOINT, null);
amazonS3 = AmazonS3ClientBuilder.standard().withCredentials(credentialsProvider).withClientConfiguration(clientConfiguration)
.withPathStyleAccessEnabled(true).withEndpointConfiguration(endpointConfiguration).build();
}
public int countObjects(String bucketName) {
int count = 0;
ObjectListing objectListing = amazonS3.listObjects(bucketName);
int currentBatchCount = objectListing.getObjectSummaries().size();
while (currentBatchCount != 0) {
count += currentBatchCount;
objectListing = amazonS3.listNextBatchOfObjects(objectListing);
currentBatchCount = objectListing.getObjectSummaries().size();
}
return count;
}
}
Retrieving subfolders names in S3 bucket from boto3
The AWS cli does this (presumably without fetching and iterating through all keys in the bucket) when you run aws s3 ls s3://my-bucket/
, so I figured there must be a way using boto3.
https://github.com/aws/aws-cli/blob/0fedc4c1b6a7aee13e2ed10c3ada778c702c22c3/awscli/customizations/s3/subcommands.py#L499
It looks like they indeed use Prefix and Delimiter - I was able to write a function that would get me all directories at the root level of a bucket by modifying that code a bit:
def list_folders_in_bucket(bucket):
paginator = boto3.client('s3').get_paginator('list_objects')
folders = []
iterator = paginator.paginate(Bucket=bucket, Prefix='', Delimiter='/', PaginationConfig={'PageSize': None})
for response_data in iterator:
prefixes = response_data.get('CommonPrefixes', [])
for prefix in prefixes:
prefix_name = prefix['Prefix']
if prefix_name.endswith('/'):
folders.append(prefix_name.rstrip('/'))
return folders
Listing contents of a bucket with boto3
So you're asking for the equivalent of aws s3 ls
in boto3. This would be listing all the top level folders and files. This is the closest I could get; it only lists all the top level folders. Surprising how difficult such a simple operation is.
import boto3
def s3_ls():
s3 = boto3.resource('s3')
bucket = s3.Bucket('example-bucket')
result = bucket.meta.client.list_objects(Bucket=bucket.name,
Delimiter='/')
for o in result.get('CommonPrefixes'):
print(o.get('Prefix'))
How do you search an amazon s3 bucket?
I tried in the following way
aws s3 ls s3://Bucket1/folder1/2019/ --recursive |grep filename.csv
This outputs the actual path where the file exists
2019-04-05 01:18:35 111111 folder1/2019/03/20/filename.csv
Read file content from S3 bucket with boto3
When you want to read a file with a different configuration than the default one, feel free to use either mpu.aws.s3_read(s3path)
directly or the copy-pasted code:
def s3_read(source, profile_name=None):
"""
Read a file from an S3 source.
Parameters
----------
source : str
Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar'
profile_name : str, optional
AWS profile
Returns
-------
content : bytes
botocore.exceptions.NoCredentialsError
Botocore is not able to find your credentials. Either specify
profile_name or add the environment variables AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN.
See https://boto3.readthedocs.io/en/latest/guide/configuration.html
"""
session = boto3.Session(profile_name=profile_name)
s3 = session.client('s3')
bucket_name, key = mpu.aws._s3_path_split(source)
s3_object = s3.get_object(Bucket=bucket_name, Key=key)
body = s3_object['Body']
return body.read()
Quick way to list all files in Amazon S3 bucket?
Be carefull, amazon list only returns 1000 files. If you want to iterate over all files you have to paginate the results using markers :
In ruby using aws-s3
bucket_name = 'yourBucket'
marker = ""
AWS::S3::Base.establish_connection!(
:access_key_id => 'your_access_key_id',
:secret_access_key => 'your_secret_access_key'
)
loop do
objects = Bucket.objects(bucket_name, :marker=>marker, :max_keys=>1000)
break if objects.size == 0
marker = objects.last.key
objects.each do |obj|
puts "#{obj.key}"
end
end
end
Hope this helps, vincent
FTP/SFTP access to an Amazon S3 Bucket
Update
S3 now offers a fully-managed SFTP Gateway Service for S3 that integrates with IAM and can be administered using aws-cli.
There are theoretical and practical reasons why this isn't a perfect solution, but it does work...
You can install an FTP/SFTP service (such as proftpd) on a linux server, either in EC2 or in your own data center... then mount a bucket into the filesystem where the ftp server is configured to chroot, using s3fs.
I have a client that serves content out of S3, and the content is provided to them by a 3rd party who only supports ftp pushes... so, with some hesitation (due to the impedance mismatch between S3 and an actual filesystem) but lacking the time to write a proper FTP/S3 gateway server software package (which I still intend to do one of these days), I proposed and deployed this solution for them several months ago and they have not reported any problems with the system.
As a bonus, since proftpd can chroot each user into their own home directory and "pretend" (as far as the user can tell) that files owned by the proftpd user are actually owned by the logged in user, this segregates each ftp user into a "subdirectory" of the bucket, and makes the other users' files inaccessible.
There is a problem with the default configuration, however.
Once you start to get a few tens or hundreds of files, the problem will manifest itself when you pull a directory listing, because ProFTPd will attempt to read the .ftpaccess
files over, and over, and over again, and for each file in the directory, .ftpaccess
is checked to see if the user should be allowed to view it.
You can disable this behavior in ProFTPd, but I would suggest that the most correct configuration is to configure additional options -o enable_noobj_cache -o stat_cache_expire=30
in s3fs:
-o stat_cache_expire
(default is no expire)
specify expire time(seconds) for entries in the stat cache
Without this option, you'll make fewer requests to S3, but you also will not always reliably discover changes made to objects if external processes or other instances of s3fs are also modifying the objects in the bucket. The value "30" in my system was selected somewhat arbitrarily.
-o enable_noobj_cache
(default is disable)
enable cache entries for the object which does not exist. s3fs always has to check whether file(or sub directory) exists under object(path) when s3fs does some command, since s3fs has recognized a directory which does not exist and has files or subdirectories under itself. It increases ListBucket request and makes performance bad. You can specify this option for performance, s3fs memorizes in stat cache that the object (file or directory) does not exist.
This option allows s3fs to remember that .ftpaccess
wasn't there.
Unrelated to the performance issues that can arise with ProFTPd, which are resolved by the above changes, you also need to enable -o enable_content_md5
in s3fs.
-o enable_content_md5
(default is disable)
verifying uploaded data without multipart by content-md5 header. Enable to send "Content-MD5" header when uploading a object without multipart posting. If this option is enabled, it has some influences on a performance of s3fs when uploading small object. Because s3fs always checks MD5 when uploading large object, this option does not affect on large object.
This is an option which never should have been an option -- it should always be enabled, because not doing this bypasses a critical integrity check for only a negligible performance benefit. When an object is uploaded to S3 with a Content-MD5:
header, S3 will validate the checksum and reject the object if it's corrupted in transit. However unlikely that might be, it seems short-sighted to disable this safety check.
Quotes are from the man page of s3fs. Grammatical errors are in the original text.
How to rename files and folder in Amazon S3?
Below is the code example to rename file on s3. My file was part-000* because of spark o/p file, then i copy it to another file name on same location and delete the part-000*:
import boto3
client = boto3.client('s3')
response = client.list_objects(
Bucket='lsph',
MaxKeys=10,
Prefix='03curated/DIM_DEMOGRAPHIC/',
Delimiter='/'
)
name = response["Contents"][0]["Key"]
copy_source = {'Bucket': 'lsph', 'Key': name}
client.copy_object(Bucket='lsph', CopySource=copy_source,
Key='03curated/DIM_DEMOGRAPHIC/'+'DIM_DEMOGRAPHIC.json')
client.delete_object(Bucket='lsph', Key=name)
How to get response from S3 getObject in Node.js?
Alternatively you could use minio-js client library get-object.js
var Minio = require('minio')
var s3Client = new Minio({
endPoint: 's3.amazonaws.com',
accessKey: 'YOUR-ACCESSKEYID',
secretKey: 'YOUR-SECRETACCESSKEY'
})
var size = 0
// Get a full object.
s3Client.getObject('my-bucketname', 'my-objectname', function(e, dataStream) {
if (e) {
return console.log(e)
}
dataStream.on('data', function(chunk) {
size += chunk.length
})
dataStream.on('end', function() {
console.log("End. Total size = " + size)
})
dataStream.on('error', function(e) {
console.log(e)
})
})
Disclaimer: I work for Minio Its open source, S3 compatible object storage written in golang with client libraries available in Java, Python, Js, golang.
S3 Static Website Hosting Route All Paths to Index.html
I ran into the same problem today but the solution of @Mark-Nutter was incomplete to remove the hashbang from my angularjs application.
In fact you have to go to Edit Permissions, click on Add more permissions and then add the right List on your bucket to everyone. With this configuration, AWS S3 will now, be able to return 404 error and then the redirection rule will properly catch the case.
Just like this :
And then you can go to Edit Redirection Rules and add this rule :
<RoutingRules>
<RoutingRule>
<Condition>
<HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
</Condition>
<Redirect>
<HostName>subdomain.domain.fr</HostName>
<ReplaceKeyPrefixWith>#!/</ReplaceKeyPrefixWith>
</Redirect>
</RoutingRule>
</RoutingRules>
Here you can replace the HostName subdomain.domain.fr with your domain and the KeyPrefix #!/ if you don't use the hashbang method for SEO purpose.
Of course, all of this will only work if you have already have setup html5mode in your angular application.
$locationProvider.html5Mode(true).hashPrefix('!');
AWS S3 CLI - Could not connect to the endpoint URL
You should specify the region in your CLI script, rather than rely on default region specified using aws configure (as the current most popular answer asserts). Another answer alluded to that, but the syntax is wrong if you're using CLI via AWS Tools for Powershell.
This example forces region to us-west-2 (Northern California), PowerShell syntax:
aws s3 ls --region us-west-2
Amazon S3 direct file upload from client browser - private key disclosure
To create a signature, I must use my secret key. But all things
happens on a client side, so, the secret key can be easily revealed
from page source (even if I obfuscate/encrypt my sources).
This is where you have misunderstood. The very reason digital signatures are used is so that you can verify something as correct without revealing your secret key. In this case the digital signature is used to prevent the user from modifying the policy you set for the form post.
Digital signatures such as the one here are used for security all around the web. If someone (NSA?) really were able to break them, they would have much bigger targets than your S3 bucket :)
Upload a file to Amazon S3 with NodeJS
Upload CSV/Excel
const fs = require('fs');
const AWS = require('aws-sdk');
const s3 = new AWS.S3({
accessKeyId: XXXXXXXXX,
secretAccessKey: XXXXXXXXX
});
const absoluteFilePath = "C:\\Project\\test.xlsx";
const uploadFile = () => {
fs.readFile(absoluteFilePath, (err, data) => {
if (err) throw err;
const params = {
Bucket: 'testBucket', // pass your bucket name
Key: 'folderName/key.xlsx', // file will be saved in <folderName> folder
Body: data
};
s3.upload(params, function (s3Err, data) {
if (s3Err) throw s3Err
console.log(`File uploaded successfully at ${data.Location}`);
debugger;
});
});
};
uploadFile();
Best way to move files between S3 buckets?
Actually as of recently I just use the copy+paste action in the AWS s3 interface. Just navigate to the files you want to copy, click on "Actions" -> "Copy" then navigate to the destination bucket and "Actions" -> "Paste"
It transfers the files pretty quick and it seems like a less convoluted solution that doesn't require any programming, or over the top solutions like that.
URL for public Amazon S3 bucket
The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.
Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.
If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/
is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/
or http://s3-external-1.amazonaws.com/bucket/
.¹
The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].
S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com
. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.
If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.
However... the two endpoints do not offer the same functionality.
Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.
Choose the correct type of endpoint (REST or web site) for your application:
http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff
¹ s3-external-1.amazonaws.com
has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com
. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2
had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1
so s3-external-2
appears to have no purpose except backwards-compatibility.
Security of REST authentication schemes
Remember that your suggestions makes it difficult for clients to communicate with the server. They need to understand your innovative solution and encrypt the data accordingly, this model is not so good for public API (unless you are amazon\yahoo\google..).
Anyways, if you must encrypt the body content I would suggest you to check out existing standards and solutions like:
XML encryption (W3C standard)
XML Security
How to upload a file to directory in S3 bucket using boto
from boto3.s3.transfer import S3Transfer
import boto3
#have all the variables populated which are required below
client = boto3.client('s3', aws_access_key_id=access_key,aws_secret_access_key=secret_key)
transfer = S3Transfer(client)
transfer.upload_file(filepath, bucket_name, folder_name+"/"+filename)
AWS EFS vs EBS vs S3 (differences & when to use?)
Fixing the comparison:
- S3 is a storage facility accessible any where
- EBS is a device you can mount onto EC2
- EFS is a file system you can mount onto several EC2 instances at the same time
At this point it's a little premature to compare EFS and EBS- the performance of EFS isn't known, nor is its reliability known.
Why would you use S3?
- You don't have a need for the files to be 'local' to one or more EC2 instances.
- (effectively) infinite capacity
- built-in web serving, authentication
Listing files in a specific "folder" of a AWS S3 bucket
As other have already said, everything in S3 is an object. To you, it may be files and folders. But to S3, they're just objects.
If you don't need objects which end with a '/' you can safely delete them e.g. via REST api or AWS Java SDK (I assume you have write access). You will not lose "nested files" (there no files, so you will not lose objects whose names are prefixed with the key you delete)
AmazonS3 amazonS3 = AmazonS3ClientBuilder.standard().withCredentials(new ProfileCredentialsProvider()).withRegion("region").build();
amazonS3.deleteObject(new DeleteObjectRequest("my-bucket", "users/<user-id>/contacts/<contact-id>/"));
Please note that I'm using ProfileCredentialsProvider
so that my requests are not anonymous. Otherwise, you will not be able to delete an object. I have my AWS keep key stored in ~/.aws/credentials file.
AccessDenied for ListObjects for S3 bucket when permissions are s3:*
I got the same error when using policy as below, although i have "s3:ListBucket" for s3:ListObjects operation.
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"s3:ListBucket",
"s3:GetObject",
"s3:GetObjectAcl"
],
"Resource": [
"arn:aws:s3:::<bucketname>/*",
"arn:aws:s3:::*-bucket/*"
],
"Effect": "Allow"
}
]
}
Then i fixed it by adding one line
"arn:aws:s3:::bucketname"
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"s3:ListBucket",
"s3:GetObject",
"s3:GetObjectAcl"
],
"Resource": [
"arn:aws:s3:::<bucketname>",
"arn:aws:s3:::<bucketname>/*",
"arn:aws:s3:::*-bucket/*"
],
"Effect": "Allow"
}
]
}
The AWS Access Key Id does not exist in our records
To those of you who run aws s3 ls
and getting this exception. Make sure You have permissions to all regions under the provided AWS Account. When running aws s3 ls
you try to pull all the s3 buckets under the AWS Account. therefore, in case you don't have permissions to all regions, you'll get this exception - An error occurred (InvalidAccessKeyId) when calling the ListBuckets operation: The AWS Access Key Id you provided does not exist in our records.
Follow Describing your Regions using the AWS CLI for more info.
Boto3 to download all files from a S3 Bucket
import boto3, os
s3 = boto3.client('s3')
def download_bucket(bucket):
paginator = s3.get_paginator('list_objects_v2')
pages = paginator.paginate(Bucket=bucket)
for page in pages:
if 'Contents' in page:
for obj in page['Contents']:
os.path.dirname(obj['Key']) and os.makedirs(os.path.dirname(obj['Key']), exist_ok=True)
try:
s3.download_file(bucket, obj['Key'], obj['Key'])
except NotADirectoryError:
pass
# Change bucket_name to name of bucket that you want to download
download_bucket(bucket_name)
This should work for all number of objects (also when there are more than 1000). Each paginator page can contain up to 1000 objects.Notice extra param in os.makedirs function - exist_ok=True which cause that it's not throwing error when path exist)
How to format a URL to get a file from Amazon S3?
Documentation here, and I'll use the Frankfurt region as an example.
There are 2 different URL styles:
But this url does not work:
The message is explicit: The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.
I may be talking about another problem because I'm not getting NoSuchKey
error but I suspect the error message has been made clearer over time.
Amazon S3 - HTTPS/SSL - Is it possible?
As previously stated, it's not directly possible, but you can set up Apache or nginx + SSL on a EC2 instance, CNAME your desired domain to that, and reverse-proxy to the (non-custom domain) S3 URLs.
How to check if a specified key exists in a given S3 bucket using Java
Using Object isting. Java function to check if specified key exist in AWS S3.
boolean isExist(String key)
{
ObjectListing objects = amazonS3.listObjects(new ListObjectsRequest().withBucketName(bucketName).withPrefix(key));
for (S3ObjectSummary objectSummary : objects.getObjectSummaries())
{
if (objectSummary.getKey().equals(key))
{
return true;
}
}
return false;
}
How to list all AWS S3 objects in a bucket using Java
This is direct from AWS documentation:
AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());
ListObjectsRequest listObjectsRequest = new ListObjectsRequest()
.withBucketName(bucketName)
.withPrefix("m");
ObjectListing objectListing;
do {
objectListing = s3client.listObjects(listObjectsRequest);
for (S3ObjectSummary objectSummary :
objectListing.getObjectSummaries()) {
System.out.println( " - " + objectSummary.getKey() + " " +
"(size = " + objectSummary.getSize() +
")");
}
listObjectsRequest.setMarker(objectListing.getNextMarker());
} while (objectListing.isTruncated());
How to specify credentials when connecting to boto3 S3?
You can get a client
with new session directly like below.
s3_client = boto3.client('s3',
aws_access_key_id=settings.AWS_SERVER_PUBLIC_KEY,
aws_secret_access_key=settings.AWS_SERVER_SECRET_KEY,
region_name=REGION_NAME
)
Setting up FTP on Amazon Cloud Server
It will not be ok until you add your user to the group www by the following commands:
sudo usermod -a -G www <USER>
This solves the permission problem.
Set the default path by adding this:
local_root=/var/www/html
Getting Access Denied when calling the PutObject operation with bucket-level permission
If you have set public access for bucket and if it is still not working, edit bucker policy and paste following:
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"s3:PutObject",
"s3:PutObjectAcl",
"s3:GetObject",
"s3:GetObjectAcl",
"s3:DeleteObject"
],
"Resource": [
"arn:aws:s3:::yourbucketnamehere",
"arn:aws:s3:::yourbucketnamehere/*"
],
"Effect": "Allow",
"Principal": "*"
}
]
}
Downloading folders from aws s3, cp or sync?
In case you need to use another profile, especially cross account. you need to add the profile in the config file
[profile profileName]
region = us-east-1
role_arn = arn:aws:iam::XXX:role/XXXX
source_profile = default
and then if you are accessing only a single file
aws s3 cp s3://crossAccountBucket/dir localdir --profile profileName
AWS S3: how do I see how much disk space is using
See https://serverfault.com/questions/84815/how-can-i-get-the-size-of-an-amazon-s3-bucket
Answered by Vic...
<?php
if (!class_exists('S3')) require_once 'S3.php';
// Instantiate the class
$s3 = new S3('accessKeyId', 'secretAccessKey');
S3::$useSSL = false;
// List your buckets:
echo "S3::listBuckets(): ";
echo '<pre>' . print_r($s3->listBuckets(), 1). '</pre>';
$totalSize = 0;
$objects = $s3->getBucket('name-of-your-bucket');
foreach ($objects as $name => $val) {
// If you want to get the size of a particular directory, you can do
// only that.
// if (strpos($name, 'directory/sub-directory') !== false)
$totalSize += $val['size'];
}
echo ($totalSize / 1024 / 1024 / 1024) . ' GB';
?>
Open S3 object as a string with Boto3
read
will return bytes. At least for Python 3, if you want to return a string, you have to decode using the right encoding:
import boto3
s3 = boto3.resource('s3')
obj = s3.Object(bucket, key)
obj.get()['Body'].read().decode('utf-8')
check if a key exists in a bucket in s3 using boto3
Not only client
but bucket
too:
import boto3
import botocore
bucket = boto3.resource('s3', region_name='eu-west-1').Bucket('my-bucket')
try:
bucket.Object('my-file').get()
except botocore.exceptions.ClientError as ex:
if ex.response['Error']['Code'] == 'NoSuchKey':
print('NoSuchKey')
Downloading an entire S3 bucket?
To add another GUI option, we use WinSCP's S3 functionality. It's very easy to connect, only requiring your access key and secret key in the UI. You can then browse and download whatever files you require from any accessible buckets, including recursive downloads of nested folders.
Since it can be a challenge to clear new software through security and WinSCP is fairly prevalent, it can be really beneficial to just use it rather than try to install a more specialized utility.
Read file from aws s3 bucket using node fs
With the new version of sdk, the accepted answer does not work - it does not wait for the object to be downloaded. The following code snippet will help with the new version:
// dependencies
const AWS = require('aws-sdk');
// get reference to S3 client
const s3 = new AWS.S3();
exports.handler = async (event, context, callback) => {
var bucket = "TestBucket"
var key = "TestKey"
try {
const params = {
Bucket: Bucket,
Key: Key
};
var theObject = await s3.getObject(params).promise();
} catch (error) {
console.log(error);
return;
}
}
Amazon S3 upload file and get URL
Similarly if you want link through s3Client you can use below.
System.out.println("filelink: " + s3Client.getUrl("your_bucket_name", "your_file_key"));
How can I get a value from a map?
The answer by Steve Jessop explains well, why you can't use std::map::operator[]
on a const std::map
. Gabe Rainbow's answer suggests a nice alternative. I'd just like to provide some example code on how to use map::at()
. So, here is an enhanced example of your function()
:
void function(const MAP &map, const std::string &findMe) {
try {
const std::string& value = map.at(findMe);
std::cout << "Value of key \"" << findMe.c_str() << "\": " << value.c_str() << std::endl;
// TODO: Handle the element found.
}
catch (const std::out_of_range&) {
std::cout << "Key \"" << findMe.c_str() << "\" not found" << std::endl;
// TODO: Deal with the missing element.
}
}
And here is an example main()
function:
int main() {
MAP valueMap;
valueMap["string"] = "abc";
function(valueMap, "string");
function(valueMap, "strong");
return 0;
}
Output:
Value of key "string": abc
Key "strong" not found
Code on Ideone
apache redirect from non www to www
If using the above solution of two <VirtualHost *:80>
blocks with different ServerName
s...
<VirtualHost *:80>
ServerName example.com
Redirect permanent / http://www.example.com/
</VirtualHost>
<VirtualHost *:80>
ServerName www.example.com
</VirtualHost>
... then you must set NameVirtualHost On
as well.
If you don't do this, Apache doesn't allow itself to use the different ServerName
s to distinguish the blocks, so you get this error message:
[warn] _default_ VirtualHost overlap on port 80, the first has precedence
...and either no redirection happens, or you have an infinite redirection loop, depending on which block you put first.
Jackson - How to process (deserialize) nested JSON?
Here is a rough but more declarative solution. I haven't been able to get it down to a single annotation, but this seems to work well. Also not sure about performance on large data sets.
Given this JSON:
{
"list": [
{
"wrapper": {
"name": "Jack"
}
},
{
"wrapper": {
"name": "Jane"
}
}
]
}
And these model objects:
public class RootObject {
@JsonProperty("list")
@JsonDeserialize(contentUsing = SkipWrapperObjectDeserializer.class)
@SkipWrapperObject("wrapper")
public InnerObject[] innerObjects;
}
and
public class InnerObject {
@JsonProperty("name")
public String name;
}
Where the Jackson voodoo is implemented like:
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface SkipWrapperObject {
String value();
}
and
public class SkipWrapperObjectDeserializer extends JsonDeserializer<Object> implements
ContextualDeserializer {
private Class<?> wrappedType;
private String wrapperKey;
public JsonDeserializer<?> createContextual(DeserializationContext ctxt,
BeanProperty property) throws JsonMappingException {
SkipWrapperObject skipWrapperObject = property
.getAnnotation(SkipWrapperObject.class);
wrapperKey = skipWrapperObject.value();
JavaType collectionType = property.getType();
JavaType collectedType = collectionType.containedType(0);
wrappedType = collectedType.getRawClass();
return this;
}
@Override
public Object deserialize(JsonParser parser, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
ObjectNode objectNode = mapper.readTree(parser);
JsonNode wrapped = objectNode.get(wrapperKey);
Object mapped = mapIntoObject(wrapped);
return mapped;
}
private Object mapIntoObject(JsonNode node) throws IOException,
JsonProcessingException {
JsonParser parser = node.traverse();
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(parser, wrappedType);
}
}
Hope this is useful to someone!
Rownum in postgresql
If you just want a number to come back try this.
create temp sequence temp_seq;
SELECT inline_v1.ROWNUM,inline_v1.c1
FROM
(
select nextval('temp_seq') as ROWNUM, c1
from sometable
)inline_v1;
You can add a order by to the inline_v1 SQL so your ROWNUM has some sequential meaning to your data.
select nextval('temp_seq') as ROWNUM, c1
from sometable
ORDER BY c1 desc;
Might not be the fastest, but it's an option if you really do need them.
Are there pointers in php?
Yes there is something similar to pointers in PHP but may not match with what exactly happens in c or c++.
Following is one of the example.
$a = "test";
$b = "a";
echo $a;
echo $b;
echo $$b;
//output
test
a
test
This illustrates similar concept of pointers in PHP.
Run PowerShell command from command prompt (no ps1 script)
This works from my Windows 10's cmd.exe prompt
powershell -ExecutionPolicy Bypass -Command "Import-Module C:\Users\william\ps1\TravelBook; Get-TravelBook Hawaii"
This example shows
- how to chain multiple commands
- how to import module with module path
- how to run a function defined in the module
- No need for those fancy "&".
What is the purpose of Order By 1 in SQL select statement?
An example here from a sample test WAMP server database:-
mysql> select * from user_privileges;
| GRANTEE | TABLE_CATALOG | PRIVILEGE_TYPE | IS_GRANTABLE |
+--------------------+---------------+-------------------------+--------------+
| 'root'@'localhost' | def | SELECT | YES |
| 'root'@'localhost' | def | INSERT | YES |
| 'root'@'localhost' | def | UPDATE | YES |
| 'root'@'localhost' | def | DELETE | YES |
| 'root'@'localhost' | def | CREATE | YES |
| 'root'@'localhost' | def | DROP | YES |
| 'root'@'localhost' | def | RELOAD | YES |
| 'root'@'localhost' | def | SHUTDOWN | YES |
| 'root'@'localhost' | def | PROCESS | YES |
| 'root'@'localhost' | def | FILE | YES |
| 'root'@'localhost' | def | REFERENCES | YES |
| 'root'@'localhost' | def | INDEX | YES |
| 'root'@'localhost' | def | ALTER | YES |
| 'root'@'localhost' | def | SHOW DATABASES | YES |
| 'root'@'localhost' | def | SUPER | YES |
| 'root'@'localhost' | def | CREATE TEMPORARY TABLES | YES |
| 'root'@'localhost' | def | LOCK TABLES | YES |
| 'root'@'localhost' | def | EXECUTE | YES |
| 'root'@'localhost' | def | REPLICATION SLAVE | YES |
| 'root'@'localhost' | def | REPLICATION CLIENT | YES |
| 'root'@'localhost' | def | CREATE VIEW | YES |
| 'root'@'localhost' | def | SHOW VIEW | YES |
| 'root'@'localhost' | def | CREATE ROUTINE | YES |
| 'root'@'localhost' | def | ALTER ROUTINE | YES |
| 'root'@'localhost' | def | CREATE USER | YES |
| 'root'@'localhost' | def | EVENT | YES |
| 'root'@'localhost' | def | TRIGGER | YES |
| 'root'@'localhost' | def | CREATE TABLESPACE | YES |
| 'root'@'127.0.0.1' | def | SELECT | YES |
| 'root'@'127.0.0.1' | def | INSERT | YES |
| 'root'@'127.0.0.1' | def | UPDATE | YES |
| 'root'@'127.0.0.1' | def | DELETE | YES |
| 'root'@'127.0.0.1' | def | CREATE | YES |
| 'root'@'127.0.0.1' | def | DROP | YES |
| 'root'@'127.0.0.1' | def | RELOAD | YES |
| 'root'@'127.0.0.1' | def | SHUTDOWN | YES |
| 'root'@'127.0.0.1' | def | PROCESS | YES |
| 'root'@'127.0.0.1' | def | FILE | YES |
| 'root'@'127.0.0.1' | def | REFERENCES | YES |
| 'root'@'127.0.0.1' | def | INDEX | YES |
| 'root'@'127.0.0.1' | def | ALTER | YES |
| 'root'@'127.0.0.1' | def | SHOW DATABASES | YES |
| 'root'@'127.0.0.1' | def | SUPER | YES |
| 'root'@'127.0.0.1' | def | CREATE TEMPORARY TABLES | YES |
| 'root'@'127.0.0.1' | def | LOCK TABLES | YES |
| 'root'@'127.0.0.1' | def | EXECUTE | YES |
| 'root'@'127.0.0.1' | def | REPLICATION SLAVE | YES |
| 'root'@'127.0.0.1' | def | REPLICATION CLIENT | YES |
| 'root'@'127.0.0.1' | def | CREATE VIEW | YES |
| 'root'@'127.0.0.1' | def | SHOW VIEW | YES |
| 'root'@'127.0.0.1' | def | CREATE ROUTINE | YES |
| 'root'@'127.0.0.1' | def | ALTER ROUTINE | YES |
| 'root'@'127.0.0.1' | def | CREATE USER | YES |
| 'root'@'127.0.0.1' | def | EVENT | YES |
| 'root'@'127.0.0.1' | def | TRIGGER | YES |
| 'root'@'127.0.0.1' | def | CREATE TABLESPACE | YES |
| 'root'@'::1' | def | SELECT | YES |
| 'root'@'::1' | def | INSERT | YES |
| 'root'@'::1' | def | UPDATE | YES |
| 'root'@'::1' | def | DELETE | YES |
| 'root'@'::1' | def | CREATE | YES |
| 'root'@'::1' | def | DROP | YES |
| 'root'@'::1' | def | RELOAD | YES |
| 'root'@'::1' | def | SHUTDOWN | YES |
| 'root'@'::1' | def | PROCESS | YES |
| 'root'@'::1' | def | FILE | YES |
| 'root'@'::1' | def | REFERENCES | YES |
| 'root'@'::1' | def | INDEX | YES |
| 'root'@'::1' | def | ALTER | YES |
| 'root'@'::1' | def | SHOW DATABASES | YES |
| 'root'@'::1' | def | SUPER | YES |
| 'root'@'::1' | def | CREATE TEMPORARY TABLES | YES |
| 'root'@'::1' | def | LOCK TABLES | YES |
| 'root'@'::1' | def | EXECUTE | YES |
| 'root'@'::1' | def | REPLICATION SLAVE | YES |
| 'root'@'::1' | def | REPLICATION CLIENT | YES |
| 'root'@'::1' | def | CREATE VIEW | YES |
| 'root'@'::1' | def | SHOW VIEW | YES |
| 'root'@'::1' | def | CREATE ROUTINE | YES |
| 'root'@'::1' | def | ALTER ROUTINE | YES |
| 'root'@'::1' | def | CREATE USER | YES |
| 'root'@'::1' | def | EVENT | YES |
| 'root'@'::1' | def | TRIGGER | YES |
| 'root'@'::1' | def | CREATE TABLESPACE | YES |
| ''@'localhost' | def | USAGE | NO |
+--------------------+---------------+-------------------------+--------------+
85 rows in set (0.00 sec)
And when it is given additional order by PRIVILEGE_TYPE
or can be given order by 3
. Notice the 3rd column (PRIVILEGE_TYPE
) getting sorted alphabetically.
mysql> select * from user_privileges order by PRIVILEGE_TYPE;
+--------------------+---------------+-------------------------+--------------+
| GRANTEE | TABLE_CATALOG | PRIVILEGE_TYPE | IS_GRANTABLE |
+--------------------+---------------+-------------------------+--------------+
| 'root'@'127.0.0.1' | def | ALTER | YES |
| 'root'@'::1' | def | ALTER | YES |
| 'root'@'localhost' | def | ALTER | YES |
| 'root'@'::1' | def | ALTER ROUTINE | YES |
| 'root'@'localhost' | def | ALTER ROUTINE | YES |
| 'root'@'127.0.0.1' | def | ALTER ROUTINE | YES |
| 'root'@'127.0.0.1' | def | CREATE | YES |
| 'root'@'::1' | def | CREATE | YES |
| 'root'@'localhost' | def | CREATE | YES |
| 'root'@'::1' | def | CREATE ROUTINE | YES |
| 'root'@'localhost' | def | CREATE ROUTINE | YES |
| 'root'@'127.0.0.1' | def | CREATE ROUTINE | YES |
| 'root'@'::1' | def | CREATE TABLESPACE | YES |
| 'root'@'localhost' | def | CREATE TABLESPACE | YES |
| 'root'@'127.0.0.1' | def | CREATE TABLESPACE | YES |
| 'root'@'::1' | def | CREATE TEMPORARY TABLES | YES |
| 'root'@'localhost' | def | CREATE TEMPORARY TABLES | YES |
| 'root'@'127.0.0.1' | def | CREATE TEMPORARY TABLES | YES |
| 'root'@'localhost' | def | CREATE USER | YES |
| 'root'@'127.0.0.1' | def | CREATE USER | YES |
| 'root'@'::1' | def | CREATE USER | YES |
| 'root'@'localhost' | def | CREATE VIEW | YES |
| 'root'@'127.0.0.1' | def | CREATE VIEW | YES |
| 'root'@'::1' | def | CREATE VIEW | YES |
| 'root'@'127.0.0.1' | def | DELETE | YES |
| 'root'@'::1' | def | DELETE | YES |
| 'root'@'localhost' | def | DELETE | YES |
| 'root'@'::1' | def | DROP | YES |
| 'root'@'localhost' | def | DROP | YES |
| 'root'@'127.0.0.1' | def | DROP | YES |
| 'root'@'127.0.0.1' | def | EVENT | YES |
| 'root'@'::1' | def | EVENT | YES |
| 'root'@'localhost' | def | EVENT | YES |
| 'root'@'127.0.0.1' | def | EXECUTE | YES |
| 'root'@'::1' | def | EXECUTE | YES |
| 'root'@'localhost' | def | EXECUTE | YES |
| 'root'@'127.0.0.1' | def | FILE | YES |
| 'root'@'::1' | def | FILE | YES |
| 'root'@'localhost' | def | FILE | YES |
| 'root'@'localhost' | def | INDEX | YES |
| 'root'@'127.0.0.1' | def | INDEX | YES |
| 'root'@'::1' | def | INDEX | YES |
| 'root'@'::1' | def | INSERT | YES |
| 'root'@'localhost' | def | INSERT | YES |
| 'root'@'127.0.0.1' | def | INSERT | YES |
| 'root'@'127.0.0.1' | def | LOCK TABLES | YES |
| 'root'@'::1' | def | LOCK TABLES | YES |
| 'root'@'localhost' | def | LOCK TABLES | YES |
| 'root'@'127.0.0.1' | def | PROCESS | YES |
| 'root'@'::1' | def | PROCESS | YES |
| 'root'@'localhost' | def | PROCESS | YES |
| 'root'@'::1' | def | REFERENCES | YES |
| 'root'@'localhost' | def | REFERENCES | YES |
| 'root'@'127.0.0.1' | def | REFERENCES | YES |
| 'root'@'::1' | def | RELOAD | YES |
| 'root'@'localhost' | def | RELOAD | YES |
| 'root'@'127.0.0.1' | def | RELOAD | YES |
| 'root'@'::1' | def | REPLICATION CLIENT | YES |
| 'root'@'localhost' | def | REPLICATION CLIENT | YES |
| 'root'@'127.0.0.1' | def | REPLICATION CLIENT | YES |
| 'root'@'::1' | def | REPLICATION SLAVE | YES |
| 'root'@'localhost' | def | REPLICATION SLAVE | YES |
| 'root'@'127.0.0.1' | def | REPLICATION SLAVE | YES |
| 'root'@'127.0.0.1' | def | SELECT | YES |
| 'root'@'::1' | def | SELECT | YES |
| 'root'@'localhost' | def | SELECT | YES |
| 'root'@'127.0.0.1' | def | SHOW DATABASES | YES |
| 'root'@'::1' | def | SHOW DATABASES | YES |
| 'root'@'localhost' | def | SHOW DATABASES | YES |
| 'root'@'127.0.0.1' | def | SHOW VIEW | YES |
| 'root'@'::1' | def | SHOW VIEW | YES |
| 'root'@'localhost' | def | SHOW VIEW | YES |
| 'root'@'localhost' | def | SHUTDOWN | YES |
| 'root'@'127.0.0.1' | def | SHUTDOWN | YES |
| 'root'@'::1' | def | SHUTDOWN | YES |
| 'root'@'::1' | def | SUPER | YES |
| 'root'@'localhost' | def | SUPER | YES |
| 'root'@'127.0.0.1' | def | SUPER | YES |
| 'root'@'127.0.0.1' | def | TRIGGER | YES |
| 'root'@'::1' | def | TRIGGER | YES |
| 'root'@'localhost' | def | TRIGGER | YES |
| 'root'@'::1' | def | UPDATE | YES |
| 'root'@'localhost' | def | UPDATE | YES |
| 'root'@'127.0.0.1' | def | UPDATE | YES |
| ''@'localhost' | def | USAGE | NO | +--------------------+---------------+-------------------------+--------------+
85 rows in set (0.00 sec)
DEFINITIVELY, a long answer and alot of scrolling.
Also I struggled hard to pass the output of the queries to a text file.
Here is how to do that without using the annoying into outfile
thing-
tee E:/sqllogfile.txt;
And when you are done, stop the logging-
tee off;
Hope it adds more clarity.
How do I filter query objects by date range in Django?
To make it more flexible, you can design a FilterBackend as below:
class AnalyticsFilterBackend(generic_filters.BaseFilterBackend):
def filter_queryset(self, request, queryset, view):
predicate = request.query_params # or request.data for POST
if predicate.get('from_date', None) is not None and predicate.get('to_date', None) is not None:
queryset = queryset.filter(your_date__range=(predicate['from_date'], predicate['to_date']))
if predicate.get('from_date', None) is not None and predicate.get('to_date', None) is None:
queryset = queryset.filter(your_date__gte=predicate['from_date'])
if predicate.get('to_date', None) is not None and predicate.get('from_date', None) is None:
queryset = queryset.filter(your_date__lte=predicate['to_date'])
return queryset
PHP, get file name without file extension
If the extension is not known, use this solution
pathinfo('D:/dir1/dir2/fname', PATHINFO_FILENAME); // return "fname"
pathinfo('D:/dir1/dir2/fname.php', PATHINFO_FILENAME); // return "fname"
pathinfo('D:/dir1/dir2/fname.jpg', PATHINFO_FILENAME); // return "fname"
pathinfo('D:/dir1/dir2/fname.jpg', PATHINFO_DIRNAME) . '/' . pathinfo('D:/dir1/dir2/fname.jpg', PATHINFO_FILENAME); // return "D:/dir1/dir2/fname"
PHP MAN function pathinfo
Angular 2 change event on every keypress
I've been using keyup on a number field, but today I noticed in chrome the input has up/down buttons to increase/decrease the value which aren't recognized by keyup.
My solution is to use keyup and change together:
(keyup)="unitsChanged[i] = true" (change)="unitsChanged[i] = true"
Initial tests indicate this works fine, will post back if any bugs found after further testing.
SQLite add Primary Key
I tried to add the primary key afterwards by changing the sqlite_master table directly.
This trick seems to work.
It is a hack solution of course.
In short: create a regular (unique) index on the table, then make the schema writable and change the name of the index to the form reserved by sqlite to identify a primary key index, (i.e. sqlite_autoindex_XXX_1, where XXX is the table name) and set the sql string to NULL. At last change the table definition itself.
One pittfal: sqlite does not see the index name change until the database is reopened. This seems like a bug, but not a severe one (even without reopening the database, you can still use it).
Suppose the table looks like:
CREATE TABLE tab1(i INTEGER, j INTEGER, t TEXT);
Then I did the following:
BEGIN;
CREATE INDEX pk_tab1 ON tab1(i,j);
pragma writable_schema=1;
UPDATE sqlite_master SET name='sqlite_autoindex_tab1_1',sql=null WHERE name='pk_tab1';
UPDATE sqlite_master SET sql='CREATE TABLE tab1(i integer,j integer,t text,primary key(i,j))' WHERE name='tab1';
COMMIT;
Some tests (in sqlite shell):
sqlite> explain query plan select * from tab1 order by i,j;
0|0|0|SCAN TABLE tab1 USING INDEX sqlite_autoindex_tab1_1
sqlite> drop index sqlite_autoindex_tab1_1;
Error: index associated with UNIQUE or PRIMARY KEY constraint cannot be dropped
How to completely remove Python from a Windows machine?
It's actually quite simple.
When you installed it, you must have done it using some .exe file (I am assuming). Just run that .exe again, and then there will be options to modify Python. Just select the "Complete Uninstall" option, and the EXE will completely wipe out python for you.
Also, you might have to checkbox the "Remove Python from PATH". By default it is selected, but you may as well check it to be sure :)
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
How to get a index value from foreach loop in jstl
You can use the varStatus
attribute like this:-
<c:forEach var="categoryName" items="${categoriesList}" varStatus="myIndex">
myIndex.index will give you the index. Here myIndex
is a LoopTagStatus object.
Hence, you can send that to your javascript method like this:-
<a onclick="getCategoryIndex(${myIndex.index})" href="#">${categoryName}</a>
Get selected value/text from Select on change
No need for an onchange function. You can grab the value in one line:
document.getElementById("select_id").options[document.getElementById("select_id").selectedIndex].value;
Or, split it up for better readability:
var select_id = document.getElementById("select_id");
select_id.options[select_id.selectedIndex].value;
java.lang.ClassNotFoundException: org.springframework.core.io.Resource
There is a version conflict between jar/dependency please check all version of spring is same.
if you use maven remove version of dependency and use Spring.io dependency.it handle version conflict. Add this in your pom
<dependency>
<groupId>io.spring.platform</groupId>
<artifactId>platform-bom</artifactId>
<version>2.0.1.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
How does Subquery in select statement work in oracle
In the Oracle RDBMS, it is possible to use a multi-row subquery in the select clause as long as the (sub-)output is encapsulated as a collection. In particular, a multi-row select clause subquery can output each of its rows as an xmlelement that is encapsulated in an xmlforest.
Numpy where function multiple conditions
The accepted answer explained the problem well enough. However, the more Numpythonic approach for applying multiple conditions is to use numpy logical functions. In this case, you can use np.logical_and
:
np.where(np.logical_and(np.greater_equal(dists,r),np.greater_equal(dists,r + dr)))
Bootstrap 3 navbar active li not changing background-color
In Bootstrap 3.3.x make sure you use the scrollspy JavaScript capability to track active elements. It's easy to include it in your HTML. Just do the following:
<body data-spy="scroll" data-target="Id or class of the element you want to track">
In most cases I usually track active elements on my navbar, so I do the following:
<body data-spy="scroll" data-target=".navbar-fixed-top" >
Now in your CSS you can target .navbar-fixed-top .active a
:
.navbar-fixed-top .active a {
// Put in some styling
}
This should work if you are tracking active li elements in your top fixed navigation bar.
Get safe area inset top and bottom heights
extension UIViewController {
var topbarHeight: CGFloat {
return
(view.window?.safeAreaInsets.top ?? 0) +
(view.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0.0) +
(self.navigationController?.navigationBar.frame.height ?? 0.0)
}
}
registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later
iOS 8 has changed notification registration in a non-backwards compatible way. While you need to support iOS 7 and 8 (and while apps built with the 8 SDK aren't accepted), you can check for the selectors you need and conditionally call them correctly for the running version.
Here's a category on UIApplication that will hide this logic behind a clean interface for you that will work in both Xcode 5 and Xcode 6.
Header:
//Call these from your application code for both iOS 7 and 8
//put this in the public header
@interface UIApplication (RemoteNotifications)
- (BOOL)pushNotificationsEnabled;
- (void)registerForPushNotifications;
@end
Implementation:
//these declarations are to quiet the compiler when using 7.x SDK
//put this interface in the implementation file of this category, so they are
//not visible to any other code.
@interface NSObject (IOS8)
- (BOOL)isRegisteredForRemoteNotifications;
- (void)registerForRemoteNotifications;
+ (id)settingsForTypes:(NSUInteger)types categories:(NSSet*)categories;
- (void)registerUserNotificationSettings:(id)settings;
@end
@implementation UIApplication (RemoteNotifications)
- (BOOL)pushNotificationsEnabled
{
if ([self respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
{
return [self isRegisteredForRemoteNotifications];
}
else
{
return ([self enabledRemoteNotificationTypes] & UIRemoteNotificationTypeAlert);
}
}
- (void)registerForPushNotifications
{
if ([self respondsToSelector:@selector(registerForRemoteNotifications)])
{
[self registerForRemoteNotifications];
Class uiUserNotificationSettings = NSClassFromString(@"UIUserNotificationSettings");
//If you want to add other capabilities than just banner alerts, you'll need to grab their declarations from the iOS 8 SDK and define them in the same way.
NSUInteger UIUserNotificationTypeAlert = 1 << 2;
id settings = [uiUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert categories:[NSSet set]];
[self registerUserNotificationSettings:settings];
}
else
{
[self registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert];
}
}
@end
Delete duplicate elements from an array
Try following from Removing duplicates from an Array(simple):
Array.prototype.removeDuplicates = function (){
var temp=new Array();
this.sort();
for(i=0;i<this.length;i++){
if(this[i]==this[i+1]) {continue}
temp[temp.length]=this[i];
}
return temp;
}
Edit:
This code doesn't need sort:
Array.prototype.removeDuplicates = function (){
var temp=new Array();
label:for(i=0;i<this.length;i++){
for(var j=0; j<temp.length;j++ ){//check duplicates
if(temp[j]==this[i])//skip if already present
continue label;
}
temp[temp.length] = this[i];
}
return temp;
}
(But not a tested code!)
pass parameter by link_to ruby on rails
Maybe try this:
<%= link_to "Add to cart",
:controller => "car",
:action => "add_to_cart",
:car => car.attributes %>
But I'd really like to see where the car object is getting setup for this page (i.e., the rest of the view).
Hide all elements with class using plain Javascript
There are many ways to hide all elements which has certain class in javascript one way is to using for loop but here i want to show you other ways to doing it.
1.forEach and querySelectorAll('.classname')
document.querySelectorAll('.classname').forEach(function(el) {
el.style.display = 'none';
});
2.for...of with getElementsByClassName
for (let element of document.getElementsByClassName("classname")){
element.style.display="none";
}
3.Array.protoype.forEach getElementsByClassName
Array.prototype.forEach.call(document.getElementsByClassName("classname"), function(el) {
// Do something amazing below
el.style.display = 'none';
});
4.[ ].forEach and getElementsByClassName
[].forEach.call(document.getElementsByClassName("classname"), function (el) {
el.style.display = 'none';
});
i have shown some of the possible ways, there are also more ways to do it, but from above list you can Pick whichever suits and easy for you.
Note: all above methods are supported in modern browsers but may be some of them will not work in old age browsers like internet explorer.
Paramiko's SSHClient with SFTP
If you have a SSHClient, you can also use open_sftp()
:
import paramiko
# lets say you have SSH client...
client = paramiko.SSHClient()
sftp = client.open_sftp()
# then you can use upload & download as shown above
...
Python list subtraction operation
This example subtracts two lists:
# List of pairs of points
list = []
list.append([(602, 336), (624, 365)])
list.append([(635, 336), (654, 365)])
list.append([(642, 342), (648, 358)])
list.append([(644, 344), (646, 356)])
list.append([(653, 337), (671, 365)])
list.append([(728, 13), (739, 32)])
list.append([(756, 59), (767, 79)])
itens_to_remove = []
itens_to_remove.append([(642, 342), (648, 358)])
itens_to_remove.append([(644, 344), (646, 356)])
print("Initial List Size: ", len(list))
for a in itens_to_remove:
for b in list:
if a == b :
list.remove(b)
print("Final List Size: ", len(list))
JOptionPane - input dialog box program
import java.util.SortedSet;
import java.util.TreeSet;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
public class Average {
public static void main(String [] args) {
String test1= JOptionPane.showInputDialog("Please input mark for test 1: ");
String test2= JOptionPane.showInputDialog("Please input mark for test 2: ");
String test3= JOptionPane.showInputDialog("Please input mark for test 3: ");
int int1 = Integer.parseInt(test1);
int int2 = Integer.parseInt(test2);
int int3 = Integer.parseInt(test3);
SortedSet<Integer> set = new TreeSet<>();
set.add(int1);
set.add(int2);
set.add(int3);
Integer [] intArray = set.toArray(new Integer[3]);
JFrame frame = new JFrame();
JOptionPane.showInternalMessageDialog(frame.getContentPane(), String.format("Result %f", (intArray[1] + intArray[2]) / 2.0));
}
}
rails bundle clean
If you are using Bundler 1.1 or later you can use bundle clean
, just as you imagined you could. This is redundant if you're using bundle install --path
(Bundler manages the location you specified with --path, so takes responsibility for removing outdated gems), but if you've used Bundler to install the gems as system gems then bundle clean --force
will delete any system gems not required by your Gemfile. Blindingly obvious caveat: don't do this if you have other apps that rely on system gems that aren't in your Gemfile!
Pat Shaughnessy has a good description of bundle clean
and other new additions in bundler 1.1.
std::enable_if to conditionally compile a member function
One way to solve this problem, specialization of member functions is to put the specialization into another class, then inherit from that class. You may have to change the order of inheritence to get access to all of the other underlying data but this technique does work.
template< class T, bool condition> struct FooImpl;
template<class T> struct FooImpl<T, true> {
T foo() { return 10; }
};
template<class T> struct FoolImpl<T,false> {
T foo() { return 5; }
};
template< class T >
class Y : public FooImpl<T, boost::is_integer<T> > // whatever your test is goes here.
{
public:
typedef FooImpl<T, boost::is_integer<T> > inherited;
// you will need to use "inherited::" if you want to name any of the
// members of those inherited classes.
};
The disadvantage of this technique is that if you need to test a lot of different things for different member functions you'll have to make a class for each one, and chain it in the inheritence tree. This is true for accessing common data members.
Ex:
template<class T, bool condition> class Goo;
// repeat pattern above.
template<class T, bool condition>
class Foo<T, true> : public Goo<T, boost::test<T> > {
public:
typedef Goo<T, boost::test<T> > inherited:
// etc. etc.
};
How do I calculate the date in JavaScript three months prior to today?
I like the simplicity of gilly3's answer, but users will probably be surprised that a month before March 31 is March 3. I chose to implement a version that sticks to the end of the month, so a month before March 28, 29, 30, and 31 will all be Feb 28 when it's not a leap year.
_x000D_
_x000D_
function addMonths(date, months) {_x000D_
var result = new Date(date),_x000D_
expectedMonth = ((date.getMonth() + months) % 12 + 12) % 12;_x000D_
result.setMonth(result.getMonth() + months);_x000D_
if (result.getMonth() !== expectedMonth) {_x000D_
result.setDate(0);_x000D_
}_x000D_
return result;_x000D_
}_x000D_
_x000D_
var dt2004_05_31 = new Date("2004-05-31 0:00"),_x000D_
dt2001_05_31 = new Date("2001-05-31 0:00"),_x000D_
dt2001_03_31 = new Date("2001-03-31 0:00"),_x000D_
dt2001_02_28 = new Date("2001-02-28 0:00"),_x000D_
result = addMonths(dt2001_05_31, -2);_x000D_
console.assert(dt2001_03_31.getTime() == result.getTime(), result.toDateString());_x000D_
_x000D_
result = addMonths(dt2001_05_31, -3);_x000D_
console.assert(dt2001_02_28.getTime() == result.getTime(), result.toDateString());_x000D_
_x000D_
result = addMonths(dt2001_05_31, 36);_x000D_
console.assert(dt2004_05_31.getTime() == result.getTime(), result.toDateString());_x000D_
_x000D_
result = addMonths(dt2004_05_31, -38);_x000D_
console.assert(dt2001_03_31.getTime() == result.getTime(), result.toDateString());_x000D_
_x000D_
console.log('Done.');
_x000D_
_x000D_
_x000D_
Use a JSON array with objects with javascript
Your question feels a little incomplete, but I think what you're looking for is a way of making your JSON accessible to your code:
if you have the JSON string as above then you'd just need to do this
var jsonObj = eval('[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]');
then you can access these vars with something like jsonObj[0].id etc
Let me know if that's not what you were getting at and I'll try to help.
M
Error Code: 1406. Data too long for column - MySQL
I got the same error while using the imagefield in Django.
post_picture = models.ImageField(upload_to='home2/khamulat/mydomain.com/static/assets/images/uploads/blog/%Y/%m/%d', height_field=None, default=None, width_field=None, max_length=None)
I just removed the excess code as shown above to post_picture = models.ImageField(upload_to='images/uploads/blog/%Y/%m/%d', height_field=None, default=None, width_field=None, max_length=None)
and the error was gone
Converting JSON to XML in Java
For json to xml use the following Jackson example:
final String str = "{\"name\":\"JSON\",\"integer\":1,\"double\":2.0,\"boolean\":true,\"nested\":{\"id\":42},\"array\":[1,2,3]}";
ObjectMapper jsonMapper = new ObjectMapper();
JsonNode node = jsonMapper.readValue(str, JsonNode.class);
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_1_1, true);
StringWriter w = new StringWriter();
xmlMapper.writeValue(w, node);
System.out.println(w.toString());
Prints:
<?xml version='1.1' encoding='UTF-8'?>
<ObjectNode>
<name>JSON</name>
<integer>1</integer>
<double>2.0</double>
<boolean>true</boolean>
<nested>
<id>42</id>
</nested>
<array>1</array>
<array>2</array>
<array>3</array>
</ObjectNode>
To convert it back (xml to json) take a look at this answer https://stackoverflow.com/a/62468955/1485527 .
Python string.replace regular expression
As a summary
import sys
import re
f = sys.argv[1]
find = sys.argv[2]
replace = sys.argv[3]
with open (f, "r") as myfile:
s=myfile.read()
ret = re.sub(find,replace, s) # <<< This is where the magic happens
print ret
CodeIgniter : Unable to load the requested file:
I was getting this error in PyroCMS.
You can improve the error message in the Loader.php file that is in the code of the library.
Open the Loader.php file and find any calls to show_error
. I replaced mine with the following:
show_error(sprintf("Unable to load the requested file: \"%s\" with instance title of \"%s\"", $_ci_file, $_ci_data['_ci_vars']['options']['instance_title']));
I was then able to see which file was causing the issues for me.
How to remove Left property when position: absolute?
left:auto;
This will default the left
back to the browser default.
So if you have your Markup/CSS as:
<div class="myClass"></div>
.myClass
{
position:absolute;
left:0;
}
When setting RTL, you could change to:
<div class="myClass rtl"></div>
.myClass
{
position:absolute;
left:0;
}
.myClass.rtl
{
left:auto;
right:0;
}
Gunicorn worker timeout error
I've got the same problem in Docker.
In Docker I keep trained LightGBM
model + Flask
serving requests. As HTTP server I used gunicorn 19.9.0
. When I run my code locally on my Mac laptop everything worked just perfect, but when I ran the app in Docker my POST JSON requests were freezing for some time, then gunicorn
worker had been failing with [CRITICAL] WORKER TIMEOUT
exception.
I tried tons of different approaches, but the only one solved my issue was adding worker_class=gthread
.
Here is my complete config:
import multiprocessing
workers = multiprocessing.cpu_count() * 2 + 1
accesslog = "-" # STDOUT
access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(q)s" "%(D)s"'
bind = "0.0.0.0:5000"
keepalive = 120
timeout = 120
worker_class = "gthread"
threads = 3
How to disable all div content
Another way, in jQuery, would be to get the inner height, inner width and positioning of the containing DIV, and simply overlay another DIV, transparent, over the top the same size. This will work on all elements inside that container, instead of only the inputs.
Remember though, with JS disabled, you'll still be able to use the DIVs inputs/content. The same goes with the above answers too.
Remove git mapping in Visual Studio 2015
It's so simple,
make sure that you are not connected to the project you want to delete
project is closed in the solution explorer
That'a all, if your retry now, the remove action will enabled
Linq to Entities join vs groupjoin
According to eduLINQ:
The best way to get to grips with what GroupJoin does is to think of
Join. There, the overall idea was that we looked through the "outer"
input sequence, found all the matching items from the "inner" sequence
(based on a key projection on each sequence) and then yielded pairs of
matching elements. GroupJoin is similar, except that instead of
yielding pairs of elements, it yields a single result for each "outer"
item based on that item and the sequence of matching "inner" items.
The only difference is in return statement:
Join:
var lookup = inner.ToLookup(innerKeySelector, comparer);
foreach (var outerElement in outer)
{
var key = outerKeySelector(outerElement);
foreach (var innerElement in lookup[key])
{
yield return resultSelector(outerElement, innerElement);
}
}
GroupJoin:
var lookup = inner.ToLookup(innerKeySelector, comparer);
foreach (var outerElement in outer)
{
var key = outerKeySelector(outerElement);
yield return resultSelector(outerElement, lookup[key]);
}
Read more here:
How do you share code between projects/solutions in Visual Studio?
You could include the same project in more than one solution, but you're guaranteed to run into problems sometime down the road (relative paths can become invalid when you move directories around for example)
After years of struggling with this, I finally came up with a workable solution, but it requires you to use Subversion for source control (which is not a bad thing)
At the directory level of your solution, add a svn:externals property pointing to the projects you want to include in your solution. Subversion will pull the project from the repository and store it in a subfolder of your solution file. Your solution file can simply use relative paths to refer to your project.
If I find some more time, I'll explain this in detail.
dbms_lob.getlength() vs. length() to find blob size in oracle
length
and dbms_lob.getlength
return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength
will return the number of bytes, which may differ from the number of characters in a multi-byte character set.
As the documentation doesn't specify what happens when you apply length
on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength
.
Android Studio: Unable to start the daemon process
Some ways of troubleshooting the Gradle daemon:
- If you have a problem with your build, try temporarily disabling the daemon (you can pass the command line switch
--no-daemon
).
- Occasionally, you may want to stop the daemons either via the --stop command line option or in a more forceful way.
- There is a daemon log file, which by default is located in the Gradle user home directory.
- You may want to start the daemon in --foreground mode to observe how the build is executed.
How can I create C header files
- Open your favorite text editor
- Create a new file named whatever.h
- Put your function prototypes in it
DONE.
Example whatever.h
#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int f(int a);
#endif
Note: include guards (preprocessor commands) added thanks to luke. They avoid including the same header file twice in the same compilation. Another possibility (also mentioned on the comments) is to add #pragma once
but it is not guaranteed to be supported on every compiler.
Example whatever.c
#include "whatever.h"
int f(int a) { return a + 1; }
And then you can include "whatever.h" into any other .c file, and link it with whatever.c's object file.
Like this:
sample.c
#include "whatever.h"
int main(int argc, char **argv)
{
printf("%d\n", f(2)); /* prints 3 */
return 0;
}
To compile it (if you use GCC):
$ gcc -c whatever.c -o whatever.o
$ gcc -c sample.c -o sample.o
To link the files to create an executable file:
$ gcc sample.o whatever.o -o sample
You can test sample:
$ ./sample
3
$
What's the difference between session.persist() and session.save() in Hibernate?
Actually, the difference between hibernate save() and persist() methods depends on generator class we are using.
If our generator class is assigned, then there is no difference between save() and persist() methods. Because generator ‘assigned’ means, as a programmer we need to give the primary key value to save in the database right [ Hope you know this generators concept ]
In case of other than assigned generator class, suppose if our generator class name is Increment means hibernate itself will assign the primary key id value into the database right [other than assigned generator, hibernate only used to take care the primary key id value remember], so in this case if we call save() or persist() method, then it will insert the record into the database normally.
But here, thing is, save() method can return that primary key id value which is generated by hibernate and we can see it by
long s = session.save(k);
In this same case, persist() will never give any value back to the client, return type void.
persist() also guarantees that it will not execute an INSERT statement if it is called outside of transaction boundaries.
whereas in save(), INSERT happens immediately, no matter if you are inside or outside of a transaction.
Release generating .pdb files, why?
Debug symbols (.pdb) and XML doc (.xml) files make up a large percentage of the total size and should not be part of the regular deployment package.
But it should be possible to access them in case they are needed.
One possible approach: at the end of the TFS build process, move them to a separate artifact.
How to store a large (10 digits) integer?
In addition to all the other answers I'd like to note that if you want to write that number as a literal in your Java code, you'll need to append a L
or l
to tell the compiler that it's a long
constant:
long l1 = 9999999999; // this won't compile
long l2 = 9999999999L; // this will work
Mongoose and multiple database in single node.js project
Pretty late but this might help someone. The current answers assumes you are using the same file for your connections and models.
In real life, there is a high chance that you are splitting your models into different files. You can use something like this in your main file:
mongoose.connect('mongodb://localhost/default');
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log('connected');
});
which is just how it is described in the docs. And then in your model files, do something like the following:
import mongoose, { Schema } from 'mongoose';
const userInfoSchema = new Schema({
createdAt: {
type: Date,
required: true,
default: new Date(),
},
// ...other fields
});
const myDB = mongoose.connection.useDb('myDB');
const UserInfo = myDB.model('userInfo', userInfoSchema);
export default UserInfo;
Where myDB is your database name.
What is the Python equivalent of Matlab's tic and toc functions?
I had the same question when I migrated to python from Matlab. With the help of this thread I was able to construct an exact analog of the Matlab tic()
and toc()
functions. Simply insert the following code at the top of your script.
import time
def TicTocGenerator():
# Generator that returns time differences
ti = 0 # initial time
tf = time.time() # final time
while True:
ti = tf
tf = time.time()
yield tf-ti # returns the time difference
TicToc = TicTocGenerator() # create an instance of the TicTocGen generator
# This will be the main function through which we define both tic() and toc()
def toc(tempBool=True):
# Prints the time difference yielded by generator instance TicToc
tempTimeInterval = next(TicToc)
if tempBool:
print( "Elapsed time: %f seconds.\n" %tempTimeInterval )
def tic():
# Records a time in TicToc, marks the beginning of a time interval
toc(False)
That's it! Now we are ready to fully use tic()
and toc()
just as in Matlab. For example
tic()
time.sleep(5)
toc() # returns "Elapsed time: 5.00 seconds."
Actually, this is more versatile than the built-in Matlab functions. Here, you could create another instance of the TicTocGenerator
to keep track of multiple operations, or just to time things differently. For instance, while timing a script, we can now time each piece of the script seperately, as well as the entire script. (I will provide a concrete example)
TicToc2 = TicTocGenerator() # create another instance of the TicTocGen generator
def toc2(tempBool=True):
# Prints the time difference yielded by generator instance TicToc2
tempTimeInterval = next(TicToc2)
if tempBool:
print( "Elapsed time 2: %f seconds.\n" %tempTimeInterval )
def tic2():
# Records a time in TicToc2, marks the beginning of a time interval
toc2(False)
Now you should be able to time two separate things: In the following example, we time the total script and parts of a script separately.
tic()
time.sleep(5)
tic2()
time.sleep(3)
toc2() # returns "Elapsed time 2: 5.00 seconds."
toc() # returns "Elapsed time: 8.00 seconds."
Actually, you do not even need to use tic()
each time. If you have a series of commands that you want to time, then you can write
tic()
time.sleep(1)
toc() # returns "Elapsed time: 1.00 seconds."
time.sleep(2)
toc() # returns "Elapsed time: 2.00 seconds."
time.sleep(3)
toc() # returns "Elapsed time: 3.00 seconds."
# and so on...
I hope that this is helpful.
How to use sed to replace only the first occurrence in a file?
If anyone came here to replace a character for the first occurrence in all lines (like myself), use this:
sed '/old/s/old/new/1' file
-bash-4.2$ cat file
123a456a789a
12a34a56
a12
-bash-4.2$ sed '/a/s/a/b/1' file
123b456a789a
12b34a56
b12
By changing 1 to 2 for example, you can replace all the second a's only instead.
Open a folder using Process.Start
Just for completeness, if all you want to do is to open a folder, use this:
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo() {
FileName = "C:\\teste\\",
UseShellExecute = true,
Verb = "open"
});
Ensure FileName ends with Path.DirectorySeparatorChar
to make it unambiguously point to a folder. (Thanks to @binki.)
This solution won't work for opening a folder and selecting an item, since there doesn't seem a verb for that.
Install / upgrade gradle on Mac OS X
Two Method
- using homebrew auto install:
- Steps:
- Pros and cons
- Pros: easy
- Cons: (probably) not latest version
- manually install (for latest version):
- Pros and cons
- Pros: use your expected any (or latest) version
- Cons: need self to do it
- Steps
- download latest version binary (gradle-6.0.1) from Gradle | Releases
- unzip it (
gradle-6.0.1-all.zip
) and added gradle path
into environment variable PATH
- normally is edit and add following config into your startup script(
~/.bashrc
or ~/.zshrc
etc.):
export GRADLE_HOME=/path_to_your_gradle/gradle-6.0.1
export PATH=$GRADLE_HOME/bin:$PATH
some other basic note
Q: How to make PATH
take effect immediately?
A: use source
:
source ~/.bashrc
it will make/execute your .bashrc
, so make PATH
become your expected latest values, which include your added gradle path.
Q: How to check PATH
is really take effect/working now?
A: use echo
to see your added path in indeed in your PATH
? ~ echo $PATH
xxx:/Users/crifan/dev/dev_tool/java/gradle/gradle-6.0.1/bin:xxx
you can see we added /Users/crifan/dev/dev_tool/java/gradle/gradle-6.0.1/bin
into your PATH
Q: How to verify gradle
is installed correctly on my Mac ?
A: use which
to make sure can find gradle
? ~ which gradle
/Users/crifan/dev/dev_tool/java/gradle/gradle-6.0.1/bin/gradle
AND to check and see gradle version
? ~ gradle --version
------------------------------------------------------------
Gradle 6.0.1
------------------------------------------------------------
Build time: 2019-11-18 20:25:01 UTC
Revision: fad121066a68c4701acd362daf4287a7c309a0f5
Kotlin: 1.3.50
Groovy: 2.5.8
Ant: Apache Ant(TM) version 1.10.7 compiled on September 1 2019
JVM: 1.8.0_112 (Oracle Corporation 25.112-b16)
OS: Mac OS X 10.14.6 x86_64
this means the (latest) gradle is correctly installed on your mac ^_^.
for more detail please refer my (Chinese) post ?????mac???maven
What are the RGB codes for the Conditional Formatting 'Styles' in Excel?
For anyone who stumbles across this in the future, this is how you do it:
xl.Range("A1:A1").Style := "Bad"
xl.Range("A1:A1").Style := "Good"
xl.Range("A1:A1").Style := "Neutral"
An easy way to check on things like this is to open excel and record a macro. In this case I recorded a macro where I just formatted the cell to "Bad". Once you've recorded the macro, just go in and edit it and it will essentially give you the code. It will require a little translation on your part, but here is what the macro looks like when I edit it:
Selection.Style = "Bad"
As you can see, it's pretty easy to make the jump to AHK from what excel provides.
Jquery check if element is visible in viewport
You can write a jQuery function like this to determine if an element is in the viewport.
Include this somewhere after jQuery is included:
$.fn.isInViewport = function() {
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
Sample usage:
$(window).on('resize scroll', function() {
if ($('#Something').isInViewport()) {
// do something
} else {
// do something else
}
});
Note that this only checks the top and bottom positions of elements, it doesn't check if an element is outside of the viewport horizontally.
How to vertical align an inline-block in a line of text?
display: inline-block
is your friend you just need all three parts of the construct - before, the "block", after - to be one, then you can vertically align them all to the middle:
(it looks like your picture anyway ;))
CSS:
p, div {
display: inline-block;
vertical-align: middle;
}
p, div {
display: inline !ie7; /* hack for IE7 and below */
}
table {
background: #000;
color: #fff;
font-size: 16px;
font-weight: bold; margin: 0 10px;
}
td {
padding: 5px;
text-align: center;
}
HTML:
<p>some text</p>
<div>
<table summary="">
<tr><td>A</td></tr>
<tr><td>B</td></tr>
<tr><td>C</td></tr>
<tr><td>D</td></tr>
</table>
</div>
<p>continues afterwards</p>
Test if registry value exists
The -not
test should fire if a property doesn't exist:
$prop = (Get-ItemProperty $regkey).$name
if (-not $prop)
{
New-ItemProperty -Path $regkey -Name $name -Value "X"
}
Json.net serialize/deserialize derived types?
You have to enable Type Name Handling and pass that to the (de)serializer as a settings parameter.
Base object1 = new Base() { Name = "Object1" };
Derived object2 = new Derived() { Something = "Some other thing" };
List<Base> inheritanceList = new List<Base>() { object1, object2 };
JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
string Serialized = JsonConvert.SerializeObject(inheritanceList, settings);
List<Base> deserializedList = JsonConvert.DeserializeObject<List<Base>>(Serialized, settings);
This will result in correct deserialization of derived classes. A drawback to it is that it will name all the objects you are using, as such it will name the list you are putting the objects in.
Pandas sum by groupby, but exclude certain columns
The agg
function will do this for you. Pass the columns and function as a dict with column, output:
df.groupby(['Country', 'Item_Code']).agg({'Y1961': np.sum, 'Y1962': [np.sum, np.mean]}) # Added example for two output columns from a single input column
This will display only the group by columns, and the specified aggregate columns. In this example I included two agg functions applied to 'Y1962'.
To get exactly what you hoped to see, included the other columns in the group by, and apply sums to the Y variables in the frame:
df.groupby(['Code', 'Country', 'Item_Code', 'Item', 'Ele_Code', 'Unit']).agg({'Y1961': np.sum, 'Y1962': np.sum, 'Y1963': np.sum})
mysql error 1364 Field doesn't have a default values
i set the fields to not null and problem solved, it updates when an information is commanded to store in it, no more showing msqli message that the field was empty cus you didnt insert value to it, well application of this solution can work on some projects depends on your project structure.
Converting a double to an int in C#
Because Convert.ToInt32
rounds:
Return Value: rounded to the nearest 32-bit signed integer. If value
is halfway between two whole numbers, the even number is returned;
that is, 4.5 is converted to 4, and 5.5 is converted to 6.
...while the cast truncates:
When you convert from a double or float value to an integral type, the
value is truncated.
Update: See Jeppe Stig Nielsen's comment below for additional differences (which however do not come into play if score
is a real number as is the case here).
Laravel - Model Class not found
For me it was really silly I had created a ModelClass file without the .php extension. So calling that was giving model not found. So check the extension has .php
Converting VS2012 Solution to VS2010
I had a similar problem and none of the solutions above worked, so I went with an old standby that always works:
- Rename the folder containing the project
- Make a brand new project with the same name with 2010
- Diff the two folders and->
- Copy all source files directly
- Ignore bin/debug/release etc
- Diff the .csproj and copy over all lines that are relevant.
- If the .sln file only has one project, ignore it. If it's complex, then diff it as well.
That almost always works if you've spent 10 minutes at it and can't get it.
Note that for similar problems with older versions (2008, 2005) you can usually get away with just changing the version in the .csproj and either changing the version in the .sln or discarding it, but this doesn't seem to work for 2013.
Background thread with QThread in PyQt
Take this answer updated for PyQt5, python 3.4
Use this as a pattern to start a worker that does not take data and return data as they are available to the form.
1 - Worker class is made smaller and put in its own file worker.py for easy memorization and independent software reuse.
2 - The main.py file is the file that defines the GUI Form class
3 - The thread object is not subclassed.
4 - Both thread object and the worker object belong to the Form object
5 - Steps of the procedure are within the comments.
# worker.py
from PyQt5.QtCore import QThread, QObject, pyqtSignal, pyqtSlot
import time
class Worker(QObject):
finished = pyqtSignal()
intReady = pyqtSignal(int)
@pyqtSlot()
def procCounter(self): # A slot takes no params
for i in range(1, 100):
time.sleep(1)
self.intReady.emit(i)
self.finished.emit()
And the main file is:
# main.py
from PyQt5.QtCore import QThread
from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QGridLayout
import sys
import worker
class Form(QWidget):
def __init__(self):
super().__init__()
self.label = QLabel("0")
# 1 - create Worker and Thread inside the Form
self.obj = worker.Worker() # no parent!
self.thread = QThread() # no parent!
# 2 - Connect Worker`s Signals to Form method slots to post data.
self.obj.intReady.connect(self.onIntReady)
# 3 - Move the Worker object to the Thread object
self.obj.moveToThread(self.thread)
# 4 - Connect Worker Signals to the Thread slots
self.obj.finished.connect(self.thread.quit)
# 5 - Connect Thread started signal to Worker operational slot method
self.thread.started.connect(self.obj.procCounter)
# * - Thread finished signal will close the app if you want!
#self.thread.finished.connect(app.exit)
# 6 - Start the thread
self.thread.start()
# 7 - Start the form
self.initUI()
def initUI(self):
grid = QGridLayout()
self.setLayout(grid)
grid.addWidget(self.label,0,0)
self.move(300, 150)
self.setWindowTitle('thread test')
self.show()
def onIntReady(self, i):
self.label.setText("{}".format(i))
#print(i)
app = QApplication(sys.argv)
form = Form()
sys.exit(app.exec_())
Using psql to connect to PostgreSQL in SSL mode
Well, you cloud provide all the information with following command in CLI, if connection requires in SSL mode:
psql "sslmode=verify-ca sslrootcert=server-ca.pem sslcert=client-cert.pem sslkey=client-key.pem hostaddr=your_host port=5432 user=your_user dbname=your_db"
How to add spacing between columns?
According to Bootstrap 4 documentation you should give the parent a negative margin mx-n*
, and the children a positive padding px-*
_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="row mx-n5">_x000D_
<div class="col px-5">_x000D_
<div class="p-3 border bg-light">Custom column padding</div>_x000D_
</div>_x000D_
<div class="col px-5">_x000D_
<div class="p-3 border bg-light">Custom column padding</div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
How to create the pom.xml for a Java project with Eclipse
To create pom.xml file follow the next steps:
- Right click on the current project
- Select Configure option
- Select Convert to Maven Project
- Complete all fields in Create new POM window
- Check "Delete original references from project"
- Click on Finish button
If eclipse show the the error "Maven error “Failure to transfer…", follow the next steps
Copy the dependency to pom.
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-archiver</artifactId>
<version>2.5</version>
</dependency>
Click right on your project
- Select Maven
- Select Update project
- Select Force Update of Snapshots/Releases
Importing packages in Java
For the second class file, add "package Dan;" like the first one, so as to make sure they are in the same package; modify "import Dan.Vik.disp;" to be "import Dan.Vik;"
SQL Server, division returns zero
if you declare it as float or any decimal format it will display
0
only
E.g :
declare @weight float;
SET @weight= 47 / 638; PRINT @weight
Output : 0
If you want the output as
0.073667712
E.g
declare @weight float;
SET @weight= 47.000000000 / 638.000000000; PRINT @weight
Difference between document.addEventListener and window.addEventListener?
The window
binding refers to a built-in object provided by the browser. It represents the browser window that contains the document
. Calling its addEventListener
method registers the second argument (callback function) to be called whenever the event described by its first argument occurs.
<p>Some paragraph.</p>
<script>
window.addEventListener("click", () => {
console.log("Test");
});
</script>
Following points should be noted before select window or document to addEventListners
- Most of the events are same for
window
or document
but
some events like resize
, and other events related to loading
,
unloading
, and opening/closing
should all be set on the window.
- Since window has the document it is good practice to use document to
handle (if it can handle) since event will hit document first.
- Internet Explorer doesn't respond to many events registered on the
window,so you will need to use document for registering event.
PHP max_input_vars
You need to uncomment max_input_vars value in php.ini file and increase it (exp. 2000), also dont forget to restart your server this will help for 99,99%.
Find maximum value of a column and return the corresponding row values using Pandas
Assuming df
has a unique index, this gives the row with the maximum value:
In [34]: df.loc[df['Value'].idxmax()]
Out[34]:
Country US
Place Kansas
Value 894
Name: 7
Note that idxmax
returns index labels. So if the DataFrame has duplicates in the index, the label may not uniquely identify the row, so df.loc
may return more than one row.
Therefore, if df
does not have a unique index, you must make the index unique before proceeding as above. Depending on the DataFrame, sometimes you can use stack
or set_index
to make the index unique. Or, you can simply reset the index (so the rows become renumbered, starting at 0):
df = df.reset_index()
"No X11 DISPLAY variable" - what does it mean?
I have had the same issue in Ubuntu 14.04.01 when I tried to install JDK 8 and Netbeans if I launch the script inside a Byobu terminal (maybe with Screens happens the same).
Just exit Byobu and (in a graphical terminal) run the script.
How do I add 1 day to an NSDate?
In swift 4 or swift 5, you can use like bellow:
let date = Date()
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: date)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let yesterday_date = dateFormatter.string(from: yesterday!)
print("yesterday->",yesterday_date)
output:
Current date: 2020-03-02
yesterday date: 2020-03-01
Select all where [first letter starts with B]
This will work for MYSQL
SELECT Name FROM Employees WHERE Name REGEXP '^[B].*$'
In this REGEXP stands for regular expression
and
this is for T-SQL
SELECT Name FROM Employees WHERE Name LIKE '[B]%'
Difference between private, public, and protected inheritance
Summary:
- Private: no one can see it except for within the class
- Protected: Private + derived classes can see it
- Public: the world can see it
When inheriting, you can (in some languages) change the protection type of a data member in certain direction, e.g. from protected to public.
How to list containers in Docker
To show only running containers use the given command:
docker ps
To show all containers use the given command:
docker ps -a
To show the latest created container (includes all states) use the given command:
docker ps -l
To show n last created containers (includes all states) use the given command:
docker ps -n=-1
To display total file sizes use the given command:
docker ps -s
The content presented above is from docker.com.
In the new version of Docker, commands are updated, and some management commands are added:
docker container ls
It is used to list all the running containers.
docker container ls -a
And then, if you want to clean them all,
docker rm $(docker ps -aq)
It is used to list all the containers created irrespective of its state.
And to stop all the Docker containers (force)
docker rm -f $(docker ps -a -q)
Here the container is the management command.
What is ToString("N0") format?
It is a sort of format specifier for formatting numeric results. There are additional specifiers on the link.
What N
does is that it separates numbers into thousand decimal places according to your CultureInfo and represents only 2 decimal digits in floating part as is N2
by rounding right-most digit if necessary.
N0
does not represent any decimal place but rounding is applied to it.
Let's exemplify.
using System;
using System.Globalization;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
double x = 567892.98789;
CultureInfo someCulture = new CultureInfo("da-DK", false);
// 10 means left-padded = right-alignment
Console.WriteLine(String.Format(someCulture, "{0:N} denmark", x));
Console.WriteLine("{0,10:N} us", x);
// watch out rounding 567,893
Console.WriteLine(String.Format(someCulture, "{0,10:N0}", x));
Console.WriteLine("{0,10:N0}", x);
Console.WriteLine(String.Format(someCulture, "{0,10:N5}", x));
Console.WriteLine("{0,10:N5}", x);
Console.ReadKey();
}
}
}
It yields,
567.892,99 denmark
567,892.99 us
567.893
567,893
567.892,98789
567,892.98789
MySQL root password change
On MySQL 8.0.4+
To update current root user:
select current_user();
set password = 'new_password';
To update other user:
set password for 'otherUser'@'localhost' = 'new_password';
To set password policy before updating password:
set global validate_password.policy = 0;
set password = 'new_password';
set password for 'otherUser'@'localhost' = 'new_password';
Other / better way to update root password:
mysql_secure_installation
Want to stick with 5.x authentication so you can still use legacy apps?
On my.cnf
default_authentication_plugin = mysql_native_password
To update root:
set global validate_password.policy = 0;
alter user 'root'@'localhost' identified with mysql_native_password by 'new_password';
How to pass the values from one jsp page to another jsp without submit button?
Note: Give accurate path details for Form1.jsp in Test.jsp
1. Test.jsp and 2.Form1.jsp
Test.jsp
<body>
<form method ="get" onsubmit="Form1.jsp">
<input type="text" name="uname">
<input type="submit" value="go" ><br/>
</form>
</body>
Form1.jsp
</head>
<body>
<% String name=request.getParameter("uname"); out.print("welcome "+name); %>
</body>
How to check internet access on Android? InetAddress never times out
This my workaround to solve this problem and check the valid internet connection because as they said that Network info class cannot give you the expected result and it may return true when network connected but no internet.
So this my COMPLETE WORKAROUND based on @Levite Answer:
First you must have AsynckTask for checking Network availability and this is mine:
public class Connectivity {
private static final String TAG = "Connectivity";
private static boolean hasConnected = false, hasChecked = false;
private InternetListener internetListener;
private Activity activity;
public Connectivity(InternetListener internetListener, Activity activity) {
this.internetListener = internetListener;
this.activity = activity;
}
public void startInternetListener() {
CheckURL checkURL = new CheckURL(activity);
checkURL.execute();
long startTime = System.currentTimeMillis();
while (true) {
if (hasChecked && hasConnected) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
internetListener.onConnected();
}
});
checkURL.cancel(true);
return;
}
// check if time
if (System.currentTimeMillis() - startTime >= 1000) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
internetListener.onDisconnected();
}
});
checkURL.cancel(true);
return;
}
}
//return hasConnected;
}
class CheckURL extends AsyncTask<Void, Void, Boolean> {
private Activity activity;
public CheckURL(Activity activity) {
this.activity = activity;
}
@Override
protected Boolean doInBackground(Void... params) {
if (!isNetWorkAvailable(activity)) {
Log.i(TAG, "Internet not available!");
return false;
}
int timeoutMs = 3000;
try {
Socket sock = new Socket();
SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);
sock.connect(sockaddr, timeoutMs);
sock.close();
Log.i(TAG, "Internet available :)");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
@Override
protected void onPostExecute(Boolean result) {
hasChecked = true;
hasConnected = result;
super.onPostExecute(result);}}
private static final String TAG = "Connectivity";
private static boolean isNetWorkAvailable(Activity activity) {
ConnectivityManager connectivityManager =
(ConnectivityManager)
activity.getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo =
null;
if (connectivityManager != null) {
networkInfo =
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
}
boolean isConnected;
boolean isWifiAvailable = false;
if (networkInfo != null) {
isWifiAvailable = networkInfo.isAvailable();
}
boolean isWifiConnected = false;
if (networkInfo != null) {
isWifiConnected = networkInfo.isConnected();
}
if (connectivityManager != null) {
networkInfo =
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
}
boolean isMobileAvailable = false;
if (networkInfo != null) {
isMobileAvailable = networkInfo.isAvailable();
}
boolean isMobileConnected = false;
if (networkInfo != null) {
isMobileConnected = networkInfo.isConnected();
}
isConnected = (isMobileAvailable && isMobileConnected) ||
(isWifiAvailable && isWifiConnected);
return (isConnected);}
}}
private static boolean isNetWorkAvailable(Context context) {
ConnectivityManager connectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo =
null;
if (connectivityManager != null) {
networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
}
boolean isConnected;
boolean isWifiAvailable = false;
if (networkInfo != null) {
isWifiAvailable = networkInfo.isAvailable();
}
boolean isWifiConnected = false;
if (networkInfo != null) {
isWifiConnected = networkInfo.isConnected();
}
if (connectivityManager != null) {
networkInfo =
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
}
boolean isMobileAvailable = false;
if (networkInfo != null) {
isMobileAvailable = networkInfo.isAvailable();
}
boolean isMobileConnected = false;
if (networkInfo != null) {
isMobileConnected = networkInfo.isConnected();
}
isConnected = (isMobileAvailable && isMobileConnected) ||
(isWifiAvailable && isWifiConnected);
return (isConnected);
}
}
After that you should create another thread to start AscnkTask And listen for result with the InternetListener.
public interface InternetListener {
void onConnected();
void onDisconnected();
}
And the Thread that is waiting for AsynckTask result you can put it in Utility class:
private static Thread thread;
public static void startNetworkListener(Context context, InternetListener
internetListener) {
if (thread == null){
thread = new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
new Connectivity(internetListener,context).startInternetListener();
}
});
}
thread.start();
}
Finally call the startNetworkListener() method and listen for result.
example in activity from My Utils.java class :
Utils.startNetworkListener(this, new InternetListener() {
@Override
public void onConnected() {
// do your work when internet available.
}
@Override
public void onDisconnected() {
// do your work when no internet available.
}
});
Happy Coding :).
Using Mockito to mock classes with generic parameters
One other way around this is to use @Mock
annotation instead.
Doesn't work in all cases, but looks much sexier :)
Here's an example:
@RunWith(MockitoJUnitRunner.class)
public class FooTests {
@Mock
public Foo<Bar> fooMock;
@Test
public void testFoo() {
when(fooMock.getValue()).thenReturn(new Bar());
}
}
The MockitoJUnitRunner
initializes the fields annotated with @Mock
.
How to Sort Multi-dimensional Array by Value?
I usually use usort, and pass my own comparison function. In this case, it is very simple:
function compareOrder($a, $b)
{
return $a['order'] - $b['order'];
}
usort($array, 'compareOrder');
In PHP 7 using spaceship operator:
usort($array, function($a, $b) {
return $a['order'] <=> $b['order'];
});
How to get DataGridView cell value in messagebox?
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
{
MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
}
}
Definitive way to trigger keypress events with jQuery
Ok, for me that work with this...
var e2key = function(e) {
if (!e) return '';
var event2key = {
'96':'0', '97':'1', '98':'2', '99':'3', '100':'4', '101':'5', '102':'6', '103':'7', '104':'8', '105':'9', // Chiffres clavier num
'48':'m0', '49':'m1', '50':'m2', '51':'m3', '52':'m4', '53':'m5', '54':'m6', '55':'m7', '56':'m8', '57':'m9', // Chiffres caracteres speciaux
'65':'a', '66':'b', '67':'c', '68':'d', '69':'e', '70':'f', '71':'g', '72':'h', '73':'i', '74':'j', '75':'k', '76':'l', '77':'m', '78':'n', '79':'o', '80':'p', '81':'q', '82':'r', '83':'s', '84':'t', '85':'u', '86':'v', '87':'w', '88':'x', '89':'y', '90':'z', // Alphabet
'37':'left', '39':'right', '38':'up', '40':'down', '13':'enter', '27':'esc', '32':'space', '107':'+', '109':'-', '33':'pageUp', '34':'pageDown' // KEYCODES
};
return event2key[(e.which || e.keyCode)];
};
var page5Key = function(e, customKey) {
if (e) e.preventDefault();
switch(e2key(customKey || e)) {
case 'left': /*...*/ break;
case 'right': /*...*/ break;
}
};
$(document).bind('keyup', page5Key);
$(document).trigger('keyup', [{preventDefault:function(){},keyCode:37}]);
Close dialog on click (anywhere)
If you'd like to do it for all dialogs throughout the site try the following code...
$.extend( $.ui.dialog.prototype.options, {
open: function() {
var dialog = this;
$('.ui-widget-overlay').bind('click', function() {
$(dialog).dialog('close');
});
}
});
IntelliJ: Never use wildcard imports
It's obvious why you'd want to disable this: To force IntelliJ to include each and every import individually. It makes it easier for people to figure out exactly where classes you're using come from.
Click on the Settings "wrench" icon on the toolbar, open "Imports" under "Code Style", and check the "Use single class import" selection. You can also completely remove entries under "Packages to use import with *
", or specify a threshold value that only uses the "*
" when the individual classes from a package exceeds that threshold.
Update: in IDEA 13 "Use single class import" does not prevent wildcard imports. The solution is to go to Preferences
(? + , on macOS / Ctrl + Alt + S on Windows and Linux) > Editor > Code Style > Java > Imports tab
set Class count to use import with '*'
and Names count to use static import with '*'
to a higher value. Any value over 99 seems to work fine.
Setting equal heights for div's with jQuery
You can write the function this way also Which helps to build your code one time
just to add class name or ID at the end
function equalHeight(group) {
tallest = 0;
group.each(function() {
thisHeight = jQuery(this).height();
if(thisHeight > tallest) {
tallest = thisHeight;
}
});
group.height(tallest);
}
equalHeight(jQuery("Add your class"));
Windows error 2 occured while loading the Java VM
I got the same problem after upgrading java from 1.8.0_202 to 1.8.0_211
Problem:
Here are directories where new version of 1.8.0_211 of Java installed:
Directory of c:\Program Files\Java\jre1.8.0_211\bin
Directory of c:\Program Files (x86)\Common Files\Oracle\Java\javapath
So one is located in 32 bit and second is in 64 bit Program files folder. The one that is specified in the PATH is 32 bit version (c:\Program Files (x86)\Common Files\Oracle\Java\javapath), even though it was 64 bit version of the Java that was installed.
Solution:
Change system environments variable PATH from c:\Program Files
(x86)\Common Files\Oracle\Java\javapath to c:\Program
Files\Java\jre1.8.0_211\bin
How to install Python package from GitHub?
To install Python package from github, you need to clone that repository.
git clone https://github.com/jkbr/httpie.git
Then just run the setup.py file from that directory,
sudo python setup.py install
Python name 'os' is not defined
Just add:
import os
in the beginning, before:
from settings import PROJECT_ROOT
This will import the python's module os, which apparently is used later in the code of your module without being imported.
Using Spring 3 autowire in a standalone Java application
I case you are running SpringBoot:
I just had the same problem, that I could not Autowire one of my services from the static main method.
See below an approach in case you are relying on SpringApplication.run:
@SpringBootApplication
public class PricingOnlineApplication {
@Autowired
OrchestratorService orchestratorService;
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(PricingOnlineApplication.class, args);
PricingOnlineApplication application = context.getBean(PricingOnlineApplication.class);
application.start();
}
private void start() {
orchestratorService.performPricingRequest(null);
}
}
I noticed that SpringApplication.run returns a context which can be used similar to the above described approaches. From there, it is exactly the same as above ;-)
Get value of a merged cell of an excel from its cell address in vba
Even if it is really discouraged to use merge cells in Excel (use Center Across Selection
for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).
Hence, you can get the value of merged cells in range B4:B11
in several ways:
Range("B4").Value
Range("B4:B11").Cells(1).Value
Range("B4:B11").Cells(1,1).Value
You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty
.
Also note that Range("B4:B11").Value
won't work (raises an execution error number 13 if you try to Debug.Print
it) because it returns an array.
PersistenceContext EntityManager injection NullPointerException
An entity manager can only be injected in classes running inside a transaction. In other words, it can only be injected in a EJB. Other classe must use an EntityManagerFactory to create and destroy an EntityManager.
Since your TestService is not an EJB, the annotation @PersistenceContext is simply ignored. Not only that, in JavaEE 5, it's not possible to inject an EntityManager nor an EntityManagerFactory in a JAX-RS Service. You have to go with a JavaEE 6 server (JBoss 6, Glassfish 3, etc).
Here's an example of injecting an EntityManagerFactory:
package com.test.service;
import java.util.*;
import javax.persistence.*;
import javax.ws.rs.*;
@Path("/service")
public class TestService {
@PersistenceUnit(unitName = "test")
private EntityManagerFactory entityManagerFactory;
@GET
@Path("/get")
@Produces("application/json")
public List get() {
EntityManager entityManager = entityManagerFactory.createEntityManager();
try {
return entityManager.createQuery("from TestEntity").getResultList();
} finally {
entityManager.close();
}
}
}
The easiest way to go here is to declare your service as a EJB 3.1, assuming you're using a JavaEE 6 server.
Related question:
Inject an EJB into JAX-RS (RESTful service)
Set a thin border using .css() in javascript
I'd recommend using a class instead of setting css properties. So instead of this:
$(this).css({"border-color": "#C1E0FF",
"border-width":"1px",
"border-style":"solid"});
Define a css class:
.border
{
border-color: #C1E0FF;
border-width:1px;
border-style:solid;
}
And then change your javascript to:
$(this).addClass("border");
How add class='active' to html menu with php
<ul>
<li><a <?php echo ($page == "yourfilename") ? "class='active'" : ""; ?> href="user.php" ><span>Article</span></a></li>
<li><a <?php echo ($page == "yourfilename") ? "class='active'" : ""; ?> href="newarticle.php"><span>New Articles</span></a></li>
</ul>
List files committed for a revision
To just get the list of the changed files with the paths, use
svn diff --summarize -r<rev-of-commit>:<rev-of-commit - 1>
For example:
svn diff --summarize -r42:41
should result in something like
M path/to/modifiedfile
A path/to/newfile
CardView Corner Radius
An easy way to achieve this would be:
1.Make a custom background resource (like a rectangle shape) with rounded corners.
2.set this custom background using the command -
cardView = view.findViewById(R.id.card_view2);
cardView.setBackgroundResource(R.drawable.card_view_bg);
this worked for me.
The XML
layout I made with top left and bottom right radius.
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/white" />
<corners android:topLeftRadius="18dp" android:bottomRightRadius="18dp" />
</shape>
In your case, you need to change only topLeftRadius as well as topRightRadius.
If you have a layout that overlaps with the corners of the card view and has a different color maybe, then you might need a different background resource file for the layout and in the xml set this background resource to your layout.
I tried and tested the above method. Hope this helps you.
How do I parse JSON from a Java HTTPResponse?
Instead of doing
Reader in = new BufferedReader(
new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder= new StringBuilder();
char[] buf = new char[1000];
int l = 0;
while (l >= 0) {
builder.append(buf, 0, l);
l = in.read(buf);
}
JSONTokener tokener = new JSONTokener( builder.toString() );
You can do:
JSONTokener tokener = new JSONTokener(
IOUtils.toString(response.getEntity().getContent()) );
where IOUtils is from the commons IO library.
scrollTop animation without jquery
HTML:
<button onclick="scrollToTop(1000);"></button>
1# JavaScript (linear):
function scrollToTop (duration) {
// cancel if already on top
if (document.scrollingElement.scrollTop === 0) return;
const totalScrollDistance = document.scrollingElement.scrollTop;
let scrollY = totalScrollDistance, oldTimestamp = null;
function step (newTimestamp) {
if (oldTimestamp !== null) {
// if duration is 0 scrollY will be -Infinity
scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
document.scrollingElement.scrollTop = scrollY;
}
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
2# JavaScript (ease in and out):
function scrollToTop (duration) {
// cancel if already on top
if (document.scrollingElement.scrollTop === 0) return;
const cosParameter = document.scrollingElement.scrollTop / 2;
let scrollCount = 0, oldTimestamp = null;
function step (newTimestamp) {
if (oldTimestamp !== null) {
// if duration is 0 scrollCount will be Infinity
scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
}
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
/*
Explanation:
- pi is the length/end point of the cosinus intervall (see below)
- newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
(for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
- newTimestamp - oldTimestamp equals the delta time
a * cos (bx + c) + d | c translates along the x axis = 0
= a * cos (bx) + d | d translates along the y axis = 1 -> only positive y values
= a * cos (bx) + 1 | a stretches along the y axis = cosParameter = window.scrollY / 2
= cosParameter + cosParameter * (cos bx) | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
= cosParameter + cosParameter * (cos scrollCount * x)
*/
Note:
- Duration in milliseconds (1000ms = 1s)
- Second script uses the cos function. Example curve:
3# Simple scrolling library on Github
How do I POST form data with UTF-8 encoding by using curl?
You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.
You should use this request:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod
How to change Vagrant 'default' machine name?
If you want to change anything else instead of 'default', then just add these additional lines to your Vagrantfile:
Change the basebox name, when using "vagrant status"
config.vm.define "tendo" do |tendo|
end
Where "tendo" will be the name that will appear instead of default
What is the purpose of the "final" keyword in C++11 for functions?
Final cannot be applied to non-virtual functions.
error: only virtual member functions can be marked 'final'
It wouldn't be very meaningful to be able to mark a non-virtual method as 'final'. Given
struct A { void foo(); };
struct B : public A { void foo(); };
A * a = new B;
a -> foo(); // this will call A :: foo anyway, regardless of whether there is a B::foo
a->foo()
will always call A::foo
.
But, if A::foo was virtual
, then B::foo would override it. This might be undesirable, and hence it would make sense to make the virtual function final.
The question is though, why allow final on virtual functions. If you have a deep hierarchy:
struct A { virtual void foo(); };
struct B : public A { virtual void foo(); };
struct C : public B { virtual void foo() final; };
struct D : public C { /* cannot override foo */ };
Then the final
puts a 'floor' on how much overriding can be done. Other classes can extend A and B and override their foo
, but it a class extends C then it is not allowed.
So it probably doesn't make sense to make the 'top-level' foo final
, but it might make sense lower down.
(I think though, there is room to extend the words final and override to non-virtual members. They would have a different meaning though.)
How to build an android library with Android Studio and gradle?
Here is my solution for mac users I think it work for window also:
First go to your Android Studio toolbar
Build > Make Project (while you guys are online let it to download the files) and then
Build > Compile Module "your app name is shown here" (still online let the files are
download and finish) and then
Run your app that is done it will launch your emulator and configure it then run it!
That is it!!! Happy Coding guys!!!!!!!
Automatically size JPanel inside JFrame
You can set a layout manager like BorderLayout and then define more specifically, where your panel should go:
MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
mainFrame.add(mainPanel, BorderLayout.CENTER);
mainFrame.pack();
mainFrame.setVisible(true);
This puts the panel into the center area of the frame and lets it grow automatically when resizing the frame.
python modify item in list, save back in list
You need to use the enumerate function: python docs
for place, item in enumerate(list):
if "foo" in item:
item = replace_all(item, replaceDictionary)
list[place] = item
print item
Also, it's a bad idea to use the word list as a variable, due to it being a reserved word in python.
Since you had problems with enumerate, an alternative from the itertools library:
for place, item in itertools.zip(itertools.count(0), list):
if "foo" in item:
item = replace_all(item, replaceDictionary)
list[place] = item
print item
Random Number Between 2 Double Numbers
I'm a bit late to the party but I needed to implement a general solution and it turned out that none of the solutions can satisfy my needs.
The accepted solution is good for small ranges; however, maximum - minimum
can be infinity for big ranges. So a corrected version can be this version:
public static double NextDoubleLinear(this Random random, double minValue, double maxValue)
{
// TODO: some validation here...
double sample = random.NextDouble();
return (maxValue * sample) + (minValue * (1d - sample));
}
This generates random numbers nicely even between double.MinValue
and double.MaxValue
. But this introduces another "problem", which is nicely presented in this post: if we use such big ranges the values might seem too "unnatural". For example, after generating 10,000 random doubles between 0 and double.MaxValue
all of the values were between 2.9579E+304 and 1.7976E+308.
So I created also another version, which generates numbers on a logarithmic scale:
public static double NextDoubleLogarithmic(this Random random, double minValue, double maxValue)
{
// TODO: some validation here...
bool posAndNeg = minValue < 0d && maxValue > 0d;
double minAbs = Math.Min(Math.Abs(minValue), Math.Abs(maxValue));
double maxAbs = Math.Max(Math.Abs(minValue), Math.Abs(maxValue));
int sign;
if (!posAndNeg)
sign = minValue < 0d ? -1 : 1;
else
{
// if both negative and positive results are expected we select the sign based on the size of the ranges
double sample = random.NextDouble();
var rate = minAbs / maxAbs;
var absMinValue = Math.Abs(minValue);
bool isNeg = absMinValue <= maxValue ? rate / 2d > sample : rate / 2d < sample;
sign = isNeg ? -1 : 1;
// now adjusting the limits for 0..[selected range]
minAbs = 0d;
maxAbs = isNeg ? absMinValue : Math.Abs(maxValue);
}
// Possible double exponents are -1022..1023 but we don't generate too small exponents for big ranges because
// that would cause too many almost zero results, which are much smaller than the original NextDouble values.
double minExponent = minAbs == 0d ? -16d : Math.Log(minAbs, 2d);
double maxExponent = Math.Log(maxAbs, 2d);
if (minExponent == maxExponent)
return minValue;
// We decrease exponents only if the given range is already small. Even lower than -1022 is no problem, the result may be 0
if (maxExponent < minExponent)
minExponent = maxExponent - 4;
double result = sign * Math.Pow(2d, NextDoubleLinear(random, minExponent, maxExponent));
// protecting ourselves against inaccurate calculations; however, in practice result is always in range.
return result < minValue ? minValue : (result > maxValue ? maxValue : result);
}
Some tests:
Here are the sorted results of generating 10,000 random double numbers between 0 and Double.MaxValue
with both strategies. The results are displayed with using logarithmic scale:
Though the linear random values seem to be wrong at first glance the statistics show that none of them are "better" than the other: even the linear strategy has an even distribution and the average difference between the values are pretty much the same with both strategies.
Playing with different ranges showed me that the linear strategy gets to be "sane" with range between 0 and ushort.MaxValue
with a "reasonable" minimum value of 10.78294704
(for ulong
range the minimum value was 3.03518E+15; int
: 353341). These are the same results of both strategies displayed with different scales:
Edit:
Recently I made my libraries open source, feel free to see the RandomExtensions.NextDouble
method with the complete validation.
How do I center an SVG in a div?
Flexbox is another approach: add
_x000D_
_x000D_
.container {
display: flex;
justify-content: center;
}
_x000D_
_x000D_
_x000D_
And add the .container
class to the div which contains your svg.
Import-CSV and Foreach
Solution is to change Delimiter.
Content of the csv file -> Note .. Also space and , in value
Values are 6 Dutch word aap,noot,mies,Piet, Gijs, Jan
Col1;Col2;Col3
a,ap;noo,t;mi es
P,iet;G ,ijs;Ja ,n
$csv = Import-Csv C:\TejaCopy.csv -Delimiter ';'
Answer:
Write-Host $csv
@{Col1=a,ap; Col2=noo,t; Col3=mi es} @{Col1=P,iet; Col2=G ,ijs; Col3=Ja ,n}
It is possible to read a CSV file and use other Delimiter to separate each column.
It worked for my script :-)
How can I make all images of different height and width the same via CSS?
You can do it this way:
.container{
position: relative;
width: 100px;
height: 100px;
overflow: hidden;
z-index: 1;
}
img{
left: 50%;
position: absolute;
top: 50%;
-ms-transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
max-width: 100%;
}
VLook-Up Match first 3 characters of one column with another column
=VLOOKUP(Left(A1,1),B$2:B$22,2,FALSE)
Left is because you are starting the word/alphanumeric text from the left. the number "1" which i have placed is after lookup value in this case "A1" is because my search includes the formula for 1st character. If second character is asked it would be (A1,2)
quite simple really :)
Strip all non-numeric characters from string in JavaScript
In Angular / Ionic / VueJS -- I just came up with a simple method of:
stripNaN(txt: any) {
return txt.toString().replace(/[^a-zA-Z0-9]/g, "");
}
Usage on the view:
<a [href]="'tel:'+stripNaN(single.meta['phone'])" [innerHTML]="stripNaN(single.meta['phone'])"></a>
Android Fragments and animation
If you don't have to use the support library then have a look at Roman's answer.
But if you want to use the support library you have to use the old animation framework as described below.
After consulting Reto's and blindstuff's answers I have gotten the following code working.
The fragments appear sliding in from the right and sliding out to the left when back is pressed.
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit);
CustomFragment newCustomFragment = CustomFragment.newInstance();
transaction.replace(R.id.fragment_container, newCustomFragment );
transaction.addToBackStack(null);
transaction.commit();
The order is important. This means you must call setCustomAnimations()
before replace()
or the animation will not take effect!
Next these files have to be placed inside the res/anim folder.
enter.xml:
<?xml version="1.0" encoding="utf-8"?>
<set>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="100%"
android:toXDelta="0"
android:interpolator="@android:anim/decelerate_interpolator"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
exit.xml:
<set>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0"
android:toXDelta="-100%"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
pop_enter.xml:
<set>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="-100%"
android:toXDelta="0"
android:interpolator="@android:anim/decelerate_interpolator"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
pop_exit.xml:
<?xml version="1.0" encoding="utf-8"?>
<set>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0"
android:toXDelta="100%"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
The duration of the animations can be changed to any of the default values like @android:integer/config_shortAnimTime
or any other number.
Note that if in between fragment replacements a configuration change happens (for example rotation) the back action isn't animated. This is a documented bug that still exists in the rev 20 of the support library.
Getting indices of True values in a boolean list
You can use filter for it:
filter(lambda x: self.states[x], range(len(self.states)))
The range
here enumerates elements of your list and since we want only those where self.states
is True
, we are applying a filter based on this condition.
For Python > 3.0:
list(filter(lambda x: self.states[x], range(len(self.states))))
How to discard local commits in Git?
As an aside, apart from the answer by mipadi (which should work by the way), you should know that doing:
git branch -D master
git checkout master
also does exactly what you want without having to redownload everything
(your quote paraphrased). That is because your local repo contains a copy of the remote repo (and that copy is not the same as your local directory, it is not even the same as your checked out branch).
Wiping out a branch is perfectly safe and reconstructing that branch is very fast and involves no network traffic. Remember, git is primarily a local repo by design. Even remote branches have a copy on the local. There's only a bit of metadata that tells git that a specific local copy is actually a remote branch. In git, all files are on your hard disk all the time.
If you don't have any branches other than master, you should:
git checkout -b 'temp'
git branch -D master
git checkout master
git branch -D temp
Spring Boot REST service exception handling
For REST controllers, I would recommend to use Zalando Problem Spring Web
.
https://github.com/zalando/problem-spring-web
If Spring Boot aims to embed some auto-configuration, this library does more for exception handling. You just need to add the dependency:
<dependency>
<groupId>org.zalando</groupId>
<artifactId>problem-spring-web</artifactId>
<version>LATEST</version>
</dependency>
And then define one or more advice traits for your exceptions (or use those provided by default)
public interface NotAcceptableAdviceTrait extends AdviceTrait {
@ExceptionHandler
default ResponseEntity<Problem> handleMediaTypeNotAcceptable(
final HttpMediaTypeNotAcceptableException exception,
final NativeWebRequest request) {
return Responses.create(Status.NOT_ACCEPTABLE, exception, request);
}
}
Then you can defined the controller advice for exception handling as:
@ControllerAdvice
class ExceptionHandling implements MethodNotAllowedAdviceTrait, NotAcceptableAdviceTrait {
}
Handle ModelState Validation in ASP.NET Web API
I had an issue implementing the accepted solution pattern where my ModelStateFilter
would always return false
(and subsequently a 400) for actionContext.ModelState.IsValid
for certain model objects:
public class ModelStateFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest};
}
}
}
I only accept JSON, so I implemented a custom model binder class:
public class AddressModelBinder : System.Web.Http.ModelBinding.IModelBinder
{
public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
{
var posted = actionContext.Request.Content.ReadAsStringAsync().Result;
AddressDTO address = JsonConvert.DeserializeObject<AddressDTO>(posted);
if (address != null)
{
// moar val here
bindingContext.Model = address;
return true;
}
return false;
}
}
Which I register directly after my model via
config.BindParameter(typeof(AddressDTO), new AddressModelBinder());
CSS rule to apply only if element has BOTH classes
Below applies to all tags with the following two classes
.abc.xyz {
width: 200px !important;
}
applies to div tags with the following two classes
div.abc.xyz {
width: 200px !important;
}
If you wanted to modify this using jQuery
$(document).ready(function() {
$("div.abc.xyz").width("200px");
});
No Title Bar Android Theme
To Hide the Action Bar add the below code in Values/Styles
<style name="CustomActivityThemeNoActionBar" parent="@android:style/Theme.Holo.Light">
<item name="android:windowActionBar">false</item>
<item name="android:windowNoTitle">true</item>
</style>
Then in your AndroidManifest.xml file add the below code in the required activity
<activity
android:name="com.newbelievers.android.NBMenu"
android:label="@string/title_activity_nbmenu"
android:theme="@style/CustomActivityThemeNoActionBar">
</activity>
Pad a number with leading zeros in JavaScript
function padToFour(number) {
if (number<=9999) { number = ("000"+number).slice(-4); }
return number;
}
Something like that?
Bonus incomprehensible-but-slicker single-line ES6 version:
let padToFour = number => number <= 9999 ? `000${number}`.slice(-4) : number;
ES6isms:
let
is a block scoped variable (as opposed to var
’s functional scoping)
=>
is an arrow function that among other things replaces function
and is prepended by its parameters
- If a arrow function takes a single parameter you can omit the parentheses (hence
number =>
)
- If an arrow function body has a single line that starts with
return
you can omit the braces and the return
keyword and simply use the expression
- To get the function body down to a single line I cheated and used a ternary expression
How to convert an Array to a Set in Java
Java 8
We have the option of using Stream
as well. We can get stream in various ways:
Set<String> set = Stream.of("A", "B", "C", "D").collect(Collectors.toCollection(HashSet::new));
System.out.println(set);
String[] stringArray = {"A", "B", "C", "D"};
Set<String> strSet1 = Arrays.stream(stringArray).collect(Collectors.toSet());
System.out.println(strSet1);
// if you need HashSet then use below option.
Set<String> strSet2 = Arrays.stream(stringArray).collect(Collectors.toCollection(HashSet::new));
System.out.println(strSet2);
The source code of Collectors.toSet()
shows that elements are added one by one to a HashSet
but specification does not guarantee it will be a HashSet
.
"There are no guarantees on the type, mutability, serializability, or
thread-safety of the Set returned."
So it is better to use the later option. The output is:
[A, B, C, D]
[A, B, C, D]
[A, B, C, D]
Immutable Set (Java 9)
Java 9 introduced Set.of
static factory method which returns immutable set for the provided elements or the array.
@SafeVarargs
static <E> Set<E> of?(E... elements)
Check Immutable Set Static Factory Methods for details.
Immutable Set (Java 10)
We can also get an immutable set in two ways:
Set.copyOf(Arrays.asList(array))
Arrays.stream(array).collect(Collectors.toUnmodifiableList());
The method Collectors.toUnmodifiableList()
internally makes use of Set.of
introduced in Java 9. Also check this answer of mine for more.
Select rows with same id but different value in another column
Join the same table back to itself. Use an inner join so that rows that don't match are discarded. In the joined set, there will be rows that have a matching ARIDNR in another row in the table with a different LIEFNR. Allow those ARIDNR to appear in the final set.
SELECT * FROM YourTable WHERE ARIDNR IN (
SELECT a.ARIDNR FROM YourTable a
JOIN YourTable b on b.ARIDNR = a.ARIDNR AND b.LIEFNR <> a.LIEFNR
)
How can I make my match non greedy in vim?
G'day,
Vim's regexp processing is not too brilliant. I've found that the regexp syntax for sed is about the right match for vim's capabilities.
I usually set the search highlighting on (:set hlsearch) and then play with the regexp after entering a slash to enter search mode.
Edit: Mark, that trick to minimise greedy matching is also covered in Dale Dougherty's excellent book "Sed & Awk" (sanitised Amazon link).
Chapter Three "Understanding Regular Expression Syntax" is an excellent intro to the more primitive regexp capabilities involved with sed and awk. Only a short read and highly recommended.
HTH
cheers,
Python: Maximum recursion depth exceeded
You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:
import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values
... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.
PowerShell To Set Folder Permissions
Referring to Gamaliel 's answer: $args is an array of the arguments that are passed into a script at runtime - as such cannot be used the way Gamaliel is using it.
This is actually working:
$myPath = 'C:\whatever.file'
# get actual Acl entry
$myAcl = Get-Acl "$myPath"
$myAclEntry = "Domain\User","FullControl","Allow"
$myAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($myAclEntry)
# prepare new Acl
$myAcl.SetAccessRule($myAccessRule)
$myAcl | Set-Acl "$MyPath"
# check if added entry present
Get-Acl "$myPath" | fl
Nodejs send file in response
You need use Stream to send file (archive) in a response, what is more you have to use appropriate Content-type in your response header.
There is an example function that do it:
const fs = require('fs');
// Where fileName is name of the file and response is Node.js Reponse.
responseFile = (fileName, response) => {
const filePath = "/path/to/archive.rar" // or any file format
// Check if file specified by the filePath exists
fs.exists(filePath, function(exists){
if (exists) {
// Content-type is very interesting part that guarantee that
// Web browser will handle response in an appropriate manner.
response.writeHead(200, {
"Content-Type": "application/octet-stream",
"Content-Disposition": "attachment; filename=" + fileName
});
fs.createReadStream(filePath).pipe(response);
} else {
response.writeHead(400, {"Content-Type": "text/plain"});
response.end("ERROR File does not exist");
}
});
}
}
The purpose of the Content-Type field is to describe the data contained in the body fully enough that the receiving user agent can pick an appropriate agent or mechanism to present the data to the user, or otherwise deal with the data in an appropriate manner.
"application/octet-stream" is defined as "arbitrary binary data" in RFC 2046, purpose of this content-type is to be saved to disk - it is what you really need.
"filename=[name of file]" specifies name of file which will be downloaded.
For more information please see this stackoverflow topic.
How to check if a variable is not null?
They are not equivalent. The first will execute the block following the if
statement if myVar
is truthy (i.e. evaluates to true
in a conditional), while the second will execute the block if myVar
is any value other than null
.
The only values that are not truthy in JavaScript are the following (a.k.a. falsy values):
null
undefined
0
""
(the empty string)
false
NaN
css 100% width div not taking up full width of parent
html, body{
width:100%;
}
This tells the html to be 100% wide. But 100% refers to the whole browser window width, so no more than that.
You may want to set a min width instead.
html, body{
min-width:100%;
}
So it will be 100% as a minimum, bot more if needed.
JSF(Primefaces) ajax update of several elements by ID's
If the to-be-updated component is not inside the same NamingContainer
component (ui:repeat
, h:form
, h:dataTable
, etc), then you need to specify the "absolute" client ID. Prefix with :
(the default NamingContainer
separator character) to start from root.
<p:ajax process="@this" update="count :subTotal"/>
To be sure, check the client ID of the subTotal
component in the generated HTML for the actual value. If it's inside for example a h:form
as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.
<p:ajax process="@this" update="count :formId:subTotal"/>
Space separation of IDs is more recommended as <f:ajax>
doesn't support comma separation and starters would otherwise get confused.
SQL query: Delete all records from the table except latest N?
Using id for this task is not an option in many cases. For example - table with twitter statuses. Here is a variant with specified timestamp field.
delete from table
where access_time >=
(
select access_time from
(
select access_time from table
order by access_time limit 150000,1
) foo
)
All shards failed
If you're running a single node cluster for some reason, you might simply need to do avoid replicas, like this:
curl -XPUT -H 'Content-Type: application/json' 'localhost:9200/_settings' -d '
{
"index" : {
"number_of_replicas" : 0
}
}'
Doing this you'll force to use es without replicas
Changing background color of selected cell?
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
self.contentView.backgroundColor = .black
} else {
self.contentView.backgroundColor = .white
}
}
Giving my function access to outside variable
$myArr = array();
function someFuntion(array $myArr) {
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
return $myArr;
}
$myArr = someFunction($myArr);
How to check which version of Keras is installed?
Python library authors put the version number in <module>.__version__
. You can print it by running this on the command line:
python -c 'import keras; print(keras.__version__)'
If it's Windows terminal, enclose snippet with double-quotes like below
python -c "import keras; print(keras.__version__)"
bash: npm: command not found?
I know it's an old question. But it keeps showing in google first position and all it says it's "install node.js".
For a newbie this is not obvious, so all you have to do is go to the node.js website and search for the command for your linux distribution version or any other operating system. Here is the link:
https://nodejs.org/en/download/package-manager/
In this page you have to choose your operating system and you'll find your command. Then you just log into your console as a root (using putty for instance) and execute that command.
After that, you log as normal user and go again inside your laravel application folder and run again npm install command, and it should work.
Hope it helps.
Subtract two dates in SQL and get days of the result
Syntax
DATEDIFF(expr1,expr2)
Description
DATEDIFF() returns (expr1 – expr2) expressed as a value in days from one date to the other. expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation.
@D Stanley
Where is Maven Installed on Ubuntu
Depends on what you are looking for. If you are looking for the executable :
$ whereis mvn
If you are looking for the libs and repo :
$ locate maven
With the locate command, you could also pipe it to grep to find a particular library, i.e.
$ locate maven | grep 'jetty'
HTH
Priority queue in .Net
Use a Java to C# translator on the Java implementation (java.util.PriorityQueue) in the Java Collections framework, or more intelligently use the algorithm and core code and plug it into a C# class of your own making that adheres to the C# Collections framework API for Queues, or at least Collections.
HTML5 Audio Looping
Try using jQuery for the event listener, it will then work in Firefox.
myAudio = new Audio('someSound.ogg');
$(myAudio).bind('ended', function() {
myAudio.currentTime = 0;
myAudio.play();
});
myAudio.play();
Something like that.
Take nth column in a text file
You can use the cut
command:
cut -d' ' -f3,5 < datafile.txt
prints
1657 19.6117
1410 18.8302
3078 18.6695
2434 14.0508
3129 13.5495
the
-d' '
- mean, use space
as a delimiter
-f3,5
- take and print 3rd and 5th column
The cut
is much faster for large files as a pure shell solution. If your file is delimited with multiple whitespaces, you can remove them first, like:
sed 's/[\t ][\t ]*/ /g' < datafile.txt | cut -d' ' -f3,5
where the (gnu) sed will replace any tab
or space
characters with a single space
.
For a variant - here is a perl solution too:
perl -lanE 'say "$F[2] $F[4]"' < datafile.txt
More Pythonic Way to Run a Process X Times
The for loop is definitely more pythonic, as it uses Python's higher level built in functionality to convey what you're doing both more clearly and concisely. The overhead of range vs xrange, and assigning an unused i
variable, stem from the absence of a statement like Verilog's repeat
statement. The main reason to stick to the for range solution is that other ways are more complex. For instance:
from itertools import repeat
for unused in repeat(None, 10):
del unused # redundant and inefficient, the name is clear enough
print "This is run 10 times"
Using repeat instead of range here is less clear because it's not as well known a function, and more complex because you need to import it. The main style guides if you need a reference are PEP 20 - The Zen of Python and PEP 8 - Style Guide for Python Code.
We also note that the for range version is an explicit example used in both the language reference and tutorial, although in that case the value is used. It does mean the form is bound to be more familiar than the while expansion of a C-style for loop.
PHP Date Time Current Time Add Minutes
echo $date = date('H:i:s', strtotime('13:00:00 + 30 minutes') );
13:00:00 - any inputted time
30 minutes - any interval you wish (20 hours, 10 minutes, 1 seconds etc...)
javascript get x and y coordinates on mouse click
Like this.
_x000D_
_x000D_
function printMousePos(event) {_x000D_
document.body.textContent =_x000D_
"clientX: " + event.clientX +_x000D_
" - clientY: " + event.clientY;_x000D_
}_x000D_
_x000D_
document.addEventListener("click", printMousePos);
_x000D_
_x000D_
_x000D_
MouseEvent - MDN
MouseEvent.clientX Read only
The X coordinate of the mouse pointer in local (DOM content) coordinates.
MouseEvent.clientY Read only
The Y coordinate of the mouse pointer in local (DOM content) coordinates.
Android ViewPager with bottom dots
No need for that much code.
You can do all this stuff without coding so much by using only viewpager
with tablayout
.
Your main Layout:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
<android.support.design.widget.TabLayout
android:id="@+id/tabDots"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabBackground="@drawable/tab_selector"
app:tabGravity="center"
app:tabIndicatorHeight="0dp"/>
</RelativeLayout>
Hook up your UI elements inactivity or fragment as follows:
Java Code:
mImageViewPager = (ViewPager) findViewById(R.id.pager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabDots);
tabLayout.setupWithViewPager(mImageViewPager, true);
That's it, you are good to go.
You will need to create the following xml resource file in the drawable folder.
tab_indicator_selected.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
android:innerRadius="0dp"
android:shape="ring"
android:thickness="4dp"
android:useLevel="false"
xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/colorAccent"/>
</shape>
tab_indicator_default.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadius="0dp"
android:shape="oval"
android:thickness="2dp"
android:useLevel="false">
<solid android:color="@android:color/darker_gray"/>
</shape>
tab_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/tab_indicator_selected"
android:state_selected="true"/>
<item android:drawable="@drawable/tab_indicator_default"/>
</selector>
Feeling as lazy as I am? Well, all the above code is converted into a library!
Usage
Add the following in your gradle:
implementation 'com.chabbal:slidingdotsplash:1.0.2'
Add the following to your Activity or Fragment layout.
<com.chabbal.slidingdotsplash.SlidingSplashView
android:id="@+id/splash"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:imageResources="@array/img_id_arr"/>
Create an integer array in strings.xml
e.g.
<integer-array name="img_id_arr">
<item>@drawable/img1</item>
<item>@drawable/img2</item>
<item>@drawable/img3</item>
<item>@drawable/img4</item>
</integer-array>
Done!
Extra in order to listen page changes use addOnPageChangeListener(listener);
Github link.
How to get the top 10 values in postgresql?
For this you can use limit
select *
from scores
order by score desc
limit 10
If performance is important (when is it not ;-) look for an index on score.
Starting with version 8.4, you can also use the standard (SQL:2008) fetch first
select *
from scores
order by score desc
fetch first 10 rows only
As @Raphvanns pointed out, this will give you the first 10 rows
literally. To remove duplicate values, you have to select distinct
rows, e.g.
select distinct *
from scores
order by score desc
fetch first 10 rows only
SQL Fiddle
Efficiency of Java "Double Brace Initialization"?
leak prone
I've decided to chime in. The performance impact includes: disk operation + unzip (for jar), class verification, perm-gen space (for Sun's Hotspot JVM).
However, worst of all: it's leak prone. You can't simply return.
Set<String> getFlavors(){
return Collections.unmodifiableSet(flavors)
}
So if the set escapes to any other part loaded by a different classloader and a reference is kept there, the entire tree of classes+classloader will be leaked. To avoid that, a copy to HashMap is necessary, new LinkedHashSet(new ArrayList(){{add("xxx);add("yyy");}})
. Not so cute any more.
I don't use the idiom, myself, instead it is like new LinkedHashSet(Arrays.asList("xxx","YYY"));
HTTP headers in Websockets client API
Sending Authorization header is not possible.
Attaching a token query parameter is an option. However, in some circumstances, it may be undesirable to send your main login token in plain text as a query parameter because it is more opaque than using a header and will end up being logged whoknowswhere. If this raises security concerns for you, an alternative is to use a secondary JWT token just for the web socket stuff.
Create a REST endpoint for generating this JWT, which can of course only be accessed by users authenticated with your primary login token (transmitted via header). The web socket JWT can be configured differently than your login token, e.g. with a shorter timeout, so it's safer to send around as query param of your upgrade request.
Create a separate JwtAuthHandler for the same route you register the SockJS eventbusHandler on. Make sure your auth handler is registered first, so you can check the web socket token against your database (the JWT should be somehow linked to your user in the backend).
Average of multiple columns
In PostgreSQL, to get the average of multiple (2 to 8) columns in one row just define a set of seven functions called average(). Will produce the average of the non-null columns.
And then just
select *,(r1+r2+r3+r4+r5)/5.0,average(r1,r2,r3,r4,r5) from request;
req_id | r1 | r2 | r3 | r4 | r5 | ?column? | average
--------+----+----+----+----+----+--------------------+--------------------
R12673 | 2 | 5 | 3 | 7 | 10 | 5.4000000000000000 | 5.4000000000000000
R34721 | 3 | 5 | 2 | 1 | 8 | 3.8000000000000000 | 3.8000000000000000
R27835 | 1 | 3 | 8 | 5 | 6 | 4.6000000000000000 | 4.6000000000000000
(3 rows)
update request set r4=NULL where req_id='R34721';
UPDATE 1
select *,(r1+r2+r3+r4+r5)/5.0,average(r1,r2,r3,r4,r5) from request;
req_id | r1 | r2 | r3 | r4 | r5 | ?column? | average
--------+----+----+----+----+----+--------------------+--------------------
R12673 | 2 | 5 | 3 | 7 | 10 | 5.4000000000000000 | 5.4000000000000000
R34721 | 3 | 5 | 2 | | 8 | | 4.5000000000000000
R27835 | 1 | 3 | 8 | 5 | 6 | 4.6000000000000000 | 4.6000000000000000
(3 rows)
select *,(r3+r4+r5)/3.0,average(r3,r4,r5) from request;
req_id | r1 | r2 | r3 | r4 | r5 | ?column? | average
--------+----+----+----+----+----+--------------------+--------------------
R12673 | 2 | 5 | 3 | 7 | 10 | 6.6666666666666667 | 6.6666666666666667
R34721 | 3 | 5 | 2 | | 8 | | 5.0000000000000000
R27835 | 1 | 3 | 8 | 5 | 6 | 6.3333333333333333 | 6.3333333333333333
(3 rows)
Like this:
CREATE OR REPLACE FUNCTION AVERAGE (
V1 NUMERIC,
V2 NUMERIC)
RETURNS NUMERIC
AS $FUNCTION$
DECLARE
COUNT NUMERIC;
TOTAL NUMERIC;
BEGIN
COUNT=0;
TOTAL=0;
IF V1 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V1; END IF;
IF V2 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V2; END IF;
RETURN TOTAL/COUNT;
EXCEPTION WHEN DIVISION_BY_ZERO THEN RETURN NULL;
END
$FUNCTION$ LANGUAGE PLPGSQL;
CREATE OR REPLACE FUNCTION AVERAGE (
V1 NUMERIC,
V2 NUMERIC,
V3 NUMERIC)
RETURNS NUMERIC
AS $FUNCTION$
DECLARE
COUNT NUMERIC;
TOTAL NUMERIC;
BEGIN
COUNT=0;
TOTAL=0;
IF V1 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V1; END IF;
IF V2 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V2; END IF;
IF V3 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V3; END IF;
RETURN TOTAL/COUNT;
EXCEPTION WHEN DIVISION_BY_ZERO THEN RETURN NULL;
END
$FUNCTION$ LANGUAGE PLPGSQL;
CREATE OR REPLACE FUNCTION AVERAGE (
V1 NUMERIC,
V2 NUMERIC,
V3 NUMERIC,
V4 NUMERIC)
RETURNS NUMERIC
AS $FUNCTION$
DECLARE
COUNT NUMERIC;
TOTAL NUMERIC;
BEGIN
COUNT=0;
TOTAL=0;
IF V1 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V1; END IF;
IF V2 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V2; END IF;
IF V3 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V3; END IF;
IF V4 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V4; END IF;
RETURN TOTAL/COUNT;
EXCEPTION WHEN DIVISION_BY_ZERO THEN RETURN NULL;
END
$FUNCTION$ LANGUAGE PLPGSQL;
CREATE OR REPLACE FUNCTION AVERAGE (
V1 NUMERIC,
V2 NUMERIC,
V3 NUMERIC,
V4 NUMERIC,
V5 NUMERIC)
RETURNS NUMERIC
AS $FUNCTION$
DECLARE
COUNT NUMERIC;
TOTAL NUMERIC;
BEGIN
COUNT=0;
TOTAL=0;
IF V1 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V1; END IF;
IF V2 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V2; END IF;
IF V3 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V3; END IF;
IF V4 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V4; END IF;
IF V5 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V5; END IF;
RETURN TOTAL/COUNT;
EXCEPTION WHEN DIVISION_BY_ZERO THEN RETURN NULL;
END
$FUNCTION$ LANGUAGE PLPGSQL;
CREATE OR REPLACE FUNCTION AVERAGE (
V1 NUMERIC,
V2 NUMERIC,
V3 NUMERIC,
V4 NUMERIC,
V5 NUMERIC,
V6 NUMERIC)
RETURNS NUMERIC
AS $FUNCTION$
DECLARE
COUNT NUMERIC;
TOTAL NUMERIC;
BEGIN
COUNT=0;
TOTAL=0;
IF V1 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V1; END IF;
IF V2 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V2; END IF;
IF V3 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V3; END IF;
IF V4 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V4; END IF;
IF V5 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V5; END IF;
IF V6 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V6; END IF;
RETURN TOTAL/COUNT;
EXCEPTION WHEN DIVISION_BY_ZERO THEN RETURN NULL;
END
$FUNCTION$ LANGUAGE PLPGSQL;
CREATE OR REPLACE FUNCTION AVERAGE (
V1 NUMERIC,
V2 NUMERIC,
V3 NUMERIC,
V4 NUMERIC,
V5 NUMERIC,
V6 NUMERIC,
V7 NUMERIC)
RETURNS NUMERIC
AS $FUNCTION$
DECLARE
COUNT NUMERIC;
TOTAL NUMERIC;
BEGIN
COUNT=0;
TOTAL=0;
IF V1 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V1; END IF;
IF V2 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V2; END IF;
IF V3 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V3; END IF;
IF V4 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V4; END IF;
IF V5 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V5; END IF;
IF V6 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V6; END IF;
IF V7 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V7; END IF;
RETURN TOTAL/COUNT;
EXCEPTION WHEN DIVISION_BY_ZERO THEN RETURN NULL;
END
$FUNCTION$ LANGUAGE PLPGSQL;
CREATE OR REPLACE FUNCTION AVERAGE (
V1 NUMERIC,
V2 NUMERIC,
V3 NUMERIC,
V4 NUMERIC,
V5 NUMERIC,
V6 NUMERIC,
V7 NUMERIC,
V8 NUMERIC)
RETURNS NUMERIC
AS $FUNCTION$
DECLARE
COUNT NUMERIC;
TOTAL NUMERIC;
BEGIN
COUNT=0;
TOTAL=0;
IF V1 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V1; END IF;
IF V2 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V2; END IF;
IF V3 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V3; END IF;
IF V4 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V4; END IF;
IF V5 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V5; END IF;
IF V6 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V6; END IF;
IF V7 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V7; END IF;
IF V8 IS NOT NULL THEN COUNT=COUNT+1; TOTAL=TOTAL+V8; END IF;
RETURN TOTAL/COUNT;
EXCEPTION WHEN DIVISION_BY_ZERO THEN RETURN NULL;
END
$FUNCTION$ LANGUAGE PLPGSQL;
type checking in javascript
A clean approach
You can consider using a very small, dependency-free library like Not. Solves all problems:
// at the basic level it supports primitives
let number = 10
let array = []
not('number', 10) // returns false
not('number', []) // throws error
// so you need to define your own:
let not = Object.create(Not)
not.defineType({
primitive: 'number',
type: 'integer',
pass: function(candidate) {
// pre-ECMA6
return candidate.toFixed(0) === candidate.toString()
// ECMA6
return Number.isInteger(candidate)
}
})
not.not('integer', 4.4) // gives error message
not.is('integer', 4.4) // returns false
not.is('integer', 8) // returns true
If you make it a habit, your code will be much stronger. Typescript solves part of the problem but doesn't work at runtime, which is also important.
function test (string, boolean) {
// any of these below will throw errors to protect you
not('string', string)
not('boolean', boolean)
// continue with your code.
}
Separating class code into a header and cpp file
Basically a modified syntax of function declaration/definitions:
a2dd.h
class A2DD
{
private:
int gx;
int gy;
public:
A2DD(int x,int y);
int getSum();
};
a2dd.cpp
A2DD::A2DD(int x,int y)
{
gx = x;
gy = y;
}
int A2DD::getSum()
{
return gx + gy;
}
How can I get an object's absolute position on the page in Javascript?
I would definitely suggest using element.getBoundingClientRect().
https://developer.mozilla.org/en-US/docs/Web/API/element.getBoundingClientRect
Summary
Returns a text rectangle object that encloses a group of text
rectangles.
Syntax
var rectObject = object.getBoundingClientRect();
Returns
The returned value is a TextRectangle object which is the union of the
rectangles returned by getClientRects() for the element, i.e., the CSS
border-boxes associated with the element.
The returned value is a TextRectangle
object, which contains read-only
left
, top
, right
and bottom
properties describing the border-box, in
pixels, with the top-left relative to the top-left of the viewport.
Here's a browser compatibility table taken from the linked MDN site:
+---------------+--------+-----------------+-------------------+-------+--------+
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
+---------------+--------+-----------------+-------------------+-------+--------+
| Basic support | 1.0 | 3.0 (1.9) | 4.0 | (Yes) | 4.0 |
+---------------+--------+-----------------+-------------------+-------+--------+
It's widely supported, and is really easy to use, not to mention that it's really fast. Here's a related article from John Resig: http://ejohn.org/blog/getboundingclientrect-is-awesome/
You can use it like this:
var logo = document.getElementById('hlogo');
var logoTextRectangle = logo.getBoundingClientRect();
console.log("logo's left pos.:", logoTextRectangle.left);
console.log("logo's right pos.:", logoTextRectangle.right);
Here's a really simple example: http://jsbin.com/awisom/2 (you can view and edit the code by clicking "Edit in JS Bin" in the upper right corner).
Or here's another one using Chrome's console:
Note:
I have to mention that the width
and height
attributes of the getBoundingClientRect()
method's return value are undefined
in Internet Explorer 8. It works in Chrome 26.x, Firefox 20.x and Opera 12.x though. Workaround in IE8: for width
, you could subtract the return value's right and left attributes, and for height
, you could subtract bottom and top attributes (like this).