Here is the NodeJS REST api for two PDF render scripts. https://github.com/pumppi/pdf2images
Scripts are: pdf2svg and Imagemagicks convert
If you are using Sql Server this should work
DECLARE @Table TABLE(
ID INT,
Val INT
)
INSERT INTO @Table (ID,Val) SELECT 1, 3
INSERT INTO @Table (ID,Val) SELECT 2, NULL
INSERT INTO @Table (ID,Val) SELECT 3, 5
INSERT INTO @Table (ID,Val) SELECT 4, NULL
INSERT INTO @Table (ID,Val) SELECT 5, NULL
INSERT INTO @Table (ID,Val) SELECT 6, 2
SELECT *,
ISNULL(Val, (SELECT TOP 1 Val FROM @Table WHERE ID < t.ID AND Val IS NOT NULL ORDER BY ID DESC))
FROM @Table t
The image should be embedded in the message as an attachment like this:
--boundary
Content-Type: image/png; name="sig.png"
Content-Disposition: inline; filename="sig.png"
Content-Transfer-Encoding: base64
Content-ID: <0123456789>
Content-Location: sig.png
base64 data
--boundary
And, the HTML part would reference the image like this:
<img src="cid:0123456789">
In some clients, src="sig.png" will work too.
You'd basically have a multipart/mixed, multipart/alternative, multipart/related message where the image attachment is in the related part.
Clients shouldn't block this image either as it isn't remote.
Or, here's a multipart/alternative, multipart/related example as an mbox file (save as windows newline format and put a blank line at the end. And, use no extension or the .mbs extension):
From
From: [email protected]
To: [email protected]
Subject: HTML Messages with Embedded Pic in Signature
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary="alternative_boundary"
This is a message with multiple parts in MIME format.
--alternative_boundary
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 8bit
test
--
[Picture of a Christmas Tree]
--alternative_boundary
Content-Type: multipart/related; boundary="related_boundary"
--related_boundary
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 8bit
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p>test</p>
<p class="sig">-- <br><img src="cid:0123456789"></p>
</body>
</html>
--related_boundary
Content-Type: image/png; name="sig.png"
Content-Disposition: inline; filename="sig.png"
Content-Location: sig.png
Content-ID: <0123456789>
Content-Transfer-Encoding: base64
R0lGODlhKAA8AIMLAAD//wAhAABKAABrAACUAAC1AADeAAD/AGsAAP8zM///AP//
///M//////+ZAMwAACH/C05FVFNDQVBFMi4wAwGgDwAh+QQJFAALACwAAAAAKAA8
AAME+3DJSWt1Nuu9Mf+g5IzK6IXopaxn6orlKy/jMc6vQRy4GySABK+HAiaIoQdg
uUSCBAKAYTBwbgyGA2AgsGqo0wMh7K0YEuj0sUxRoAfqB1vycBN21Ki8vOofBndR
c1AKgH8ETE1lBgo7O2JaU2UFAgRoDGoAXV4PD2qYagl7Vp0JDKenfwado0QCAQOQ
DIcDBgIFVgYBAlOxswR5r1VIUbCHwH8HlQWFRLYABVOWamACCkiJAAehaX0rPZ1B
oQSg3Z04AuFqB2IMd+atLwUBtpAHqKdUtbwGM1BTOgA5YhBr374ZAxhAqRVLzA53
OwTEAjhDIZYs09aBASYq+94HfAq3cRt57sWDct2EvEsTpBMVF6sYeEpDQIFDdo62
BHwZApjEhjW94RyQTWK/FPx+Ahpg09GdOzoJ/ESx0JaOQ42e2tsiEYpCEFwAGi04
8g6gSgNOovD0gBeVjCPR2BIAkgOrmSNxPo3rbhgHZiMFPnLkBg2BAuQ2XdmlwK1Z
ooZu1sRz6xWlxd4U9GIHwOmdzFgCFKCERYNoeo2BZsPp0KY+A/OAfZDYWKJZLZBo
1mQXdlojvxNYiXrD8I+2uEvTdFJQksID0XjXiUwjJm6CzBVeBQgwBop1ZPpC8RKt
YN5RCpS6XiyMht093o8KcFFf/vKE0dCmaLeWYhQMwbeQaHLRfNk9o5Q13lQGklFQ
aMLFRLcwcN5qSWmGxS2jKQQFL9nEAgxsDEiwlAHaPPJWIfroo6FVEun0VkL4UABA
CAjUiIAFM2YQogzcoLCjC3HNsYB1aSBB5JFrZBABACH5BAkUAAsALAAAAAAoADwA
AwT7cMlJa3U2670x/6DkjKQXnleJrqnJruMxvq8xHDQbJEyC5yheAnh6MI5HYkgg
YNgGSo7BcGAMBNHNYGA7ELpZiyFBLg/DFvLArEBPHoAEgXDYChQP90IAoNYJCoGB
aACFhX8HBwoGegYAdHReijZoBXxmPWRYYQ8PZmSZZHmcnqBITp2jSgIBN5BVBFwC
BVkGAQJPiVV2rFCrCq1/sXUHAgQFAL45BncFNgSfW8wASoKBB59lhoVAnQqfDNCf
AJ05At5msHPiCeSqLwUBzF6nVnXSuIwvTDYGsXPhiMmSRUOWAC436HmZU+yGDQYF
81FhV+aevzUM3oHoZBD7W7Zs9VaUIhOn4pwE38p0srLCQCqSciBFUuBFGgEryj7E
Ojhg2yOG1hQMIMCEy4p8PB8llKmAIReiW040keUvmUygiexcwbWJwxUrzBDW+Thn
qLEB5UDUe0LxYwJmAhKk+pAqVLZE69qWGZpTQwG7ZISuw7uwzDFAXTXYYoJraKym
Q/HSASDpiiUFljbYitfYRtCF635yMRBUn4UA8aYclCw0shefW7gUgPxBKGPHA5pK
MpwsKy5AcmNZSIVHjdjI2eLwVZlK44IHQT8lkq7XTDznrAIEWMTErZwbsT/hQj1L
noXLV6YwS5eIJqIDf4tyLZB5Av1ZNrLzQSplrXVkOgxItBU1E+DCwC2xFZUME5dZ
c5AB9aw2jXkSQLhFIrj4xAx9szGWzwABdkGATwuAeEokW4wY24oK8MMViAjxxcc8
E0CUAYETIKAjAifgWGMI2ehBgVtCeleGEkYmeUYGEQAAIfkECRQACwAsAAAAACgA
PAADBPtwyUlrdTbrvTH/oOSMpBeeV4muqcmu4zG+r6EcNBskSoLnJ4VQCAw9ErzE
oxgSCBSGwYDJMRgOhIGAupFGsVEG12JAmpHicaU3QDPe6fHjoSAQDlIBY6leDIUD
dnp9C04DdXh3eAaEUTeKdwJRagUCBGdnW3JHmJh8XHNmWAeLDwCfRQIBA6MMiQMG
AgBcBgGSUgeuWQMAvb1MAgWruXAMrJYAUkU2wVGXDGZeAIxMCgVfaJhOVkB/PWeX
nXM5AnScSKR2dmZzqCwFUAKjo1l4XpLULNuwWXYHAHgWCYD15AXBgV+wEACg7sDA
A45oaLFy5ZKvXvYMEPCGYvvOwQOYAHRCQufFuU7/wp2Zo2AKCgPtwN3xR8/LLpcg
kg1khaVlQyw8GRAwlC8nvp2HeM5UR8CYxp05L8ay8YcplmLGtmniwCtKLFhJR9oR
amnAuBAiH9wK9G1kAgaxBCg5u6HdSUzp1LlNCqJAgZGBaC41Q6DAUAUfajm5ZUdK
v7z08ATjmKGWAltecaVTqE5oFisB/EIpSiH06IcKpQTa3JSVagPCWm7wZsgOwJkg
3xaTrJFkFgvtFHDywmt1J2iB2pC0C9x0yItnsLx1K8xdoQDYCcQ9I5KwaynaalUS
RnpBpYH4YiXoTipgIlIFtLSUFKwSBb/NtGCnb2Zl51fHo8hnhRZbSfCEKkgZkkcw
TgBgyVdxeQNRMNNMoMBOpBxFUSx+ObgYPgS1BBRss/jxxzwAqsbLRfwh1VJyF5WI
2AkIAIAAAiiUKMGMICDRXQIn6IiCW4Qs4NYZTByppBkbRAAAIf4ZQm95J3MgSGFw
cHkgSG9saWRheXMgUGFnZQA7
--related_boundary--
--alternative_boundary--
You can import that into Sylpheed or Thunderbird (with the Import/Export tools extension) or Opera's built-in mail client. Then, in Opera for example, you can toggle "prefer plain text" to see the difference between the HTML and text version. Anyway, you'll see the HTML version makes use of the embedded pic in the sig.
UPDATE: The Android Studio with NDK support is out now: http://tools.android.com/tech-docs/android-ndk-preview
For building with a script the gradle solution below should work:
I am using my build script and added to my file (Seems to work for 0.8+
): This seems to be equivalent to the solution below (but looks nicer in the gradle file):
android {
sourceSets {
main {
jniLibs.srcDirs = ['native-libs']
jni.srcDirs = [] //disable automatic ndk-build
}
}
}
The build unfortunately does not fail if the directory is not present or contains no .so
files.
./
refers to the current working directory, except in the require()
function. When using require()
, it translates ./
to the directory of the current file called. __dirname
is always the directory of the current file.
For example, with the following file structure
/home/user/dir/files/config.json
{
"hello": "world"
}
/home/user/dir/files/somefile.txt
text file
/home/user/dir/dir.js
var fs = require('fs');
console.log(require('./files/config.json'));
console.log(fs.readFileSync('./files/somefile.txt', 'utf8'));
If I cd
into /home/user/dir
and run node dir.js
I will get
{ hello: 'world' }
text file
But when I run the same script from /home/user/
I get
{ hello: 'world' }
Error: ENOENT, no such file or directory './files/somefile.txt'
at Object.openSync (fs.js:228:18)
at Object.readFileSync (fs.js:119:15)
at Object.<anonymous> (/home/user/dir/dir.js:4:16)
at Module._compile (module.js:432:26)
at Object..js (module.js:450:10)
at Module.load (module.js:351:31)
at Function._load (module.js:310:12)
at Array.0 (module.js:470:10)
at EventEmitter._tickCallback (node.js:192:40)
Using ./
worked with require
but not for fs.readFileSync
. That's because for fs.readFileSync
, ./
translates into the cwd (in this case /home/user/
). And /home/user/files/somefile.txt
does not exist.
db.collection.update( { _id:...} , { $set: { some_key : new_info } }
to
db.collection.update( { _id: ..} , { $set: { some_key: { param1: newValue} } } );
Hope this help!
I removed old AppleWWDRCA, downloaded and installed AppleWWDRCA, but problem remained. I also, checked my distribution and development certificates from Keychain Access, and see below error;
"This certificate has an invalid issuer."
Then,
This fixed certificate problem.
Since old certificates revoked, existing provisioning profiles become invalid. To fix this;
I hope this helps.
There is an input:focus as there is a textarea:focus
input:focus {
outline: none !important;
border-color: #719ECE;
box-shadow: 0 0 10px #719ECE;
}
textarea:focus {
outline: none !important;
border-color: #719ECE;
box-shadow: 0 0 10px #719ECE;
}
I am using the WLST tool that comes with weblogic, and it doesn't implement the platform package.
wls:/offline> import os
wls:/offline> print os.name
java
wls:/offline> import sys
wls:/offline> print sys.platform
'java1.5.0_11'
Apart from patching the system javaos.py (issue with os.system() on windows 2003 with jdk1.5) (which I can't do, I have to use weblogic out of the box), this is what I use:
def iswindows():
os = java.lang.System.getProperty( "os.name" )
return "win" in os.lower()
I noticed it myself, and found the files inside the backup folder. You can check where it is using Menu:Settings -> Preferences -> Backup. Note : My NPP installation is portable, and on Windows, so YMMV.
In german VS-Environments(here 2015): Optionen/Umgebung/Tastatur. (english: options/environment/keyboard). Show Commands With "GeheZuKlammer" (english: "GoToBracket"). Set your own Shortcut.
Measuring time in seconds:
from timeit import default_timer as timer
from datetime import timedelta
start = timer()
end = timer()
print(timedelta(seconds=end-start))
Output:
0:00:01.946339
In response to the comment from @poshest above, here is a React Native version of the Clock code previously posted in React (sorry, I was unable to comment on the section directly, otherwise I would have added the code there):
React Native code sample
import { AppRegistry } from 'react-native';
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
class Clock extends Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<View style={styles.container}>
<Text style={styles.sectionTitle}>Hello, world!</Text>
<Text style={styles.sectionDescription}>It is {this.state.date.toLocaleTimeString()}.</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: 'white',
flex: 1,
justifyContent: 'center',
},
sectionTitle: {
fontSize: 24,
fontWeight: '600',
color: 'black',
alignSelf: 'center',
},
sectionDescription: {
marginTop: 8,
fontSize: 18,
fontWeight: '400',
color: 'darkgrey',
alignSelf: 'center',
},
});
AppRegistry.registerComponent("clock", () => Clock);
Note that the styling is entirely my choice and does not seek to replicate directly the <h1>
and <h2>
tags used in the React code.
Percent encoding. Replace the hash with %23
.
You may group your library.available_until wheres area by grouping method of Codeigniter for without disable escaping where clauses.
$this->db
->select('*')
->from('library')
->where('library.rating >=', $form['slider'])
->where('library.votes >=', '1000')
->where('library.language !=', 'German')
->group_start() //this will start grouping
->where('library.available_until >=', date("Y-m-d H:i:s"))
->or_where('library.available_until =', "00-00-00 00:00:00")
->group_end() //this will end grouping
->where('library.release_year >=', $year_start)
->where('library.release_year <=', $year_end)
->join('rating_repo', 'library.id = rating_repo.id')
Reference: https://www.codeigniter.com/userguide3/database/query_builder.html#query-grouping
My reputation being too small to comment an answer, here is my feedback concerning roquen answer (using settings on xmlwriter to force the stream to close): it works perfectly and it made me save a lot of time. roquen's example requires some adjustment, here is the code that works on .NET framework 4.8 :
XmlWriterSettings settings = new XmlWriterSettings();
settings.CloseOutput = true;
writer = XmlWriter.Create(stream, settings);
OFFSET 10 ROWS -- skip 10 rows
FETCH NEXT 10 ROWS ONLY; -- take 10 rows
use this in the end of your select syntax. =)
The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:
pip install xlrd==1.2.0
2020 Benchmark in PHP 7.4
For these who are not satisfied with current answers, I did a little benchmark script, anyone can run from CLI.
We are going to compare two solutions:
unset() with array_values() VS array_splice().
<?php
echo 'php v' . phpversion() . "\n";
$itemsOne = [];
$itemsTwo = [];
// populate items array with 100k random strings
for ($i = 0; $i < 100000; $i++) {
$itemsOne[] = $itemsTwo[] = sha1(uniqid(true));
}
$start = microtime(true);
for ($i = 0; $i < 10000; $i++) {
unset($itemsOne[$i]);
$itemsOne = array_values($itemsOne);
}
$end = microtime(true);
echo 'unset & array_values: ' . ($end - $start) . 's' . "\n";
$start = microtime(true);
for ($i = 0; $i < 10000; $i++) {
array_splice($itemsTwo, $i, 1);
}
$end = microtime(true);
echo 'array_splice: ' . ($end - $start) . 's' . "\n";
As you can see the idea is simple:
Output of the script above on my Dell Latitude i7-6600U 2.60GHz x 4 and 15.5GiB RAM:
php v7.4.8
unset & array_values: 29.089932918549s
array_splice: 17.94264793396s
Verdict: array_splice is almost twice more performant than unset and array_values.
So: array_splice is the winner!
Step 1: Go to the download site from Gradle: https://gradle.org/releases/
Step 2: Extract the downloaded zip file into a directory.
Step 2: Hit Ctrl + Alt + S (mac: ? + ,) in Android studio/Intellij IDEA
Step 3: Goto: Build, Execution, Deployment >> Build Tools >> Gradle (Or just type in the searchbar Gradle)
Step 4: Select: (X) Use local gradle distribution and set Gradle home to your extracted Gradle directory. Click on apply.
Step 5: Get rid of your unnecessary gradle files delete:
- MyApp/gradle/
- gradlew
- gradlew.bat
Disclaimer: The following answer assumes that you are using the JavaScript environment of a web browser.
JavaScript handles XML with 'XML DOM objects'. You can obtain such an object in three ways:
1. Creating a new XML DOM object
var xmlDoc = document.implementation.createDocument(null, "books");
The first argument can contain the namespace URI of the document to be created, if the document belongs to one.
Source: https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument
2. Fetching an XML file with XMLHttpRequest
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var xmlDoc = xhttp.responseXML; //important to use responseXML here
}
xhttp.open("GET", "books.xml", true);
xhttp.send();
3. Parsing a string containing serialized XML
var xmlString = "<root></root>";
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlString, "text/xml"); //important to use "text/xml"
When you have obtained an XML DOM object, you can use methods to manipulate it like
var node = xmlDoc.createElement("heyHo");
var elements = xmlDoc.getElementsByTagName("root");
elements[0].appendChild(node);
For a full reference, see http://www.w3schools.com/xml/dom_intro.asp
Note: It is important, that you don't use the methods provided by the document namespace, i. e.
var node = document.createElement("Item");
This will create HTML nodes instead of XML nodes and will result in a node with lower-case tag names. XML tag names are case-sensitive in contrast to HTML tag names.
You can serialize XML DOM objects like this:
var serializer = new XMLSerializer();
var xmlString = serializer.serializeToString(xmlDoc);
It depends on what makes the most sense for your case.
Does it make sense to return null, e.g. "no such user exists"?
Or does it make sense to create a default user? This makes the most sense when you can safely assume that if a user DOESN'T exist, the calling code intends for one to exist when they ask for it.
Or does it make sense to throw an exception (a la "FileNotFound") if the calling code is demanding a user with an invalid ID?
However - from a separation of concerns/SRP standpoint, the first two are more correct. And technically the first is the most correct (but only by a hair) - GetUserById should only be responsible for one thing - getting the user. Handling its own "user does not exist" case by returning something else could be a violation of SRP. Separating into a different check - bool DoesUserExist(id)
would be appropriate if you do choose to throw an exception.
Based on extensive comments below: if this is an API-level design question, this method could be analogous to "OpenFile" or "ReadEntireFile". We are "opening" a user from some repository and hydrating the object from the resultant data. An exception could be appropriate in this case. It might not be, but it could be.
All approaches are acceptable - it just depends, based on the larger context of the API/application.
None of the above worked for me.
This happened to me after I added a new button to a toolstrip on a winform. When the button uses the default image of System.Drawing.Bitmap
(in image property) this error arose for me. After I changed it to a trusted image (one added to my resource file with 'Unlock' option checked) this error resolved itself.
I've done this kind of thing with a form that contains a TextBox.
So if you wanted to put this in say cell H1
, then use:
ActiveSheet.Range("H1").Value = txtBoxName.Text
# index dictionary by list of key names
def fn1():
print "One"
def fn2():
print "Two"
def fn3():
print "Three"
fndict = {"A": fn1, "B": fn2, "C": fn3}
keynames = ["A", "B", "C"]
fndict[keynames[1]]()
# keynames[1] = "B", so output of this code is
# Two
You can always load a json data
here i defined Chart as namespace
$.getJSON('data.json', function(data){
Chart.options.series[0].data = data[0].data;
Chart.options.series[1].data = data[1].data;
Chart.options.series[2].data = data[2].data;
var chart = new Highcharts.Chart(Chart.options);
});
It may be late to answer this question but I hope to document 2 good features from Pandas: pandas.Series.str.split()
with regular expression and pandas.Series.explode()
.
import pandas as pd
import numpy as np
df = pd.DataFrame(
{'CustNum': [32363, 31316],
'CustomerName': ['McCartney, Paul', 'Lennon, John'],
'ItemQty': [3, 25],
'Item': ['F04', 'F01'],
'Seatblocks': ['2:218:10:4,6', '1:13:36:1,12 1:13:37:1,13'],
'ItemExt': [60, 360]
}
)
print(df)
print('-'*80+'\n')
df['Seatblocks'] = df['Seatblocks'].str.split('[ :]')
df = df.explode('Seatblocks').reset_index(drop=True)
cols = list(df.columns)
cols.append(cols.pop(cols.index('CustomerName')))
df = df[cols]
print(df)
print('='*80+'\n')
print(df[df['CustomerName'] == 'Lennon, John'])
The output is:
CustNum CustomerName ItemQty Item Seatblocks ItemExt
0 32363 McCartney, Paul 3 F04 2:218:10:4,6 60
1 31316 Lennon, John 25 F01 1:13:36:1,12 1:13:37:1,13 360
--------------------------------------------------------------------------------
CustNum ItemQty Item Seatblocks ItemExt CustomerName
0 32363 3 F04 2 60 McCartney, Paul
1 32363 3 F04 218 60 McCartney, Paul
2 32363 3 F04 10 60 McCartney, Paul
3 32363 3 F04 4,6 60 McCartney, Paul
4 31316 25 F01 1 360 Lennon, John
5 31316 25 F01 13 360 Lennon, John
6 31316 25 F01 36 360 Lennon, John
7 31316 25 F01 1,12 360 Lennon, John
8 31316 25 F01 1 360 Lennon, John
9 31316 25 F01 13 360 Lennon, John
10 31316 25 F01 37 360 Lennon, John
11 31316 25 F01 1,13 360 Lennon, John
================================================================================
CustNum ItemQty Item Seatblocks ItemExt CustomerName
4 31316 25 F01 1 360 Lennon, John
5 31316 25 F01 13 360 Lennon, John
6 31316 25 F01 36 360 Lennon, John
7 31316 25 F01 1,12 360 Lennon, John
8 31316 25 F01 1 360 Lennon, John
9 31316 25 F01 13 360 Lennon, John
10 31316 25 F01 37 360 Lennon, John
11 31316 25 F01 1,13 360 Lennon, John
declare @testVal varchar(20)
set @testVal = '?t/es?ti/n*g 1*2?3*'
select @testVal = REPLACE(@testVal, item, '') from (select '?' item union select '*' union select '/') list
select @testVal;
The incorrect profile could be fixed by:
Note: This solution uses the Qt Library.
Here is a minimal example I have written in C++ in order to demonstrate how to implement the proposed solution:
QPixmap pixmap;
pixmap.load("badProfileImage.png");
QFile file("goodProfileImage.png");
file.open(QIODevice::WriteOnly);
pixmap.save(&file, "PNG");
The complete source code of a GUI application based on this example is available on GitHub.
UPDATE FROM 05.12.2019: The answer was and is still valid, however there was a bug in the GUI application I have shared on GitHub, causing the output image to be empty. I have just fixed it and apologise for the inconvenience!
I answered a similar question here
As @Syden said, the mixins will work. Another option is using SASS map-get
like this..
@media (min-width: map-get($grid-breakpoints, sm)){
.something {
padding: 10px;
}
}
@media (min-width: map-get($grid-breakpoints, md)){
.something {
padding: 20px;
}
}
http://www.codeply.com/go/0TU586QNlV
I was hanging out on Google, then I found your question and it's very simple to parse JSON response into normal HTML. Just use this little JavaScript code:
<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p id="demo"></p>
<script>
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
</script>
</body>
</html>
This pulls back client info as well.
var get = function(u){
var x = new XMLHttpRequest;
x.open('GET', u, false);
x.send();
return x.responseText;
}
JSON.parse(get('http://ifconfig.me/all.json'))
Ideally your .gitignore
should prevent the untracked ( and ignored )files from being shown in status, added using git add
etc. So I would ask you to correct your .gitignore
You can do git add -u
so that it will stage the modified and deleted files.
You can also do git commit -a
to commit only the modified and deleted files.
Note that if you have Git of version before 2.0 and used git add .
, then you would need to use git add -u .
(See "Difference of “git add -A
” and “git add .
”").
$date = date('h:i:s A', strtotime($today . " +10 hours"));
Many firewalls drop outbound connections which are not to ports 80 or 443 (http & https); some even drop connections to those ports that are not HTTP(S). FTP may or may not be allowed, not to speak of the active/PASV modes.
Also, HTTP/1.1 allows for much better partial requests ("only send from byte 123456 to the end of file"), conditional requests and caching ("only send if content changed/if last-modified-date changed") and content compression (gzip).
HTTP is much easier to use through a proxy.
From my anecdotal evidence, HTTP is easier to make work with dropped/slow/flaky connections; e.g. it is not needed to (re)establish a login session before (re)initiating transfer.
OTOH, HTTP is stateless, so you'd have to do authentication and building a trail of "who did what when" yourself.
The only difference in speed I've noticed is transferring lots of small files: HTTP with pipelining is faster (reduces round-trips, esp. noticeable on high-latency networks).
Note that HTTP/2 offers even more optimizations, whereas the FTP protocol has not seen any updates for decades (and even extensions to FTP have insignificant uptake by users). So, unless you are transferring files through a time machine, HTTP seems to have won.
(Tangentially: there are protocols that are better suited for file transfer, such as rsync
or BitTorrent, but those don't have as much mindshare, whereas HTTP is Everywhere™)
Quite simply the number is the precision of the timestamp, the fraction of a second held in the column:
SQL> create table t23
2 (ts0 timestamp(0)
3 , ts3 timestamp(3)
4 , ts6 timestamp(6)
5 )
6 /
Table created.
SQL> insert into t23 values (systimestamp, systimestamp, systimestamp)
2 /
1 row created.
SQL> select * from t23
2 /
TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM
SQL>
If we don't specify a precision then the timestamp defaults to six places.
SQL> alter table t23 add ts_def timestamp;
Table altered.
SQL> update t23
2 set ts_def = systimestamp
3 /
1 row updated.
SQL> select * from t23
2 /
TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
TS_DEF
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM
24-JAN-12 05.59.27.293305 AM
SQL>
Note that I'm running on Linux so my TIMESTAMP
column actually gives me precision to six places i.e. microseconds. This would also be the case on most (all?) flavours of Unix. On Windows the limit is three places i.e. milliseconds. (Is this still true of the most modern flavours of Windows - citation needed).
As might be expected, the documentation covers this. Find out more.
"when you create timestamp(9) this gives you nanos right"
Only if the OS supports it. As you can see, my OEL appliance does not:
SQL> alter table t23 add ts_nano timestamp(9)
2 /
Table altered.
SQL> update t23 set ts_nano = systimestamp(9)
2 /
1 row updated.
SQL> select * from t23
2 /
TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
TS_DEF
---------------------------------------------------------------------------
TS_NANO
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM
24-JAN-12 05.59.27.293305 AM
24-JAN-12 08.28.03.990557000 AM
SQL>
(Those trailing zeroes could be a coincidence but they aren't.)
readelf -d
recursion
redelf -d
produces similar output to objdump -p
which was mentioned at: https://stackoverflow.com/a/15520982/895245
But beware that dynamic libraries can depend on other dynamic libraries, to you have to recurse.
Example:
readelf -d /bin/ls | grep 'NEEDED'
Sample ouptut:
0x0000000000000001 (NEEDED) Shared library: [libselinux.so.1]
0x0000000000000001 (NEEDED) Shared library: [libacl.so.1]
0x0000000000000001 (NEEDED) Shared library: [libc.so.6]
Then:
$ locate libselinux.so.1
/lib/i386-linux-gnu/libselinux.so.1
/lib/x86_64-linux-gnu/libselinux.so.1
/mnt/debootstrap/lib/x86_64-linux-gnu/libselinux.so.1
Choose one, and repeat:
readelf -d /lib/x86_64-linux-gnu/libselinux.so.1 | grep 'NEEDED'
Sample output:
0x0000000000000001 (NEEDED) Shared library: [libpcre.so.3]
0x0000000000000001 (NEEDED) Shared library: [libdl.so.2]
0x0000000000000001 (NEEDED) Shared library: [libc.so.6]
0x0000000000000001 (NEEDED) Shared library: [ld-linux-x86-64.so.2]
And so on.
/proc/<pid>/maps
for running processes
This is useful to find all the libraries currently being used by running executables. E.g.:
sudo awk '/\.so/{print $6}' /proc/1/maps | sort -u
shows all currently loaded dynamic dependencies of init
(PID 1
):
/lib/x86_64-linux-gnu/ld-2.23.so
/lib/x86_64-linux-gnu/libapparmor.so.1.4.0
/lib/x86_64-linux-gnu/libaudit.so.1.0.0
/lib/x86_64-linux-gnu/libblkid.so.1.1.0
/lib/x86_64-linux-gnu/libc-2.23.so
/lib/x86_64-linux-gnu/libcap.so.2.24
/lib/x86_64-linux-gnu/libdl-2.23.so
/lib/x86_64-linux-gnu/libkmod.so.2.3.0
/lib/x86_64-linux-gnu/libmount.so.1.1.0
/lib/x86_64-linux-gnu/libpam.so.0.83.1
/lib/x86_64-linux-gnu/libpcre.so.3.13.2
/lib/x86_64-linux-gnu/libpthread-2.23.so
/lib/x86_64-linux-gnu/librt-2.23.so
/lib/x86_64-linux-gnu/libseccomp.so.2.2.3
/lib/x86_64-linux-gnu/libselinux.so.1
/lib/x86_64-linux-gnu/libuuid.so.1.3.0
This method also shows libraries opened with dlopen
, tested with this minimal setup hacked up with a sleep(1000)
on Ubuntu 18.04.
See also: https://superuser.com/questions/310199/see-currently-loaded-shared-objects-in-linux/1243089
SELECT group,subGroup,COUNT(*) FROM tablename GROUP BY group,subgroup
For ListBox / DropDown in MVC5 - i've found this to work for me sofar:
in Model:
[Required(ErrorMessage = "- Select item -")]
public List<string> SelectedItem { get; set; }
public List<SelectListItem> AvailableItemsList { get; set; }
in View:
@Html.ListBoxFor(model => model.SelectedItem, Model.AvailableItemsList)
@Html.ValidationMessageFor(model => model.SelectedItem, "", new { @class = "text-danger" })
Yes, this form of initialization is supported by all C++ compilers. It is a part of C++ language. In fact, it is an idiom that came to C++ from C language. In C language = { 0 }
is an idiomatic universal zero-initializer. This is also almost the case in C++.
Since this initalizer is universal, for bool
array you don't really need a different "syntax". 0
works as an initializer for bool
type as well, so
bool myBoolArray[ARRAY_SIZE] = { 0 };
is guaranteed to initialize the entire array with false
. As well as
char* myPtrArray[ARRAY_SIZE] = { 0 };
in guaranteed to initialize the whole array with null-pointers of type char *
.
If you believe it improves readability, you can certainly use
bool myBoolArray[ARRAY_SIZE] = { false };
char* myPtrArray[ARRAY_SIZE] = { nullptr };
but the point is that = { 0 }
variant gives you exactly the same result.
However, in C++ = { 0 }
might not work for all types, like enum types, for example, which cannot be initialized with integral 0
. But C++ supports the shorter form
T myArray[ARRAY_SIZE] = {};
i.e. just an empty pair of {}
. This will default-initialize an array of any type (assuming the elements allow default initialization), which means that for basic (scalar) types the entire array will be properly zero-initialized.
The accepted answer does not work for databases that have large numbers of tables, e.g. Drupal databases. Instead, see the script here: https://stackoverflow.com/a/12917793/1507877 which does work on MySQL 5.5. CAUTION: Around line 11, there is a "WHERE table_schema = SCHEMA();" This should instead be "WHERE table_schema = 'INSERT NAME OF DB INTO WHICH IMPORT WILL OCCUR';"
The "BIGINT(20)" specification isn't a digit limit. It just means that when the data is displayed, if it uses less than 20 digits it will be left-padded with zeros. 2^64 is the hard limit for the BIGINT type, and has 20 digits itself, hence BIGINT(20) just means everything less than 10^20 will be left-padded with spaces on display.
If ^\n
does not work properly ===> try .*[^\w]\n
Or just for a fast hack:
for line in to_read:
read_buffer = line
stripped_buffer1 = read_buffer.replace("term1", " ")
stripped_buffer2 = stripped_buffer1.replace("term2", " ")
write_to_file = to_write.write(stripped_buffer2)
You can use FitText.js (github page) to solve this problem. Is really small and efficient compared to TextFill. TextFill uses an expensive while loop and FitText don't.
Also FitText is more flexible (I use it in a proyect with very special requirements and works like a champ!).
HTML:
<div class="container">
<h1 id="responsive_headline">Your fancy title</h1>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="jquery.fittext.js"></script>
<script>
jQuery("#responsive_headline").fitText();
</script>
You also can set options to it:
<script>
jQuery("#responsive_headline").fitText(1, { minFontSize: '30px', maxFontSize: '90px'});
</script>
CSS:
#responsive_headline {
width: 100%;
display: block;
}
And if you need it, FitText also has a no-jQuery version.
Here are few pointers/suggestions for investigation
vote
method which creates a fresh HTTP connection.HttpClient
instance to post to the server. This way it wont create too many connections from the client side. HttpClient
needs to be shut and hence call httpclient.getConnectionManager().shutdown();
to release the resources used by the connections. I use in this case and it works :)
var pos = 0;
var sign = 0;
var zero = 0;
var neg = 0;
for( var i in arr ) {
sign = arr[i] > 0 ? 1 : arr[i] == 0 ? 0 : -1;
if (sign === 0) {
zero++;
} else if (sign === 1 ) {
pos++;
} else {
neg++;
}
}
For example: you populated your UIPickerView with array values, then you wanted
to select a certain array value in the first load of pickerView like "Arizona". Note that the word "Arizona" is at index 2. This how to do it :) Enjoy coding.
NSArray *countryArray =[NSArray arrayWithObjects:@"Alabama",@"Alaska",@"Arizona",@"Arkansas", nil];
UIPickerView *countryPicker=[[UIPickerView alloc]initWithFrame:self.view.bounds];
countryPicker.delegate=self;
countryPicker.dataSource=self;
[countryPicker selectRow:2 inComponent:0 animated:YES];
[self.view addSubview:countryPicker];
chmod 777 <directory>
this not change all ,just one file
chmod -R a+w <directory>
this ok
current working directory variable ie full path /home/dev/other
dir=$PWD
print the full path
echo $dir
The python code you write is compiled into python bytecode, which creates file with extension .pyc. If compiles, again question is, why not compiled language.
Note that this isn't compilation in the traditional sense of the word. Typically, we’d say that compilation is taking a high-level language and converting it to machine code. But it is a compilation of sorts. Compiled in to intermediate code not into machine code (Hope you got it Now).
Back to the execution process, your bytecode, present in pyc file, created in compilation step, is then executed by appropriate virtual machines, in our case, the CPython VM The time-stamp (called as magic number) is used to validate whether .py file is changed or not, depending on that new pyc file is created. If pyc is of current code then it simply skips compilation step.
Try to find out ID of your form element in generated aspx, and you can change target like...
getElementByID('theForm').target = '_blank' or 'myNewWindow'
Make sure you take into account that adding this tag,
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
may only allow compatibility with the latest versions. It all depends on your libraries
It should be:
ClientThread hey = clients.get(clients.size() - 1);
clients.remove(hey);
Or you can do
clients.remove(clients.size() - 1);
The minus ones are because size() returns the number of elements, but the ArrayList's first element's index is 0 and not 1.
int count = 0;
foreach (ListViewItem lvi in listView.Items)
{
if(++count > 50) break;
}
When using worker with -Q parameter to define queues, for example
celery worker -Q queue1,queue2,queue3
then celery purge
will not work, because you cannot pass the queue params to it. It will only delete the default queue.
The solution is to start your workers with --purge
parameter like this:
celery worker -Q queue1,queue2,queue3 --purge
This will however run the worker.
Other option is to use the amqp subcommand of celery
celery amqp queue.delete queue1
celery amqp queue.delete queue2
celery amqp queue.delete queue3
To upgrade Ruby with rbenv: Per the rbenv README
brew upgrade rbenv ruby-build
rbenv install -l
rbenv install <selected version>
For win7 chrome can be found at:
C:\Users\[UserName]\AppData\Local\Google\Chrome\Application\chrome.exe
For VS2017 click the little down arrow next to the run in debug/release mode button to find the "browse with..." option.
@Andrew and @CZFox
I had the same bug and found the cause to be that parameter one is in fact: http://www.example.com?param1
and not param1
which is what one would expect.
By removing all characters before and including the question mark fixes this problem. So in essence the HttpUtility.ParseQueryString
function only requires a valid query string parameter containing only characters after the question mark as in:
HttpUtility.ParseQueryString ( "param1=good¶m2=bad" )
My workaround:
string RawUrl = "http://www.example.com?param1=good¶m2=bad";
int index = RawUrl.IndexOf ( "?" );
if ( index > 0 )
RawUrl = RawUrl.Substring ( index ).Remove ( 0, 1 );
Uri myUri = new Uri( RawUrl, UriKind.RelativeOrAbsolute);
string param1 = HttpUtility.ParseQueryString( myUri.Query ).Get( "param1" );`
For Chart.js 2.x refer to andyhasit's answer - https://stackoverflow.com/a/36954319/360067
For Chart.js 1.x, you can tweak the options and extend the chart type to do this, like so
Chart.types.Line.extend({
name: "LineAlt",
draw: function () {
Chart.types.Line.prototype.draw.apply(this, arguments);
var ctx = this.chart.ctx;
ctx.save();
// text alignment and color
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
ctx.fillStyle = this.options.scaleFontColor;
// position
var x = this.scale.xScalePaddingLeft * 0.4;
var y = this.chart.height / 2;
// change origin
ctx.translate(x, y);
// rotate text
ctx.rotate(-90 * Math.PI / 180);
ctx.fillText(this.datasets[0].label, 0, 0);
ctx.restore();
}
});
calling it like this
var ctx = document.getElementById("myChart").getContext("2d");
var myLineChart = new Chart(ctx).LineAlt(data, {
// make enough space on the right side of the graph
scaleLabel: " <%=value%>"
});
Notice the space preceding the label value, this gives us space to write the y axis label without messing around with too much of Chart.js internals
Fiddle - http://jsfiddle.net/wyox23ga/
Try going to the Publish tab in the project properties and then select the Application Files button. Then set the following properties:
After that you need to republish your application.
If the reference has CopyLocal=true, then the reference will be published with the application. If the reference has CopyLocal=false then the reference will be marked as a prerequisite. This means the assembly must be installed in the client's GAC before the ClickOnce application will install.
There are some assemblies that are installed into the GAC because of the Visual Studio install, not the .NET Framework install. This could be your situation.
You should be able to remove it using
outline: none;
but keep in mind this is potentially bad for usability: It will be hard to tell whether an element is focused, which can suck when you walk through all a form's elements using the Tab key - you should reflect somehow when an element is focused.
Most likely the path you are trying to access does not exist. It seems you are trying to save to a relative location and you do not have an file extension in that string. If you need to use relative paths you can parse the path from ActiveWorkbook.FullName
EDIT: Better syntax would also be
ActiveWorkbook.SaveAs Filename:=myFileName, FileFormat:=xlWorkbookNormal
Maybe it can be useful to know that the bitwise AND and bitwise OR operators are always evaluated before conditional AND and conditional OR used in the same expression.
if ( (1>2) && (2>1) | true) // false!
Use accept attribute with the MIME_type as values
<input type="file" accept="image/gif, image/jpeg" />
var input_val=document.getElementById('my_variable');for (i=0; i<input_val.length; i++) {
xx = input_val[i];``
if (xx.name == "ans") {
new = xx.value;
alert(new); }}
// Javascript Countdown_x000D_
// Version 1.01 6/7/07 (1/20/2000)_x000D_
// by TDavid at http://www.tdscripts.com/_x000D_
var now = new Date();_x000D_
var theevent = new Date("Nov 13 2017 22:05:01");_x000D_
var seconds = (theevent - now) / 1000;_x000D_
var minutes = seconds / 60;_x000D_
var hours = minutes / 60;_x000D_
var days = hours / 24;_x000D_
ID = window.setTimeout("update();", 1000);_x000D_
_x000D_
function update() {_x000D_
now = new Date();_x000D_
seconds = (theevent - now) / 1000;_x000D_
seconds = Math.round(seconds);_x000D_
minutes = seconds / 60;_x000D_
minutes = Math.round(minutes);_x000D_
hours = minutes / 60;_x000D_
hours = Math.round(hours);_x000D_
days = hours / 24;_x000D_
days = Math.round(days);_x000D_
document.form1.days.value = days;_x000D_
document.form1.hours.value = hours;_x000D_
document.form1.minutes.value = minutes;_x000D_
document.form1.seconds.value = seconds;_x000D_
ID = window.setTimeout("update();", 1000);_x000D_
}
_x000D_
<p><font face="Arial" size="3">Countdown To January 31, 2000, at 12:00: </font>_x000D_
</p>_x000D_
<form name="form1">_x000D_
<p>Days_x000D_
<input type="text" name="days" value="0" size="3">Hours_x000D_
<input type="text" name="hours" value="0" size="4">Minutes_x000D_
<input type="text" name="minutes" value="0" size="7">Seconds_x000D_
<input type="text" name="seconds" value="0" size="7">_x000D_
</p>_x000D_
</form>
_x000D_
found = binarySearch(first, last, search4, &random);
Notice the &
.
Create a .reg file containing your proxy settings for your users. Create a batch file setting it to setting it to run the .reg file with the extension /s
On a server using a logon script, tell the logon to run the batch file. Jason
ls = [x if (condition) else None for x in ls]
I find git stash very useful for temporal handling of all 'dirty' states.
Use a Java 8 Stream
.
myString.chars().mapToObj(i -> (char) i).collect(Collectors.toList());
Breakdown:
myString
.chars() // Convert to an IntStream
.mapToObj(i -> (char) i) // Convert int to char, which gets boxed to Character
.collect(Collectors.toList()); // Collect in a List<Character>
(I have absolutely no idea why String#chars()
returns an IntStream
.)
Check if
str.charAt(str.length() -1) == ','
.
Then do
str = str.substring(0, str.length()-1)
This implementation is totally based on Sinaesthetic's, but adding CancellationToken
and keeping the same execution thread and context; that is, delegating the use of Task.Run()
up to the caller depending on whether condition
needs to be evaluated in the same thread or not.
Also, notice that, if you don't really need to throw a TimeoutException
and breaking the loop is enough, you might want to make use of cts.CancelAfter()
or new CancellationTokenSource(millisecondsDelay)
instead of using timeoutTask
with Task.Delay
plus Task.WhenAny
.
public static class AsyncUtils
{
/// <summary>
/// Blocks while condition is true or task is canceled.
/// </summary>
/// <param name="ct">
/// Cancellation token.
/// </param>
/// <param name="condition">
/// The condition that will perpetuate the block.
/// </param>
/// <param name="pollDelay">
/// The delay at which the condition will be polled, in milliseconds.
/// </param>
/// <returns>
/// <see cref="Task" />.
/// </returns>
public static async Task WaitWhileAsync(CancellationToken ct, Func<bool> condition, int pollDelay = 25)
{
try
{
while (condition())
{
await Task.Delay(pollDelay, ct).ConfigureAwait(true);
}
}
catch (TaskCanceledException)
{
// ignore: Task.Delay throws this exception when ct.IsCancellationRequested = true
// In this case, we only want to stop polling and finish this async Task.
}
}
/// <summary>
/// Blocks until condition is true or task is canceled.
/// </summary>
/// <param name="ct">
/// Cancellation token.
/// </param>
/// <param name="condition">
/// The condition that will perpetuate the block.
/// </param>
/// <param name="pollDelay">
/// The delay at which the condition will be polled, in milliseconds.
/// </param>
/// <returns>
/// <see cref="Task" />.
/// </returns>
public static async Task WaitUntilAsync(CancellationToken ct, Func<bool> condition, int pollDelay = 25)
{
try
{
while (!condition())
{
await Task.Delay(pollDelay, ct).ConfigureAwait(true);
}
}
catch (TaskCanceledException)
{
// ignore: Task.Delay throws this exception when ct.IsCancellationRequested = true
// In this case, we only want to stop polling and finish this async Task.
}
}
/// <summary>
/// Blocks while condition is true or timeout occurs.
/// </summary>
/// <param name="ct">
/// The cancellation token.
/// </param>
/// <param name="condition">
/// The condition that will perpetuate the block.
/// </param>
/// <param name="pollDelay">
/// The delay at which the condition will be polled, in milliseconds.
/// </param>
/// <param name="timeout">
/// Timeout in milliseconds.
/// </param>
/// <exception cref="TimeoutException">
/// Thrown after timeout milliseconds
/// </exception>
/// <returns>
/// <see cref="Task" />.
/// </returns>
public static async Task WaitWhileAsync(CancellationToken ct, Func<bool> condition, int pollDelay, int timeout)
{
if (ct.IsCancellationRequested)
{
return;
}
using (CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(ct))
{
Task waitTask = WaitWhileAsync(cts.Token, condition, pollDelay);
Task timeoutTask = Task.Delay(timeout, cts.Token);
Task finishedTask = await Task.WhenAny(waitTask, timeoutTask).ConfigureAwait(true);
if (!ct.IsCancellationRequested)
{
cts.Cancel(); // Cancel unfinished task
await finishedTask.ConfigureAwait(true); // Propagate exceptions
if (finishedTask == timeoutTask)
{
throw new TimeoutException();
}
}
}
}
/// <summary>
/// Blocks until condition is true or timeout occurs.
/// </summary>
/// <param name="ct">
/// Cancellation token
/// </param>
/// <param name="condition">
/// The condition that will perpetuate the block.
/// </param>
/// <param name="pollDelay">
/// The delay at which the condition will be polled, in milliseconds.
/// </param>
/// <param name="timeout">
/// Timeout in milliseconds.
/// </param>
/// <exception cref="TimeoutException">
/// Thrown after timeout milliseconds
/// </exception>
/// <returns>
/// <see cref="Task" />.
/// </returns>
public static async Task WaitUntilAsync(CancellationToken ct, Func<bool> condition, int pollDelay, int timeout)
{
if (ct.IsCancellationRequested)
{
return;
}
using (CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(ct))
{
Task waitTask = WaitUntilAsync(cts.Token, condition, pollDelay);
Task timeoutTask = Task.Delay(timeout, cts.Token);
Task finishedTask = await Task.WhenAny(waitTask, timeoutTask).ConfigureAwait(true);
if (!ct.IsCancellationRequested)
{
cts.Cancel(); // Cancel unfinished task
await finishedTask.ConfigureAwait(true); // Propagate exceptions
if (finishedTask == timeoutTask)
{
throw new TimeoutException();
}
}
}
}
}
You can do it by combining tr
and wc
commands. For example, to count e
in the string referee
echo "referee" | tr -cd 'e' | wc -c
output
4
Explanations: Command tr -cd 'e'
removes all characters other than 'e', and Command wc -c
counts the remaining characters.
Multiple lines of input are also good for this solution, like command cat mytext.txt | tr -cd 'e' | wc -c
can counts e
in the file mytext.txt
, even thought the file may contain many lines.
*** Update ***
To solve the multiple spaces in from of the number (@tom10271), simply append a piped tr command:
tr -d ' '
For example:
echo "referee" | tr -cd 'e' | wc -c | tr -d ' '
Python 2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.pi
3.141592653589793
Check out the Python tutorial on modules and how to use them.
As for the second part of your question, Python comes with batteries included, of course:
>>> math.radians(90)
1.5707963267948966
>>> math.radians(180)
3.141592653589793
Go to Start
→ Control Panel
→ System
→ Advanced system settings
→ advanced(tab)
→ Environment Variables
→ System Variables
→ New
:
Variable name: _JAVA_OPTIONS
Variable value: -Xmx512M
If you need this for < 5.6, I tripped across this UDF which seems to work fine:
let newQueue = DispatchQueue(label: "newname")
newQueue.sync {
// your code
}
Named instances?
URL: jdbc:sqlserver://[serverName][\instanceName][:portNumber][;property=value]
Note: backward slash
Reference link: http://www.programering.com/a/MTNyUDMwATA.html
Steps I followed
1) Execute the command adb nodaemon server
in command prompt
Output at command prompt will be: The following error occurred cannot bind 'tcp:5037'
The original ADB server port binding failed
2) Enter the following command query which using port 5037
netstat -ano | findstr "5037"
The following information will be prompted on command prompt: TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 9288
3) View the task manager, close all adb.exe
4) Restart eclipse or other IDE
The above steps worked for me.
You could set a margin for the table. Alternatively, wrap the table in a div and use the div's padding.
Please use chomp()
or chomp()
with STDIN
i.e. test1.rb
print 'Enter File name: '
fname = STDIN.gets.chomp() # or fname = gets.chomp()
fname_read = File.open(fname)
puts fname_read.read()
test.xml:
<?xml version="1.0" encoding="utf-8"?>
<Contacts>
<Node>
<ID>123</ID>
<Name>ABC</Name>
</Node>
<Node>
<ID>124</ID>
<Name>DEF</Name>
</Node>
</Contacts>
Select a single node:
XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123"; // id to be selected
XElement Contact = (from xml2 in XMLDoc.Descendants("Node")
where xml2.Element("ID").Value == id
select xml2).FirstOrDefault();
Console.WriteLine(Contact.ToString());
Delete a single node:
XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123";
var Contact = (from xml2 in XMLDoc.Descendants("Node")
where xml2.Element("ID").Value == id
select xml2).FirstOrDefault();
Contact.Remove();
XMLDoc.Save("test.xml");
Add new node:
XDocument XMLDoc = XDocument.Load("test.xml");
XElement newNode = new XElement("Node",
new XElement("ID", "500"),
new XElement("Name", "Whatever")
);
XMLDoc.Element("Contacts").Add(newNode);
XMLDoc.Save("test.xml");
For some reason, strtotime('next friday')
display the Friday date of the current week. Try this instead:
//Current date 2020-02-03
$fridayNextWeek = date('Y-m-d', strtotime('friday next week'); //Outputs 2020-02-14
$nextFriday = date('Y-m-d', strtotime('next friday'); //Outputs 2020-02-07
You can zip the two with something like this [like jQuery does]:
function toggleMyDiv() {
if (document.getElementById("myDiv").style.display=="block"){
document.getElementById("myDiv").style.display="none"
}
else{
document.getElementById("myDiv").style.display="block";
}
}
..and use the same function in the two buttons - or generally in the page for both functions.
Java has primitive types, objects and arrays and that's it. No typedefs.
using System.Net.NetworkInformation;
public static bool PingHost(string nameOrAddress)
{
bool pingable = false;
Ping pinger = null;
try
{
pinger = new Ping();
PingReply reply = pinger.Send(nameOrAddress);
pingable = reply.Status == IPStatus.Success;
}
catch (PingException)
{
// Discard PingExceptions and return false;
}
finally
{
if (pinger != null)
{
pinger.Dispose();
}
}
return pingable;
}
I don't know any way to do this directly in nano. However you can use "cat" or "grep" to display lines of your file in the console.
If you use a terminal multiplexer like "screen" you can copy and paste strings like this.
Javascript redirection generated with php code:
if($match > 0){
$msg = 'Login Complete! Thanks';
echo "<script> window.location.assign('index.php'); </script>";
}
else{
$msg = 'Login Failed!<br /> Please make sure that you enter the correct details and that you have activated your account.';
}
Php redirection only:
<?php
header("Location: index.php");
exit;
?>
An alternative approach is to set the width of the html element to 100vw. On many if not most browsers, this negates the effect of scrollbars on the width.
html { width: 100vw; }
please try below command : kubectl patch pod -p '{"metadata":{"finalizers":null}}'
What you actually created with:
MyType[] list = []
Was fixed size array (not list) with size of 0. You can create fixed size array of size for example 4 with:
MyType[] array = new MyType[4]
But there's no add method of course.
If you create list with def
it's something like creating this instance with Object
(You can read more about def
here). And []
creates empty ArrayList
in this case.
So using def list = []
you can then append new items with add()
method of ArrayList
list.add(new MyType())
Or more groovy way with overloaded left shift operator:
list << new MyType()
Surprisingly, all other answers only say half the truth or are actually wrong!
e.stopImmediatePropagation()
stops any further handler from being called for this event, no exceptionse.stopPropagation()
is similar, but does still call all handlers for this phase on this element if not called alreadyWhat phase?
E.g. a click event will always first go all the way down the DOM (called “capture phase”), finally reach the origin of the event (“target phase”) and then bubble up again (“bubble phase”). And with addEventListener()
you can register multiple handlers for both capture and bubble phase independently. (Target phase calls handlers of both types on the target without distinguishing.)
And this is what the other answers are incorrect about:
A fiddle and mozilla.org event phase explanation with demo.
The '\r'
character is the carriage return, and the carriage return-newline pair is both needed for newline in a network virtual terminal session.
From the old telnet specification (RFC 854) (page 11):
The sequence "CR LF", as defined, will cause the NVT to be positioned at the left margin of the next print line (as would, for example, the sequence "LF CR").
However, from the latest specification (RFC5198) (page 13):
...
In Net-ASCII, CR MUST NOT appear except when immediately followed by either NUL or LF, with the latter (CR LF) designating the "new line" function. Today and as specified above, CR should generally appear only when followed by LF. Because page layout is better done in other ways, because NUL has a special interpretation in some programming languages, and to avoid other types of confusion, CR NUL should preferably be avoided as specified above.
LF CR SHOULD NOT appear except as a side-effect of multiple CR LF sequences (e.g., CR LF CR LF).
So newline in Telnet should always be '\r\n'
but most implementations have either not been updated, or keeps the old '\n\r'
for backwards compatibility.
import json
weather = urllib2.urlopen('url')
wjson = weather.read()
wjdata = json.loads(wjson)
print wjdata['data']['current_condition'][0]['temp_C']
What you get from the url is a json string. And your can't parse it with index directly.
You should convert it to a dict by json.loads
and then you can parse it with index.
Instead of using .read()
to intermediately save it to memory and then read it to json
, allow json
to load it directly from the file:
wjdata = json.load(urllib2.urlopen('url'))
I got the same error and I changed my version from 4 to 3 and it is solved:
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<!-- Ensure correct version of MVC -->
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
First, array_length
should be an integer and not a string:
array_length = len(array_dates)
Second, your for
loop should be constructed using range
:
for i in range(array_length): # Use `xrange` for python 2.
Third, i
will increment automatically, so delete the following line:
i += 1
Note, one could also just zip
the two lists given that they have the same length:
import csv
dates = ['2020-01-01', '2020-01-02', '2020-01-03']
urls = ['www.abc.com', 'www.cnn.com', 'www.nbc.com']
csv_file_patch = '/path/to/filename.csv'
with open(csv_file_patch, 'w') as fout:
csv_file = csv.writer(fout, delimiter=';', lineterminator='\n')
result_array = zip(dates, urls)
csv_file.writerows(result_array)
Here is my solution in a recent project.
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
<title>Sample</title>_x000D_
</head>_x000D_
<body>_x000D_
<h1 id="hello_world">Sample</h1>_x000D_
<script type="text/javascript">_x000D_
var div = document.createElement("div");_x000D_
var t = document.createElement('template');_x000D_
t.innerHTML = "Check Console tab for javascript output: Hello world!!!<br/><script type='text/javascript' >console.log('Hello world!!!');<\/script>";_x000D_
_x000D_
for (var i=0; i < t.content.childNodes.length; i++){_x000D_
var node = document.importNode(t.content.childNodes[i], true);_x000D_
div.appendChild(node);_x000D_
}_x000D_
document.body.appendChild(div);_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
cd
without any parameters is equivalent to pwd
on Unix/Linux.
From the console output of typing cd /?
:
Displays the name of or changes the current directory.
[...]
Type CD without parameters to display the current drive and directory.
To get multiple stats, collapse the index, and retain column names:
df = df.groupby(['col1','col2']).agg(['mean', 'count'])
df.columns = [ ' '.join(str(i) for i in col) for col in df.columns]
df.reset_index(inplace=True)
df
Produces:
Speaking of boost:
auto ivec = boost::copy_range<std::vector<int>>(boost::irange(5, 10));
Header files needed:
#include <iostream>
#include <fstream>
declare input file stream:
ifstream in("in.txt");
declare output file stream:
ofstream out("out.txt");
if you want to use variable for a file name, instead of hardcoding it, use this:
string file_name = "my_file.txt";
ifstream in2(file_name.c_str());
reading from file into variables (assume file has 2 int variables in):
int num1,num2;
in >> num1 >> num2;
or, reading a line a time from file:
string line;
while(getline(in,line)){
//do something with the line
}
write variables back to the file:
out << num1 << num2;
close the files:
in.close();
out.close();
I had difficulty with this problem as well. I code mainly in Actionscript 3.0 which is base coding for the Adobe Flash Platform, but there are simularities in the Languages:
The solution I came up with is the following:
//Code for Rounding to the nearest 0.05
var r:Number = Math.random() * 10; // NUMBER - Input Your Number here
var n:int = r * 10; // INTEGER - Shift Decimal 2 places to right
var f:int = Math.round(r * 10 - n) * 5;// INTEGER - Test 1 or 0 then convert to 5
var d:Number = (n + (f / 10)) / 10; // NUMBER - Re-assemble the number
trace("ORG No: " + r);
trace("NEW No: " + d);
Thats pretty much it. Note the use of 'Numbers' and 'Integers' and the way they are processed.
Good Luck!
Without jQuery:
textContent:
var text = document.querySelector('.someClassname').textContent;
Markup:
var text = document.querySelector('.someClassname').innerHTML;
Markup including the matched element:
var text = document.querySelector('.someClassname').outerHTML;
though outerHTML may not be supported by all browsers of interest and document.querySelector requires IE 8 or higher.
It's better to avoid using unnecessary javascript. You can take advantage of the label tag to expand the click target of the input like so:
<label>
<input type="file" style="display: none;">
<a>Open</a>
</label>
Even though input is hidden, the link still works as a click target for it, and you can style it however you want.
There is a solution starting with KitKat (4.4.2), called Immersive Mode: https://developer.android.com/training/system-ui/immersive.html
Basically, you should add this code to your onResume() method:
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
As described in the various XML specifications, an element
is that which consists of a start tag, and end tag, and the content in between, or alternately an empty element tag (which has no content or end tag). In other words, these are all elements:
<foo> stuff </foo>
<foo bar="baz"></foo>
<foo baz="qux" />
Though you hear "node" used with roughly the same meaning, it has no precise definition per XML specs. It's usually used to refer to nodes of things like DOMs, which may be closely related to XML or use XML for their representation.
The answer from @zags is comprehensive and should suffice but the #5 method (which is the best one IMO) throws an error so I improved the helper function.
As the OP requested for converting many_to_many
fields into a list of primary keys rather than a list of objects, I enhanced the function so the return value is now JSON serializable - by converting datetime
objects into str
and many_to_many
objects to a list of id's.
import datetime
def ModelToDict(instance):
'''
Returns a dictionary object containing complete field-value pairs of the given instance
Convertion rules:
datetime.date --> str
many_to_many --> list of id's
'''
concrete_fields = instance._meta.concrete_fields
m2m_fields = instance._meta.many_to_many
data = {}
for field in concrete_fields:
key = field.name
value = field.value_from_object(instance)
if type(value) == datetime.datetime:
value = str(field.value_from_object(instance))
data[key] = value
for field in m2m_fields:
key = field.name
value = field.value_from_object(instance)
data[key] = [rel.id for rel in value]
return data
You can use, which will be triggered when the window resizes.
$( window ).bind("resize", function(){
// Change the width of the div
$("#yourdiv").width( 600 );
});
If you want a DIV width as percentage of the screen, just use CSS width : 80%;
.
I've encountered such issue recently. Though code was correct, I didn't turn on permissions in app settings. So, all permissions hasn't been set by default on emulators, so you should do it yourself.
It means "not equal to" (as in, the values in cells E37-N37 are not equal to ""
, or in other words, they are not empty.)
I had this issue while using RestAssured with JUnit. For me this programmatic approach worked:
@BeforeClass
public static void setUpClass() {
ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger("org.apache.http");
root.setLevel(ch.qos.logback.classic.Level.INFO);
//...
}
Since ng-show
is an angular attribute i think, we don't need to put the evaluation flower brackets ({{}}
)..
For attributes like class
we need to encapsulate the variables with evaluation flower brackets ({{}}
).
Your foldername is scripts
?
Change
<script src="../Script/login.js">
to
<script src='scripts/login.js' type='text/javascript'></script>
I am trying to do a robot to my little son and just play a Youtube video and than show a robot dancing.
For some reason, commands like CONTROL + T explained above was not working for me and maybe it is not the correct answer but I solved my problem using custom Javascript script like this:
using (var driver = new ChromeDriver())
{
var link1 = "https://www.youtube.com/watch?v=0GIgk4yuHOQ";
//open a music
driver.Navigate().GoToUrl(link1);
var link2 = "https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/fbe53d6d-c13f-4eec-9bcf-62f19cfab15a/d4m0h4v-9442b1f2-6a49-4818-8f51-5ebe216f043c.gif?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwic3ViIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsImF1ZCI6WyJ1cm46c2VydmljZTpmaWxlLmRvd25sb2FkIl0sIm9iaiI6W1t7InBhdGgiOiIvZi9mYmU1M2Q2ZC1jMTNmLTRlZWMtOWJjZi02MmYxOWNmYWIxNWEvZDRtMGg0di05NDQyYjFmMi02YTQ5LTQ4MTgtOGY1MS01ZWJlMjE2ZjA0M2MuZ2lmIn1dXX0.BTTlingNpBqH5O9dNVienFsArNqkfUc7KXnIgHumrBQ";
//Dance robot, dance
driver.ExecuteScript($"window.open('{link2}', '_blank');");
Thread.Sleep(20000);
}
Please try below code, I think this will solve your problem.
var classObj = new Class1();
classObj.Name => "StackOverflow";
var property = new Class1().GetType().GetProperty(nameof(classObj.Name));
var displayNameAttributeValue = (property ?? throw new InvalidOperationException())
.GetCustomAttributes(typeof(DisplayNameAttribute)) as DisplayNameAttribute;
if (displayNameAttributeValue != null)
{
Console.WriteLine("{0} = {1}", displayNameAttributeValue, classObj.Name);
}
why dont you add a "source" column to each of the queries with a static value like
select 'source 1' as Source, column1, column2...
from table1
UNION ALL
select 'source 2' as Source, column1, column2...
from table2
Generally the first 2 package "words" are your web address in reverse. (You'd have 3 here as convention, if you had a subdomain.)
So something stackoverflow produces would likely be in package com.stackoverflow.whatever.customname
something asp.net produces might be called net.asp.whatever.customname.omg.srsly
something from mysubdomain.toplevel.com would be com.toplevel.mysubdomain.whatever
Beyond that simple convention, the sky's the limit. This is an old linux convention for something that I cannot recall exactly...
In ES6, the includes()
method is used to determine whether one string may be found within another string, returning true
or false
as appropriate.
var str = 'To be, or not to be, that is the question.';
console.log(str.includes('To be')); // true
console.log(str.includes('question')); // true
console.log(str.includes('nonexistent')); // false
Here is jsperf between
var ret = str.includes('one');
And
var ret = (str.indexOf('one') !== -1);
As the result shown in jsperf, it seems both of them perform well.
Sometimes it is the simple things. In my case, I had an invalid url. I had left out a colon before the at sign (@). I had "jdbc:oracle:thin@//localhost" instead of "jdbc:oracle:thin:@//localhost" Hope this helps someone else with this issue.
If the number of elements in the array is not given, you can alternatively make use of list comprehension like:
str_arr = raw_input().split(' ') //will take in a string of numbers separated by a space
arr = [int(num) for num in str_arr]
You can use regular expressions.
String input = ...
if (input.matches("[^a-zA-Z0-9 ]"))
If your definition of a 'special character' is simply anything that doesn't apply to your other filters that you already have, then you can simply add an else
. Also note that you have to use else if
in this case:
if(c == ' ') {
blankCount++;
} else if (Character.isDigit(c)) {
digitCount++;
} else if (Character.isLetter(c)) {
letterCount++;
} else {
specialcharCount++;
}
You can merge, or you can apply individual commits across branches by using git cherry-pick.
There are many uses for the **null** value in the Boolean wrapper! :)
For example, you may have in a form a field named "newsletter" that indicate if the user want or doesn't want a newsletter from your site. If the user doesn't select a value in this field, you may want to implement a default behaviour to that situation (send? don't send?, question again?, etc) . Clearly, not set (or not selected or **null**), is not the same that true or false.
But, if "not set" doesn't apply to your model, don't change the boolean primitive ;)
Try:
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children:children...)
js-xlsx library makes it easy to convert Excel/CSV files into JSON objects.
Download the xlsx.full.min.js file from here. Write below code on your HTML page Edit the referenced js file link (xlsx.full.min.js) and link of Excel file
<!doctype html>
<html>
<head>
<title>Excel to JSON Demo</title>
<script src="xlsx.full.min.js"></script>
</head>
<body>
<script>
/* set up XMLHttpRequest */
var url = "http://myclassbook.org/wp-content/uploads/2017/12/Test.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
/* convert data to binary string */
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
/* Call XLSX */
var workbook = XLSX.read(bstr, {
type: "binary"
});
/* DO SOMETHING WITH workbook HERE */
var first_sheet_name = workbook.SheetNames[0];
/* Get worksheet */
var worksheet = workbook.Sheets[first_sheet_name];
console.log(XLSX.utils.sheet_to_json(worksheet, {
raw: true
}));
}
oReq.send();
</script>
</body>
</html>
Input:
Output:
In response to your postscript, that depends on what you would like.
You are getting (possible) multiple rows for each row in your left table because there are multiple matches for the join condition. If you want your total results to have the same number of rows as there is in the left part of the query you need to make sure your join conditions cause a 1-to-1 match.
Alternatively, depending on what you actually want you can use aggregate functions (if for example you just want a string from the right part you could generate a column that is a comma delimited string of the right side results for that left row.
If you are only looking at 1 or 2 columns from the outer join you might consider using a scalar subquery since you will be guaranteed 1 result.
I found a posting about Using the Windows Hosts File that also says "No wildcards are allowed."
In the past, I have just added the additional entries to the hosts file, because (as previously said), it's not that much extra work when you already are editing the apache config file.
variable
- named storage address. Every variable has a type which defines a memory size, attributes and behaviours. There are for types of Java variables: class variable
, instance variable
, local variable
, method parameter
//pattern
<Java_type> <name> ;
//for example
int myInt;
String myString;
CustomClass myCustomClass;
field
- member variable or data member. It is a variable
inside a class
(class variable
or instance variable
)
attribute
- in some articles you can find that attribute
it is an object
representation of class variable
. Object
operates by attributes
which define a set of characteristics.
CustomClass myCustomClass = new CustomClass();
myCustomClass.myAttribute = "poor fantasy"; //`myAttribute` is an attribute of `myCustomClass` object with a "poor fantasy" value
property
- field
+ bounded getter/setter
. It has a field syntax but uses methods under the hood. Java
does not support it in pure form. Take a look at Objective-C
, Swift
, Kotlin
For example Kotlin
sample:
//field - Backing Field
class Person {
var name: String = "default name"
get() = field
set(value) { field = value }
}
//using
val person = Person()
person.name = "Alex" // setter is used
println(person.name) // getter is used
You can try
grep -f file1 file2
or
grep -v -F -x -f file1 file2
Simply, to ignore white space as well:
if (str == null || str.trim().length() == 0) {
// str is empty
} else {
// str is not empty
}
If you want to print the last 10 lines, use
tail(dataset, 10)
for the first 10, you could also do
head(dataset, 10)
in swift ;)
UPDATE SWIFT 3.0 :D
func sFunc_imageFixOrientation(img:UIImage) -> UIImage {
// No-op if the orientation is already correct
if (img.imageOrientation == UIImageOrientation.up) {
return img;
}
// We need to calculate the proper transformation to make the image upright.
// We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
var transform:CGAffineTransform = CGAffineTransform.identity
if (img.imageOrientation == UIImageOrientation.down
|| img.imageOrientation == UIImageOrientation.downMirrored) {
transform = transform.translatedBy(x: img.size.width, y: img.size.height)
transform = transform.rotated(by: CGFloat(M_PI))
}
if (img.imageOrientation == UIImageOrientation.left
|| img.imageOrientation == UIImageOrientation.leftMirrored) {
transform = transform.translatedBy(x: img.size.width, y: 0)
transform = transform.rotated(by: CGFloat(M_PI_2))
}
if (img.imageOrientation == UIImageOrientation.right
|| img.imageOrientation == UIImageOrientation.rightMirrored) {
transform = transform.translatedBy(x: 0, y: img.size.height);
transform = transform.rotated(by: CGFloat(-M_PI_2));
}
if (img.imageOrientation == UIImageOrientation.upMirrored
|| img.imageOrientation == UIImageOrientation.downMirrored) {
transform = transform.translatedBy(x: img.size.width, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
}
if (img.imageOrientation == UIImageOrientation.leftMirrored
|| img.imageOrientation == UIImageOrientation.rightMirrored) {
transform = transform.translatedBy(x: img.size.height, y: 0);
transform = transform.scaledBy(x: -1, y: 1);
}
// Now we draw the underlying CGImage into a new context, applying the transform
// calculated above.
let ctx:CGContext = CGContext(data: nil, width: Int(img.size.width), height: Int(img.size.height),
bitsPerComponent: img.cgImage!.bitsPerComponent, bytesPerRow: 0,
space: img.cgImage!.colorSpace!,
bitmapInfo: img.cgImage!.bitmapInfo.rawValue)!
ctx.concatenate(transform)
if (img.imageOrientation == UIImageOrientation.left
|| img.imageOrientation == UIImageOrientation.leftMirrored
|| img.imageOrientation == UIImageOrientation.right
|| img.imageOrientation == UIImageOrientation.rightMirrored
) {
ctx.draw(img.cgImage!, in: CGRect(x:0,y:0,width:img.size.height,height:img.size.width))
} else {
ctx.draw(img.cgImage!, in: CGRect(x:0,y:0,width:img.size.width,height:img.size.height))
}
// And now we just create a new UIImage from the drawing context
let cgimg:CGImage = ctx.makeImage()!
let imgEnd:UIImage = UIImage(cgImage: cgimg)
return imgEnd
}
Add a mail header in the mail function:
$header = "From: [email protected]\r\n";
$header.= "MIME-Version: 1.0\r\n";
$header.= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$header.= "X-Priority: 1\r\n";
$status = mail($to, $subject, $message, $header);
if($status)
{
echo '<p>Your mail has been sent!</p>';
} else {
echo '<p>Something went wrong. Please try again!</p>';
}
SELECT *
FROM TABLE_NAME
WHERE Date_Column >= DATEADD(MONTH, -3, GETDATE())
Mureinik's suggested method will return the same results, but doing it this way your query can benefit from any indexes on Date_Column
.
or you can check against last 90 days.
SELECT *
FROM TABLE_NAME
WHERE Date_Column >= DATEADD(DAY, -90, GETDATE())
The List (unlike the Set) is an ordered collection and iterating over it does preserve the order by contract. I would have expected a Stack to iterate in the reverse order but unfortunately it doesn't. So the simplest solution I can think of is this:
for (int i = stack.size() - 1; i >= 0; i--) {
System.out.println(stack.get(i));
}
I realize that this is not a "for each" loop solution. I'd rather use the for loop than introducing a new library like the Google Collections.
Collections.reverse() also does the job but it updates the list as opposed to returning a copy in reverse order.
as simple as:
find . -mtime -1 | xargs tar --no-recursion -czf myfile.tgz
where find . -mtime -1
will select all the files in (recursively) current directory modified day before. you can use fractions, for example:
find . -mtime -1.5 | xargs tar --no-recursion -czf myfile.tgz
The transforms are SVG transforms (for details, have a look at the standard; here are some examples). Basically, scale and translate apply the respective transformations to the coordinate system, which should work as expected in most cases. You can apply more than one transform however (e.g. first scale and then translate) and then the result might not be what you expect.
When working with the transforms, keep in mind that they transform the coordinate system. In principle, what you say is true -- if you apply a scale > 1 to an object, it will look bigger and a translate will move it to a different position relative to the other objects.
Never do premature assumption as other application code and usage can impact your function. So looking at function is isolation is of no use.
If you are serious with application then VTune it or use any similar profiling tool and look at hotspots.
Ketan
list1 = sorted(csv1, key=lambda x: (x[1], x[2]) )
You should remove .Value
from all option buttons because option buttons don't hold the resultant value, the option group control does. If you omit .Value
then the default interface will report the option button status, as you are expecting. You should write all relevant code under commandbutton_click events because whenever the commandbutton is clicked the option button action will run.
If you want to run action code when the optionbutton is clicked then don't write an if loop for that.
EXAMPLE:
Sub CommandButton1_Click
If OptionButton1 = true then
(action code...)
End if
End sub
Sub OptionButton1_Click
(action code...)
End sub
Likely when you experience this issue, it is possible is a permission issue on your PC. Going to the PC properties and granting which ever account you use on your PC full control will solve it.
Again command /usr/local doesn't work on windows
You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);
, you just need to get rid of default sum(max_count)
. No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL
as the value for every cell in that column.
So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.
You also have the option to always COALESCE
the column to your desired default and leave it NULL
for now. This option fails when you want NULL
to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE
.
If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.
If you have a return value you need to send to the UI you can use the generic version like this:
This is being called from an MVVM ViewModel in my case.
var updateManifest = Task<ShippingManifest>.Run(() =>
{
Thread.Sleep(5000); // prove it's really working!
// GenerateManifest calls service and returns 'ShippingManifest' object
return GenerateManifest();
})
.ContinueWith(manifest =>
{
// MVVM property
this.ShippingManifest = manifest.Result;
// or if you are not using MVVM...
// txtShippingManifest.Text = manifest.Result.ToString();
System.Diagnostics.Debug.WriteLine("UI manifest updated - " + DateTime.Now);
}, TaskScheduler.FromCurrentSynchronizationContext());
Equal height columns is the default behaviour for Bootstrap 4 grids.
.col { background: red; }_x000D_
.col:nth-child(odd) { background: yellow; }
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col">_x000D_
1 of 3_x000D_
</div>_x000D_
<div class="col">_x000D_
1 of 3_x000D_
<br>_x000D_
Line 2_x000D_
<br>_x000D_
Line 3_x000D_
</div>_x000D_
<div class="col">_x000D_
1 of 3_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Easy way to convert base64 image into file and save as some random id or name.
// to create some random id or name for your image name
const imgname = new Date().getTime().toString();
// to declare some path to store your converted image
const path = yourpath.png
// image takes from body which you uploaded
const imgdata = req.body.image;
// to convert base64 format into random filename
const base64Data = imgdata.replace(/^data:([A-Za-z-+/]+);base64,/, '');
fs.writeFile(path, base64Data, 'base64', (err) => {
console.log(err);
});
// assigning converted image into your database
req.body.coverImage = imgname
This concise example demonstrates common way how to create custom tooltip in d3.
var w = 500;_x000D_
var h = 150;_x000D_
_x000D_
var dataset = [5, 10, 15, 20, 25];_x000D_
_x000D_
// firstly we create div element that we can use as_x000D_
// tooltip container, it have absolute position and_x000D_
// visibility: hidden by default_x000D_
_x000D_
var tooltip = d3.select("body")_x000D_
.append("div")_x000D_
.attr('class', 'tooltip');_x000D_
_x000D_
var svg = d3.select("body")_x000D_
.append("svg")_x000D_
.attr("width", w)_x000D_
.attr("height", h);_x000D_
_x000D_
// here we add some circles on the page_x000D_
_x000D_
var circles = svg.selectAll("circle")_x000D_
.data(dataset)_x000D_
.enter()_x000D_
.append("circle");_x000D_
_x000D_
circles.attr("cx", function(d, i) {_x000D_
return (i * 50) + 25;_x000D_
})_x000D_
.attr("cy", h / 2)_x000D_
.attr("r", function(d) {_x000D_
return d;_x000D_
})_x000D_
_x000D_
// we define "mouseover" handler, here we change tooltip_x000D_
// visibility to "visible" and add appropriate test_x000D_
_x000D_
.on("mouseover", function(d) {_x000D_
return tooltip.style("visibility", "visible").text('radius = ' + d);_x000D_
})_x000D_
_x000D_
// we move tooltip during of "mousemove"_x000D_
_x000D_
.on("mousemove", function() {_x000D_
return tooltip.style("top", (event.pageY - 30) + "px")_x000D_
.style("left", event.pageX + "px");_x000D_
})_x000D_
_x000D_
// we hide our tooltip on "mouseout"_x000D_
_x000D_
.on("mouseout", function() {_x000D_
return tooltip.style("visibility", "hidden");_x000D_
});
_x000D_
.tooltip {_x000D_
position: absolute;_x000D_
z-index: 10;_x000D_
visibility: hidden;_x000D_
background-color: lightblue;_x000D_
text-align: center;_x000D_
padding: 4px;_x000D_
border-radius: 4px;_x000D_
font-weight: bold;_x000D_
color: orange;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.min.js"></script>
_x000D_
You can remove a specific event handler that was attached by on
, using off
$("#ID").on ("eventName", additionalCss, handlerFunction);
// to remove the specific handler
$("#ID").off ("eventName", additionalCss, handlerFunction);
Using this, you will remove only handlerFunction
Another good practice, is to set a nameSpace for multiple attached events
$("#ID").on ("eventName1.nameSpace", additionalCss, handlerFunction1);
$("#ID").on ("eventName2.nameSpace", additionalCss, handlerFunction2);
// ...
$("#ID").on ("eventNameN.nameSpace", additionalCss, handlerFunctionN);
// and to remove handlerFunction from 1 to N, just use this
$("#ID").off(".nameSpace");
I had the same requirement to mount host directory from container and I used volume mount command. But during testing noticed that it's creating files inside container too but after some digging found that they are just symbolic links and actual file system used form host machine.
This wll work.
public class CryptoUtils {
private final String TRANSFORMATION = "AES";
private final String encodekey = "1234543444555666";
public String encrypt(String inputFile)
throws CryptoException {
return doEncrypt(encodekey, inputFile);
}
public String decrypt(String input)
throws CryptoException {
// return doCrypto(Cipher.DECRYPT_MODE, key, inputFile);
return doDecrypt(encodekey,input);
}
private String doEncrypt(String encodekey, String inputStr) throws CryptoException {
try {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
byte[] key = encodekey.getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] inputBytes = inputStr.getBytes();
byte[] outputBytes = cipher.doFinal(inputBytes);
return Base64Utils.encodeToString(outputBytes);
} catch (NoSuchPaddingException | NoSuchAlgorithmException
| InvalidKeyException | BadPaddingException
| IllegalBlockSizeException | IOException ex) {
throw new CryptoException("Error encrypting/decrypting file", ex);
}
}
public String doDecrypt(String encodekey,String encrptedStr) {
try {
Cipher dcipher = Cipher.getInstance(TRANSFORMATION);
dcipher = Cipher.getInstance("AES");
byte[] key = encodekey.getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
dcipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
// decode with base64 to get bytes
byte[] dec = Base64Utils.decode(encrptedStr.getBytes());
byte[] utf8 = dcipher.doFinal(dec);
// create new string based on the specified charset
return new String(utf8, "UTF8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Another solution is:
>>> "".join(list(hex(255))[2:])
'ff'
Probably an archaic answer, but functional.
It's not possible to configure an IIS managed handler to run in classic mode. You should be running IIS in integrated mode if you want to do that.
You can learn more about modules, handlers and IIS modes in the following blog post:
IIS 7.0, ASP.NET, pipelines, modules, handlers, and preconditions
For handlers, if you set preCondition="integratedMode" in the mapping, the handler will only run in integrated mode. On the other hand, if you set preCondition="classicMode" the handler will only run in classic mode. And if you omit both of these, the handler can run in both modes, although this is not possible for a managed handler.
Converting your value in milliseconds to days is simply (MsValue / 86,400,000)
We can get 1/1/1970 as numeric value by DATE(1970,1,1)
= (MsValueCellReference / 86400000) + DATE(1970,1,1)
Using your value of 1271664970687 and formatting it as dd/mm/yyyy hh:mm:ss
gives me a date and time of 19/04/2010 08:16:11
You need to create another migration file - and place it in there:
Run
Laravel 4: php artisan migrate:make rename_stnk_column
Laravel 5: php artisan make:migration rename_stnk_column
Then inside the new migration file place:
class RenameStnkColumn extends Migration
{
public function up()
{
Schema::table('stnk', function(Blueprint $table) {
$table->renameColumn('id', 'id_stnk');
});
}
public function down()
{
Schema::table('stnk', function(Blueprint $table) {
$table->renameColumn('id_stnk', 'id');
});
}
}
Take a look at
assert() example program in C++
Many compilers offer an assert() macro. The assert() macro returns TRUE if its parameter evaluates TRUE and takes some kind of action if it evaluates FALSE. Many compilers will abort the program on an assert() that fails; others will throw an exception
One powerful feature of the assert() macro is that the preprocessor collapses it into no code at all if DEBUG is not defined. It is a great help during development, and when the final product ships there is no performance penalty nor increase in the size of the executable version of the program.
Eg
#include <stdio.h>
#include <assert.h>
void analyze (char *, int);
int main(void)
{
char *string = "ABC";
int length = 3;
analyze(string, length);
printf("The string %s is not null or empty, "
"and has length %d \n", string, length);
}
void analyze(char *string, int length)
{
assert(string != NULL); /* cannot be NULL */
assert(*string != '\0'); /* cannot be empty */
assert(length > 0); /* must be positive */
}
/**************** Output should be similar to ******************
The string ABC is not null or empty, and has length 3
Not PIL, but scipy.misc.imread
might still be interesting:
import scipy.misc
im = scipy.misc.imread('um_000000.png', flatten=False, mode='RGB')
print(im.shape)
gives
(480, 640, 3)
so it is (height, width, channels). So you can iterate over it by
for y in range(im.shape[0]):
for x in range(im.shape[1]):
color = tuple(im[y][x])
r, g, b = color
This is far easier to check in Python (i.e. your view code) than in the template, because the Python code is simply:
myvar is False
Illustrating:
>>> False is False
True
>>> None is False
False
>>> [] is False
False
The problem at the template level is that the template if
doesn't parse is
(though it does parse in
). Also, if you don't mind it, you could try to patch support for is
into the template engine; base it on the code for ==
.
If you want to convert to integers only, another fast (and short) way is the double-bitwise not (i.e. using two tilde characters):
e.g.
~~x;
Reference: http://james.padolsey.com/cool-stuff/double-bitwise-not/
The 5 common ways I know so far to convert a string to a number all have their differences (there are more bitwise operators that work, but they all give the same result as ~~
). This JSFiddle shows the different results you can expect in the debug console: http://jsfiddle.net/TrueBlueAussie/j7x0q0e3/22/
var values = ["123",
undefined,
"not a number",
"123.45",
"1234 error",
"2147483648",
"4999999999"
];
for (var i = 0; i < values.length; i++){
var x = values[i];
console.log(x);
console.log(" Number(x) = " + Number(x));
console.log(" parseInt(x, 10) = " + parseInt(x, 10));
console.log(" parseFloat(x) = " + parseFloat(x));
console.log(" +x = " + +x);
console.log(" ~~x = " + ~~x);
}
123
Number(x) = 123
parseInt(x, 10) = 123
parseFloat(x) = 123
+x = 123
~~x = 123
undefined
Number(x) = NaN
parseInt(x, 10) = NaN
parseFloat(x) = NaN
+x = NaN
~~x = 0
null
Number(x) = 0
parseInt(x, 10) = NaN
parseFloat(x) = NaN
+x = 0
~~x = 0
"not a number"
Number(x) = NaN
parseInt(x, 10) = NaN
parseFloat(x) = NaN
+x = NaN
~~x = 0
123.45
Number(x) = 123.45
parseInt(x, 10) = 123
parseFloat(x) = 123.45
+x = 123.45
~~x = 123
1234 error
Number(x) = NaN
parseInt(x, 10) = 1234
parseFloat(x) = 1234
+x = NaN
~~x = 0
2147483648
Number(x) = 2147483648
parseInt(x, 10) = 2147483648
parseFloat(x) = 2147483648
+x = 2147483648
~~x = -2147483648
4999999999
Number(x) = 4999999999
parseInt(x, 10) = 4999999999
parseFloat(x) = 4999999999
+x = 4999999999
~~x = 705032703
The ~~x
version results in a number in "more" cases, where others often result in undefined
, but it fails for invalid input (e.g. it will return 0
if the string contains non-number characters after a valid number).
Please note: Integer overflow and/or bit truncation can occur with ~~
, but not the other conversions. While it is unusual to be entering such large values, you need to be aware of this. Example updated to include much larger values.
Some Perf tests indicate that the standard parseInt
and parseFloat
functions are actually the fastest options, presumably highly optimised by browsers, but it all depends on your requirement as all options are fast enough: http://jsperf.com/best-of-string-to-number-conversion/37
This all depends on how the perf tests are configured as some show parseInt/parseFloat to be much slower.
response.setContentType("application/json;charset=utf-8");
Answer of @S.A.Parkhid on kotlin.
class FileUtils @Inject constructor(private val context: Context) {
private var selection: String? = null
private var selectionArgs: Array<String>? = null
fun getFile(uri: Uri): File? {
val path = getPath(uri)
return if (path != null) {
File(path)
} else {
null
}
}
fun getPath(uri: Uri): String? {
// check here to KITKAT or new version
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getPathForKitKatAndAbove(uri)
} else {
getPathBelowKitKat(uri)
}
}
@SuppressLint("NewApi")
private fun handleExternalStorage(uri: Uri): String? {
val docId = DocumentsContract.getDocumentId(uri)
val split = docId.split(":".toRegex()).toTypedArray()
val fullPath = getPathFromExtSD(split)
return if (fullPath !== "") {
fullPath
} else {
null
}
}
@SuppressLint("NewApi")
private fun handleDownloads(uri: Uri): String? {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
handleDownloads23ApiAndAbove(uri)
} else {
handleDownloadsBelow23Api(uri)
}
return null
}
@SuppressLint("NewApi")
private fun handleDownloadsBelow23Api(uri: Uri): String? {
val id = DocumentsContract.getDocumentId(uri)
if (id.startsWith("raw:")) {
return id.replaceFirst("raw:".toRegex(), "")
}
var contentUri: Uri? = null
try {
contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), id.toLong()
)
} catch (e: NumberFormatException) {
log(e)
}
if (contentUri != null) {
return getDataColumn(contentUri)
}
return null
}
@SuppressLint("NewApi")
private fun handleDownloads23ApiAndAbove(uri: Uri): String? {
var cursor: Cursor? = null
try {
cursor = context.contentResolver
.query(uri, arrayOf(MediaStore.MediaColumns.DISPLAY_NAME), null, null, null)
if (cursor != null && cursor.moveToFirst()) {
val fileName = cursor.getString(0)
val path: String =
Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName
if (path.isNotEmpty()) {
return path
}
}
} finally {
cursor?.close()
}
val id: String = DocumentsContract.getDocumentId(uri)
if (id.isNotEmpty()) {
if (id.startsWith("raw:")) {
return id.replaceFirst("raw:".toRegex(), "")
}
val contentUriPrefixesToTry = arrayOf(
"content://downloads/public_downloads",
"content://downloads/my_downloads"
)
for (contentUriPrefix in contentUriPrefixesToTry) {
return try {
val contentUri = ContentUris.withAppendedId(
Uri.parse(contentUriPrefix),
id.toLong()
)
getDataColumn(contentUri)
} catch (e: NumberFormatException) {
//In Android 8 and Android P the id is not a number
uri.path.orEmpty().replaceFirst("^/document/raw:".toRegex(), "")
.replaceFirst("^raw:".toRegex(), "")
}
}
}
return null
}
@SuppressLint("NewApi")
private fun handleMedia(uri: Uri): String? {
val docId = DocumentsContract.getDocumentId(uri)
val split = docId.split(":".toRegex()).toTypedArray()
val contentUri: Uri? = when (split[0]) {
"image" -> {
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
}
"video" -> {
MediaStore.Video.Media.EXTERNAL_CONTENT_URI
}
"audio" -> {
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
}
else -> null
}
selection = "_id=?"
selectionArgs = arrayOf(split[1])
return if (contentUri != null) {
getDataColumn(contentUri)
} else {
null
}
}
private fun handleContentScheme(uri: Uri): String? {
if (isGooglePhotosUri(uri)) {
return uri.lastPathSegment
}
if (isGoogleDriveUri(uri)) {
return getDriveFilePath(uri)
}
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
copyFileToInternalStorage(uri, "userfiles")
} else {
getDataColumn(uri)
}
}
@SuppressLint("NewApi")
private fun getPathForKitKatAndAbove(uri: Uri): String? {
return when {
// ExternalStorageProvider
isExternalStorageDocument(uri) -> handleExternalStorage(uri)
// DownloadsProvider
isDownloadsDocument(uri) -> handleDownloads(uri)
// MediaProvider
isMediaDocument(uri) -> handleMedia(uri)
//GoogleDriveProvider
isGoogleDriveUri(uri) -> getDriveFilePath(uri)
//WhatsAppProvider
isWhatsAppFile(uri) -> getFilePathForWhatsApp(uri)
//ContentScheme
"content".equals(uri.scheme, ignoreCase = true) -> handleContentScheme(uri)
//FileScheme
"file".equals(uri.scheme, ignoreCase = true) -> uri.path
else -> null
}
}
private fun getPathBelowKitKat(uri: Uri): String? {
if (isWhatsAppFile(uri)) {
return getFilePathForWhatsApp(uri)
}
if ("content".equals(uri.scheme, ignoreCase = true)) {
val projection = arrayOf(
MediaStore.Images.Media.DATA
)
var cursor: Cursor? = null
try {
cursor = context.contentResolver
.query(uri, projection, selection, selectionArgs, null)
val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
if (cursor.moveToFirst()) {
return cursor.getString(columnIndex)
}
} catch (e: IOException) {
log(e)
} finally {
cursor?.close()
}
}
return null
}
private fun fileExists(filePath: String): Boolean {
val file = File(filePath)
return file.exists()
}
private fun getPathFromExtSD(pathData: Array<String>): String {
val type = pathData[0]
val relativePath = "/" + pathData[1]
var fullPath: String
// on my Sony devices (4.4.4 & 5.1.1), `type` is a dynamic string
// something like "71F8-2C0A", some kind of unique id per storage
// don't know any API that can get the root path of that storage based on its id.
//
// so no "primary" type, but let the check here for other devices
if ("primary".equals(type, ignoreCase = true)) {
fullPath = Environment.getExternalStorageDirectory().toString() + relativePath
if (fileExists(fullPath)) {
return fullPath
}
}
// Environment.isExternalStorageRemovable() is `true` for external and internal storage
// so we cannot relay on it.
//
// instead, for each possible path, check if file exists
// we'll start with secondary storage as this could be our (physically) removable sd card
fullPath = System.getenv("SECONDARY_STORAGE").orEmpty() + relativePath
if (fileExists(fullPath)) {
return fullPath
}
fullPath = System.getenv("EXTERNAL_STORAGE").orEmpty() + relativePath
return if (fileExists(fullPath)) {
fullPath
} else fullPath
}
private fun getDriveFilePath(uri: Uri): String? {
context.contentResolver.query(
uri, null, null, null, null
)?.use { cursor ->
/*
* Get the column indexes of the data in the Cursor,
* * move to the first row in the Cursor, get the data,
* * and display it.
* */
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
cursor.moveToFirst()
val name = cursor.getString(nameIndex)
val file = File(context.cacheDir, name)
try {
val inputStream = context.contentResolver.openInputStream(uri)!!
val outputStream = FileOutputStream(file)
val bytesAvailable = inputStream.available()
val bufferSize = min(bytesAvailable, MAX_BUFFER_SIZE)
val buffers = ByteArray(bufferSize)
var read: Int
while (inputStream.read(buffers).also { read = it } != -1) {
outputStream.write(buffers, 0, read)
}
inputStream.close()
outputStream.close()
} catch (e: IOException) {
log(e)
} finally {
cursor.close()
}
return file.path
}
return null
}
/***
* Used for Android Q+
* @param uri
* @param newDirName if you want to create a directory, you can set this variable
* @return
*/
private fun copyFileToInternalStorage(uri: Uri, newDirName: String): String? {
context.contentResolver.query(
uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null
)?.use { cursor ->
/*
* Get the column indexes of the data in the Cursor,
* * move to the first row in the Cursor, get the data,
* * and display it.
* */
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
cursor.moveToFirst()
val name = cursor.getString(nameIndex)
val output: File = if (newDirName != "") {
val dir = File(context.filesDir.toString() + "/" + newDirName)
if (!dir.exists()) {
dir.mkdir()
}
File(context.filesDir.toString() + "/" + newDirName + "/" + name)
} else {
File(context.filesDir.toString() + "/" + name)
}
try {
val inputStream = context.contentResolver.openInputStream(uri) ?: return null
val outputStream = FileOutputStream(output)
var read: Int
val buffers = ByteArray(BUFFER_SIZE)
while (inputStream.read(buffers).also { read = it } != -1) {
outputStream.write(buffers, 0, read)
}
inputStream.close()
outputStream.close()
} catch (e: IOException) {
log(e)
} finally {
cursor.close()
}
return output.path
}
return null
}
private fun getFilePathForWhatsApp(uri: Uri): String? {
return copyFileToInternalStorage(uri, "whatsapp")
}
private fun getDataColumn(uri: Uri): String? {
var cursor: Cursor? = null
val column = "_data"
val projection = arrayOf(column)
try {
cursor = context.contentResolver.query(
uri, projection,
selection, selectionArgs, null
)
if (cursor != null && cursor.moveToFirst()) {
val index = cursor.getColumnIndexOrThrow(column)
return cursor.getString(index)
}
} finally {
cursor?.close()
}
return null
}
private fun isExternalStorageDocument(uri: Uri): Boolean {
return EXTERNAL_STORAGE_CONTENT == uri.authority
}
private fun isDownloadsDocument(uri: Uri): Boolean {
return DOWNLOAD_DOCUMENT_CONTENT == uri.authority
}
private fun isMediaDocument(uri: Uri): Boolean {
return MEDIA_DOCUMENT_CONTENT == uri.authority
}
private fun isGooglePhotosUri(uri: Uri): Boolean {
return GOOGLE_PHOTOS_CONTENT == uri.authority
}
private fun isWhatsAppFile(uri: Uri): Boolean {
return WHATS_APP_CONTENT == uri.authority
}
private fun isGoogleDriveUri(uri: Uri): Boolean {
return GOOGLE_DRIVE_CONTENT == uri.authority || "com.google.android.apps.docs.storage.legacy" == uri.authority
}
companion object {
private const val BUFFER_SIZE = 1024
private const val MAX_BUFFER_SIZE = 1024 * 1024
private const val GOOGLE_DRIVE_CONTENT = "com.google.android.apps.docs.storage"
private const val WHATS_APP_CONTENT = "com.whatsapp.provider.media"
private const val GOOGLE_PHOTOS_CONTENT = "com.google.android.apps.photos.content"
private const val MEDIA_DOCUMENT_CONTENT = "com.android.providers.media.documents"
private const val DOWNLOAD_DOCUMENT_CONTENT = "com.android.providers.downloads.documents"
private const val EXTERNAL_STORAGE_CONTENT = "com.android.externalstorage.documents"
}
}
Use all()
method - it's designed to return items of Collection:
/**
* Get all of the items in the collection.
*
* @return array
*/
public function all()
{
return $this->items;
}
I learned that depth and height are properties of a node:
The depth of a node is the number of edges from the node to the tree's root node.
A root node will have a depth of 0.
The height of a node is the number of edges on the longest path from the node to a leaf.
A leaf node will have a height of 0.
Properties of a tree:
The height of a tree would be the height of its root node,
or equivalently, the depth of its deepest node.
The diameter (or width) of a tree is the number of nodes on the longest path between any two leaf nodes. The tree below has a diameter of 6 nodes.
In JSFiddle, when you set the wrapping to "onLoad" or "onDomready", the functions you define are only defined inside that block, and cannot be accessed by outside event handlers.
Easiest fix is to change:
function something(...)
To:
window.something = function(...)
I faced the same issue but, in my case, I had only to point my project to a JDK instead of the JRE in the build path then it solved the issue and I was able to import all maven dependencies with no problem!
subdate(now(),1) will return yesterdays timestamp The below code will select all rows with yesterday's timestamp
Select * FROM `login` WHERE `dattime` <= subdate(now(),1) AND `dattime` > subdate(now(),2)
From the Vimeo Simple API docs:
Making a Video Request
To get data about a specific video, use the following url:
http://vimeo.com/api/v2/video/video_id.output
video_id The ID of the video you want information for.
output Specify the output type. We currently offer JSON, PHP, and XML formats.
So getting this URL http://vimeo.com/api/v2/video/6271487.xml
<videos>
<video>
[skipped]
<thumbnail_small>http://ts.vimeo.com.s3.amazonaws.com/235/662/23566238_100.jpg</thumbnail_small>
<thumbnail_medium>http://ts.vimeo.com.s3.amazonaws.com/235/662/23566238_200.jpg</thumbnail_medium>
<thumbnail_large>http://ts.vimeo.com.s3.amazonaws.com/235/662/23566238_640.jpg</thumbnail_large>
[skipped]
</videos>
Parse this for every video to get the thumbnail
Here's approximate code in PHP
<?php
$imgid = 6271487;
$hash = unserialize(file_get_contents("http://vimeo.com/api/v2/video/$imgid.php"));
echo $hash[0]['thumbnail_medium'];
I believe you're looking for the @filename
syntax, e.g.:
strip new lines
curl --data "@/path/to/filename" http://...
keep new lines
curl --data-binary "@/path/to/filename" http://...
curl will strip all newlines from the file. If you want to send the file with newlines intact, use --data-binary
in place of --data
The best way to do it is:
String path = "C:" + File.separator + "hello" + File.separator + "hi.txt";
// Use relative path for Unix systems
File f = new File(path);
f.getParentFile().mkdirs();
f.createNewFile();
Nothing I've seen anywhere indicates you can ad-hoc deploy to a real iPhone without a (paid for) certificate.
from django.http import JsonResponse
def SomeFunction(): dict1 = {}
obj = list( Mymodel.objects.values() )
dict1['data']=obj
return JsonResponse(dict1)
Try this code for Django
Based on some other answers, but this one will reject programs with illegal binary literals. Leading zeroes are optional.
template<bool> struct BinaryLiteralDigit;
template<> struct BinaryLiteralDigit<true> {
static bool const value = true;
};
template<unsigned long long int OCT, unsigned long long int HEX>
struct BinaryLiteral {
enum {
value = (BinaryLiteralDigit<(OCT%8 < 2)>::value && BinaryLiteralDigit<(HEX >= 0)>::value
? (OCT%8) + (BinaryLiteral<OCT/8, 0>::value << 1)
: -1)
};
};
template<>
struct BinaryLiteral<0, 0> {
enum {
value = 0
};
};
#define BINARY_LITERAL(n) BinaryLiteral<0##n##LU, 0x##n##LU>::value
Example:
#define B BINARY_LITERAL
#define COMPILE_ERRORS 0
int main (int argc, char ** argv) {
int _0s[] = { 0, B(0), B(00), B(000) };
int _1s[] = { 1, B(1), B(01), B(001) };
int _2s[] = { 2, B(10), B(010), B(0010) };
int _3s[] = { 3, B(11), B(011), B(0011) };
int _4s[] = { 4, B(100), B(0100), B(00100) };
int neg8s[] = { -8, -B(1000) };
#if COMPILE_ERRORS
int errors[] = { B(-1), B(2), B(9), B(1234567) };
#endif
return 0;
}
A relative URL without a scheme (http: or https:) is valid, per RFC 3986: "Uniform Resource Identifier (URI): Generic Syntax", Section 4.2. If a client chokes on it, then it's the client's fault because they're not complying with the URI syntax specified in the RFC.
Your example is valid and should work. I've used that relative URL method myself on heavily trafficked sites and have had zero complaints. Also, we test our sites in Firefox, Safari, IE6, IE7 and Opera. These browsers all understand that URL format.
I have got same issue on my server. Follow below steps -
It works and solved my problem.
You can parse the geolocation through the addresses. Create an Array with jquery like this:
//follow this structure
var addressesArray = [
'Address Str.No, Postal Area/city'
]
//loop all the addresses and call a marker for each one
for (var x = 0; x < addressesArray.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addressesArray[x]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
//it will place marker based on the addresses, which they will be translated as geolocations.
var aMarker= new google.maps.Marker({
position: latlng,
map: map
});
});
}
Also please note that Google limit your results if you don't have a business account with them, and you my get an error if you use too many addresses.
In awk, FNR
refers to the record number (typically the line number) in the current file and NR
refers to the total record number. The operator ==
is a comparison operator, which returns true when the two surrounding operands are equal.
This means that the condition NR==FNR
is only true for the first file, as FNR
resets back to 1 for the first line of each file but NR
keeps on increasing.
This pattern is typically used to perform actions on only the first file. The next
inside the block means any further commands are skipped, so they are only run on files other than the first.
The condition FNR==NR
compares the same two operands as NR==FNR
, so it behaves in the same way.
So you should be able to do:
Whatever.declaredMethods
.find { it.name == 'aMethod' }
.parameters
.collect { "$it.type : $it.name" }
But you'll probably get a list like so:
["int : arg0"]
I believe this will be fixed in Groovy 2.5+
So currently, the answer is:
See also:
For every method, then something like:
Whatever.declaredMethods
.findAll { !it.synthetic }
.collect { method ->
println method
method.name + " -> " + method.parameters.collect { "[$it.type : $it.name]" }.join(';')
}
.each {
println it
}
Using the FM
format model modifier to get close, as you won't get the trailing zeros after the decimal separator; but you will still get the separator itself, e.g. 50.
. You can use rtrim
to get rid of that:
select to_char(a, '99D90'),
to_char(a, '90D90'),
to_char(a, 'FM90D99'),
rtrim(to_char(a, 'FM90D99'), to_char(0, 'D'))
from (
select 50 a from dual
union all select 50.57 from dual
union all select 5.57 from dual
union all select 0.35 from dual
union all select 0.4 from dual
)
order by a;
TO_CHA TO_CHA TO_CHA RTRIM(
------ ------ ------ ------
.35 0.35 0.35 0.35
.40 0.40 0.4 0.4
5.57 5.57 5.57 5.57
50.00 50.00 50. 50
50.57 50.57 50.57 50.57
Note that I'm using to_char(0, 'D')
to generate the character to trim, to match the decimal separator - so it looks for the same character, ,
or .
, as the first to_char
adds.
The slight downside is that you lose the alignment. If this is being used elsewhere it might not matter, but it does then you can also wrap it in an lpad
, which starts to make it look a bit complicated:
...
lpad(rtrim(to_char(a, 'FM90D99'), to_char(0, 'D')), 6)
...
TO_CHA TO_CHA TO_CHA RTRIM( LPAD(RTRIM(TO_CHAR(A,'FM
------ ------ ------ ------ ------------------------
.35 0.35 0.35 0.35 0.35
.40 0.40 0.4 0.4 0.4
5.57 5.57 5.57 5.57 5.57
50.00 50.00 50. 50 50
50.57 50.57 50.57 50.57 50.57
All of these answers are really great for moving data! Where they fail is preserving the column type of data being moved. This becomes a problem when you want to do things like merge datatables that appear to be the same. JsonConvert
will look at the first row of data to determine the column datatype, which may be guessed incorrectly.
To get around this;
DataTable
and DataColumn
definitions in separate response objects.DataColumn
definitions in the response before reading in the table.DataTable
ignoring the schema defined by Json.It sounds like a lot, but its only three additional lines of code.
// Get our Column definitions and serialize them using an anoymous function.
var columns = dt.Columns.Cast<DataColumn>().Select(c => new { DataPropertyName = c.ColumnName, DataPropertyType = c.DataType.ToString()});
resp.ObjSchema = JsonConvert.SerializeObject(columns);
resp.Obj = JsonConvert.SerializeObject(dt);
resp.ObjSchema
becomes;
[
{
"DataPropertyName": "RowId",
"DataPropertyType ": "System.Int32"
},
{
"DataPropertyName": "ItemName",
"DataPropertyType ": "System.String"
}
]
Instead of letting Json define the column definitions via dt = JsonConvert.DeserializeObject<DataTable>(response)
we can use LINQ on our resp.ObjSchema
to define them ourselves. We'll use MissingSchemaAction.Ignore
to ignore the schema provided by Json.
// If your environment does not support dynamic you'll need to create a class for with DataPropertyName and DataPropertyType.
JsonConvert.DeserializeObject<List<dynamic>>(response.ObjSchema).ForEach(prop =>
{
dt.Columns.Add(new DataColumn() { ColumnName = prop.DataPropertyName, DataType = Type.GetType(prop.DataPropertyType.ToString()) });
});
// Merge the results ignoring the JSON schema.
dt.Merge(JsonConvert.DeserializeObject<DataTable>(response.Obj), true, MissingSchemaAction.Ignore);
As per PEP-20 by Tim Peters, "Explicit is better than implicit" and "Readability counts". If all you need from the os
module is under os.path
, import os.path
would be more explicit and let others know what you really care about.
Likewise, PEP-20 also says "Simple is better than complex", so if you also need stuff that resides under the more-general os
umbrella, import os
would be preferred.
Below command will work in command prompt:
copy c:\folder\file.ext \\dest-machine\destfolder /Z /Y
To Copy all files:
copy c:\folder\*.* \\dest-machine\destfolder /Z /Y
You can use the following script to dynamically traverse through your variable, no matter how many fields it has as long as it is only comma separated.
variable=abc,def,ghij
for i in $(echo $variable | sed "s/,/ /g")
do
# call your procedure/other scripts here below
echo "$i"
done
Instead of the echo "$i"
call above, between the do
and done
inside the for loop, you can invoke your procedure proc "$i"
.
Update: The above snippet works if the value of variable does not contain spaces. If you have such a requirement, please use one of the solutions that can change IFS
and then parse your variable.
Hope this helps.
For Visual Studio 2019 (Preview, at least) it is now in:
C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\MSBuild\Current\Bin\MSBuild.exe
I imagine the process will be similar for the official 2019 release.
Eulerian path must visit each edge exactly once, while Hamiltonian path must visit each vertex exactly once.
I wanted to work in VSO/TFS, then push publicly to GitHub when ready. Initial repo created in private VSO. When it came time to add to GitHub I did:
git remote add mygithubrepo https://github.com/jhealy/kinect2.git
git push -f mygithubrepo master
Worked like a champ...
For a sanity check, issue "git remote -v" to list the repositories associated with a project.
C:\dev\kinect\vso-repo-k2work\FaceNSkinWPF>git remote -v
githubrepo https://github.com/jhealy/kinect2.git (fetch)
githubrepo https://github.com/jhealy/kinect2.git (push)
origin https://devfish.visualstudio.com/DefaultCollection/_git/Kinect2Work (fetch)
origin https://devfish.visualstudio.com/DefaultCollection/_git/Kinect2Work (push)
Simple way, worked for me... Hope this helps someone.
You could use the built-in exec statement, eg.:
exec("try: \n \t if sam[0] != 'harry': \n \t\t print('hello', sam) \nexcept: pass")
Where \n
is a newline and \t
is used as indentation (a tab).
Also, you should count the spaces you use, so your indentation matches exactly.
However, as all the other answers already said, this is of course only to be used when you really have to put it on one line.
exec
is quite a dangerous statement (especially when building a webapp) since it allows execution of arbitrary Python code.
Returning 0 should tell the programmer that the program has successfully finished the job.
After some testing with an icon with 8, 16, 20, 24, 32, 40, 48, 64, 96, 128 and 256 pixels (256 in PNG) in Windows 7:
So 8, 32 were never used (it's strange to me for 32) and 128 only by Windows Photo Viewer with a very high dpi screen, i.e. almot never used.
It means your icon should at least provide 16, 48 and 256 for Windows 7. For supporting newer screens with high resolutions, you should provide 16, 20, 24, 40, 48, 64, 96, and 256. For Windows 7, all pictures can be compressed using PNG but for backward compatibility with Windows XP, 16 to 48 should not be compressed.
The ability to search commits has recently been added to GitHub.
To search for a hash, just enter at least the first 7 characters in the search box. Then on the results page, click the "Commits" tab to see matching commits (but only on the default branch, usually master
), or the "Issues" tab to see pull requests containing the commit.
To be more explicit you can add the hash:
prefix to the search, but it's not really necessary.
There is also a REST API (at the time of writing it is still in preview).
Follow these Steps Restore your "Default Website" Website :
The shortest answer is
Please try this.
<switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/shop" component={Shop} />
</switch>
To answer that question, I'd like to describe member's accessors first in my own words. If you already know this, skip to the heading "next:".
There are three accessors that I'm aware of: public
, protected
and private
.
Let:
class Base {
public:
int publicMember;
protected:
int protectedMember;
private:
int privateMember;
};
Base
is also aware that Base
contains publicMember
.Base
contains protectedMember
.Base
is aware of privateMember
.By "is aware of", I mean "acknowledge the existence of, and thus be able to access".
The same happens with public, private and protected inheritance. Let's consider a class Base
and a class Child
that inherits from Base
.
public
, everything that is aware of Base
and Child
is also aware that Child
inherits from Base
.protected
, only Child
, and its children, are aware that they inherit from Base
.private
, no one other than Child
is aware of the inheritance.I was using .NET Framework 4.5 but my new library had .NET Framework 4.5.2 and I got the same issue when I tried to build. I solved it by updating my project from 4.5 to 4.5.2 (same as my library).
Use the jQuery hashchange event plugin instead. Regarding your full ajax navigation, try to have SEO friendly ajax. Otherwise your pages shown nothing in browsers with JavaScript limitations.
No, prior to Oracle version 12.2, identifiers are not allowed to exceed 30 characters in length. See the Oracle SQL Language Reference.
However, from version 12.2 they can be up to 128 bytes long. (Note: bytes, not characters).