https://www.ripe.net/internet-coordination/press-centre/understanding-ip-addressing
For IPv4, this pool is 32-bits (2³²) in size and contains 4,294,967,296 IPv4 addresses.
In case of IPv6
The IPv6 address space is 128-bits (2¹²8) in size, containing 340,282,366,920,938,463,463,374,607,431,768,211,456 IPv6 addresses.
inclusive of RESERVED IP
Reserved address blocks
Range Description Reference
0.0.0.0/8 Current network (only valid as source address) RFC 6890
10.0.0.0/8 Private network RFC 1918
100.64.0.0/10 Shared Address Space RFC 6598
127.0.0.0/8 Loopback RFC 6890
169.254.0.0/16 Link-local RFC 3927
172.16.0.0/12 Private network RFC 1918
192.0.0.0/24 IETF Protocol Assignments RFC 6890
192.0.2.0/24 TEST-NET-1, documentation and examples RFC 5737
192.88.99.0/24 IPv6 to IPv4 relay (includes 2002::/16) RFC 3068
192.168.0.0/16 Private network RFC 1918
198.18.0.0/15 Network benchmark tests RFC 2544
198.51.100.0/24 TEST-NET-2, documentation and examples RFC 5737
203.0.113.0/24 TEST-NET-3, documentation and examples RFC 5737
224.0.0.0/4 IP multicast (former Class D network) RFC 5771
240.0.0.0/4 Reserved (former Class E network) RFC 1700
255.255.255.255 Broadcast RFC 919
::1
is the loopback address in IPv6.
Within a URL, use square brackets []
:
http://[::1]/
http://[::1]:80/
Enclosing the IPv6 literal in square brackets for use in a URL is defined in RFC 2732 – Format for Literal IPv6 Addresses in URL's.
For number from 0 to 255 I use this regex:
(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))
Above regex will match integer number from 0 to 255, but not match 256.
So for IPv4 I use this regex:
^(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))((\.(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))){3})$
It is in this structure: ^(N)((\.(N)){3})$
where N is the regex used to match number from 0 to 255.
This regex will match IP like below:
0.0.0.0
192.168.1.2
but not those below:
10.1.0.256
1.2.3.
127.0.1-2.3
For IPv4 CIDR (Classless Inter-Domain Routing) I use this regex:
^(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))((\.(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))){3})\/(([0-9])|([12][0-9])|(3[0-2]))$
It is in this structure: ^(N)((\.(N)){3})\/M$
where N is the regex used to match number from 0 to 255, and M is the regex used to match number from 0 to 32.
This regex will match CIDR like below:
0.0.0.0/0
192.168.1.2/32
but not those below:
10.1.0.256/16
1.2.3./24
127.0.0.1/33
And for list of IPv4 CIDR like "10.0.0.0/16", "192.168.1.1/32"
I use this regex:
^("(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))((\.(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))){3})\/(([0-9])|([12][0-9])|(3[0-2]))")((,([ ]*)("(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))((\.(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))){3})\/(([0-9])|([12][0-9])|(3[0-2]))"))*)$
It is in this structure: ^(“C”)((,([ ]*)(“C”))*)$
where C is the regex used to match CIDR (like 0.0.0.0/0).
This regex will match list of CIDR like below:
“10.0.0.0/16”,”192.168.1.2/32”, “1.2.3.4/32”
but not those below:
“10.0.0.0/16” 192.168.1.2/32 “1.2.3.4/32”
Maybe it might get shorter but for me it is easy to understand so fine by me.
Hope it helps!
Another approach, if you're desperate and don't have access to (a) the code or (b) the command line, then you can use environment variables:
http://docs.oracle.com/javase/7/docs/webnotes/tsg/TSG-Desktop/html/plugin.html.
Specifically for java web start set the environment variable:
JAVAWS_VM_ARGS
and for applets:
_JPI_VM_OPTIONS
e.g.
_JPI_VM_OPTIONS=-Djava.net.preferIPv4Stack=true
Additionally, under Windows global options (for general Java applications) can be set in the Java control plan page under the "Java" tab.
UDP is not "safe", so the question is not great - however -
If you send 9217 or more (mac) or 65508+ (linux/windows), the socket send function returns with an error.
The above answers discussing fragmentation and MTU and so on are off topic - that all takes place at a lower level, is "invisible" to you, and does not affect "safety" on typical connections to a significant degree.
To answer the actual question meaning though - do not use UDP - use raw sockets so you get better control of everything; since you're writing a game, you need to delve into the flags to get priority into your traffic anyhow, so you may as well get rid of UDP issues at the same time.
Assembled several of the above answers into an extension method that handles the Endianness of the machine and handles IPv4 addresses that were mapped to IPv6.
public static class IPAddressExtensions
{
/// <summary>
/// Converts IPv4 and IPv4 mapped to IPv6 addresses to an unsigned integer.
/// </summary>
/// <param name="address">The address to conver</param>
/// <returns>An unsigned integer that represents an IPv4 address.</returns>
public static uint ToUint(this IPAddress address)
{
if (address.AddressFamily == AddressFamily.InterNetwork || address.IsIPv4MappedToIPv6)
{
var bytes = address.GetAddressBytes();
if (BitConverter.IsLittleEndian)
Array.Reverse(bytes);
return BitConverter.ToUInt32(bytes, 0);
}
throw new ArgumentOutOfRangeException("address", "Address must be IPv4 or IPv4 mapped to IPv6");
}
}
Unit tests:
[TestClass]
public class IPAddressExtensionsTests
{
[TestMethod]
public void SimpleIp1()
{
var ip = IPAddress.Parse("0.0.0.15");
uint expected = GetExpected(0, 0, 0, 15);
Assert.AreEqual(expected, ip.ToUint());
}
[TestMethod]
public void SimpleIp2()
{
var ip = IPAddress.Parse("0.0.1.15");
uint expected = GetExpected(0, 0, 1, 15);
Assert.AreEqual(expected, ip.ToUint());
}
[TestMethod]
public void SimpleIpSix1()
{
var ip = IPAddress.Parse("0.0.0.15").MapToIPv6();
uint expected = GetExpected(0, 0, 0, 15);
Assert.AreEqual(expected, ip.ToUint());
}
[TestMethod]
public void SimpleIpSix2()
{
var ip = IPAddress.Parse("0.0.1.15").MapToIPv6();
uint expected = GetExpected(0, 0, 1, 15);
Assert.AreEqual(expected, ip.ToUint());
}
[TestMethod]
public void HighBits()
{
var ip = IPAddress.Parse("200.12.1.15").MapToIPv6();
uint expected = GetExpected(200, 12, 1, 15);
Assert.AreEqual(expected, ip.ToUint());
}
uint GetExpected(uint a, uint b, uint c, uint d)
{
return
(a * 256u * 256u * 256u) +
(b * 256u * 256u) +
(c * 256u) +
(d);
}
}
IPHostEntry ipHostInfo = Dns.GetHostEntry(serverName);
IPAddress ipAddress = ipHostInfo.AddressList
.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork);
Here is the code you are looking for in javascript. Well you know you can't convert all of the ipv6 addresses
<script>
function parseIp6(str)
{
//init
var ar=new Array;
for(var i=0;i<8;i++)ar[i]=0;
//check for trivial IPs
if(str=="::")return ar;
//parse
var sar=str.split(':');
var slen=sar.length;
if(slen>8)slen=8;
var j=0;
for(var i=0;i<slen;i++){
//this is a "::", switch to end-run mode
if(i && sar[i]==""){j=9-slen+i;continue;}
ar[j]=parseInt("0x0"+sar[i]);
j++;
}
return ar;
}
function ipcnvfrom6(ip6)
{
var ip6=parseIp6(ip6);
var ip4=(ip6[6]>>8)+"."+(ip6[6]&0xff)+"."+(ip6[7]>>8)+"."+(ip6[7]&0xff);
return ip4;
}
alert(ipcnvfrom6("::C0A8:4A07"));
</script>
It's available in the HTTP referer
header. You can get it in a servlet as follows:
String referrer = request.getHeader("referer"); // Yes, with the legendary misspelling.
You, however, need to realize that this is a client-controlled value and can thus be spoofed to something entirely different or even removed. Thus, whatever value it returns, you should not use it for any critical business processes in the backend, but only for presentation control (e.g. hiding/showing/changing certain pure layout parts) and/or statistics.
For the interested, background about the misspelling can be found in Wikipedia.
Restarting Visual Studio did the trick for me. I am using VS 2015.
In addition to the disable cache option (which you get to via a button in the lower right corner of the developer tools window -- Tools | Developer Tools, or Ctrl + Shift + I), on the network pane of the developer tools you can now right click and choose "Clear Cache" from the popup menu.
Just one addition to answers: If all these methods return false, even if strings seem to be equal, it is possible that there is a whitespace to the left and or right of one string. So, just put a .trim()
at the end of strings before comparing:
if(s1.trim() === s2.trim())
{
// your code
}
I have lost hours trying to figure out what is wrong. Hope this will help to someone!
I'm way late, but check out Quandl. They have an API for stock prices and fundamentals.
Here's an example call, using Quandl-api download in csv
example:
https://www.quandl.com/api/v1/datasets/WIKI/AAPL.csv?column=4&sort_order=asc&collapse=quarterly&trim_start=2012-01-01&trim_end=2013-12-31
They support these languages. Their source data comes from Yahoo Finance, Google Finance, NSE, BSE, FSE, HKEX, LSE, SSE, TSE and more (see here).
You don't need to add '.' in your class name. This will do
document.getElementsByClassName('col1')
Additionally, since you haven't define the background color via javascript, you won't able to call it directly. You have to use window.getComputedStyle() or jquery to achieve what you are trying to do above.
Here is a working example
Rda is just a short name for RData. You can just save(), load(), attach(), etc. just like you do with RData.
Rds stores a single R object. Yet, beyond that simple explanation, there are several differences from a "standard" storage. Probably this R-manual Link to readRDS() function clarifies such distinctions sufficiently.
So, answering your questions:
I use such code, if I have list of strings:
((IList<string>)Table).Count
use a static defaultProps like:
export default class AddAddressComponent extends Component {
static defaultProps = {
provinceList: [],
cityList: []
}
render() {
let {provinceList,cityList} = this.props
if(cityList === undefined || provinceList === undefined){
console.log('undefined props')
}
...
}
AddAddressComponent.contextTypes = {
router: React.PropTypes.object.isRequired
}
AddAddressComponent.defaultProps = {
cityList: [],
provinceList: [],
}
AddAddressComponent.propTypes = {
userInfo: React.PropTypes.object,
cityList: PropTypes.array.isRequired,
provinceList: PropTypes.array.isRequired,
}
Taken from: https://github.com/facebook/react-native/issues/1772
If you wish to check the types, see how to use PropTypes in treyhakanson's or Ilan Hasanov's answer, or review the many answers in the above link.
Go through http://nodejs.org/api/fs.html
One important thing - you can use sync functions also. (It will work like C program)
In my case the error was on a module of my project.I have resolved this with adding
dependencies {
implementation 'com.android.support:support-v4:20.0.+'
}
this dependency in gradle of corresponding module
You can use the below syntax -
from FolderName.FileName import Classname
That's because you're using a non-blocking
socket and the output buffer is full.
From the send()
man page
When the message does not fit into the send buffer of the socket,
send() normally blocks, unless the socket has been placed in non-block-
ing I/O mode. In non-blocking mode it would return EAGAIN in this
case.
EAGAIN is the error code tied to "Resource temporarily unavailable"
Consider using select()
to get a better control of this behaviours
An update. Dates of the form '2019-08-00' will trigger the same error. Adding the lines:
[mysqld]
sql_mode="NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
to mysql.cnf
fixes this too. Inserting malformed dates now generates warnings for values out of range but does insert the data.
I prefer inline-block
, but float
are still useful way to put together HTML elemenets, specially when we have elements which one should stick to the left and one to the right, float working better with writing less lines, while inline-block working well in many other cases.
L
: long i = 12345678910L;
.BTW: it doesn't have to be an upper case L, but lower case is confused with 1
many times :).
Here are some methods that may help others, though they aren't really services as much as they may be described as "methods that may, after some torture of effort or logic, lead to a claim of on-demand access to Mac OS X" (no doubt I should patent that phrase).
Fundamentally, I am inclined to believe that on-demand (per-hour) hosting does not exist, and @Erik has given information for the shortest feasible services, i.e. monthly hosting.
It seems that one may use EC2 itself, but install OS X on the instance through a lot of elbow grease.
Where this gets tricky is I'm not sure if this will work for a cluster compute instance. In fact, I think this is likely to be a royal pain. A similar approach may work for Rackspace or other cloud services.
I found only this site claiming on-demand Mac hosting, with a Mac Mini. It doesn't look particularly accurate: it offers free on-demand access to a Mini if one pays for a month of bandwidth. That's like free bandwidth if one rents a Mini for a month. That's not really how "on-demand" works.
Update 1: In the end, it seems that nobody offers a comparable service. An outfit called Media Temple claims they will offer the first virtual servers using Parallels, OS X Leopard, and some other stuff (in other words, I wonder if there is some caveat that makes them unique, but, without that caveat, someone else may have a usable offering).
After this search, I think that a counterpart to EC2 does not exist for the OS X operating system. It is extraordinarily unlikely that one would exist, offer a scalable solution, and yet be very difficult to find. One could set it up internally, but there's no reseller/vendor offering on-demand, hourly virtual servers. This may be disappointing, but not surprising - apparently iCloud is running on Amazon and Microsoft systems.
Actually, you can process the find
command output in a copy command in two ways:
If the find
command's output doesn't contain any space, i.e if the filename doesn't contain a space in it, then you can use:
Syntax:
find <Path> <Conditions> | xargs cp -t <copy file path>
Example:
find -mtime -1 -type f | xargs cp -t inner/
But our production data files might contain spaces, so most of time this command is effective:
Syntax:
find <path> <condition> -exec cp '{}' <copy path> \;
Example
find -mtime -1 -type f -exec cp '{}' inner/ \;
In the second example, the last part, the semi-colon is also considered as part of the find
command, and should be escaped before pressing Enter. Otherwise you will get an error something like:
find: missing argument to `-exec'
I don't know what the .tex extension on your file means. If we are saying that it is any file with any extension you have several methods of reading it.
I have to assume you are using windows because you have mentioned notepad++.
Use notepad++. Right click on the file and choose "edit with notepad++"
Use notepad Change the filename extension to .txt and double click the file.
Use command prompt. Open the folder that your file is in. Hold down shift and right click. (not on the file, but in the folder that the file is in.) Choose "open command window here" from the command prompt type: "type filename.tex"
If these don't work, I would need more detail as to how they are not working. Errors that you may be getting or what you may expect to be in the file might help.
def flatten_it(d):
if isinstance(d, list) or isinstance(d, tuple):
return tuple([flatten_it(item) for item in d])
elif isinstance(d, dict):
return tuple([(flatten_it(k), flatten_it(v)) for k, v in sorted(d.items())])
else:
return d
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 1, 'b': 1}
print set(flatten_it(dict1)) - set(flatten_it(dict2)) # set([('b', 2), ('c', 3)])
# or
print set(flatten_it(dict2)) - set(flatten_it(dict1)) # set([('b', 1)])
Use Math.ceil()
and cast the result to int:
Example:
(int) Math.ceil((double)divident / divisor);
I had that problem too and I solve it by:
$today = date("Ymd");
$expire = str_replace('-', '', $row->expireDate); //from db
if(($today - $expire) > $NUMBER_OF_DAYS)
{
//do something;
}
It may be worth mentioning that running tomcat as a non root user (which you should be doing) will prevent you from using a port below 1024 on *nix. If you want to use TC as a standalone server -- as its performance no longer requires it to be fronted by Apache or the like -- you'll want to bind to port 80 along with whatever IP address you're specifying.
You can do this by using IPTABLES to redirect port 80 to 8080.
stdout is buffered, so will only output after a newline is printed.
To get immediate output, either:
The issue is caused because of event bubbling. The first part of your code to add .grown
works fine.
The second part "removing grown class" on clicking the link doesn't work as expected as both the handler for .close_button
and .clickable
are executed. So it removes and readd the grown
class to the div
.
You can avoid this by using e.stopPropagation()
inside .close_button
click handler to avoid the event from bubbling.
DEMO: http://jsfiddle.net/vL8DP/
Full Code
$(document).on('click', '.clickable', function () {
$(this).addClass('grown').removeClass('spot');
}).on('click', '.close_button', function (e) {
e.stopPropagation();
$(this).closest('.clickable').removeClass('grown').addClass('spot');
});
You can try this:
/*iPad landscape oriented styles */
@media only screen and (device-width:768px)and (orientation:landscape){
.yourstyle{
}
}
/*iPad Portrait oriented styles */
@media only screen and (device-width:768px)and (orientation:portrait){
.yourstyle{
}
}
For me, I was writing to a file that is opened in Excel.
To be precise, a block ends when it encounter a non-empty line indented at most the same level with the start. This non empty line is not part of that block For example, the following print ends two blocks at the same time:
def foo():
if bar:
print "bar"
print "baz" # ends the if and foo at the same time
The indentation level is less-than-or-equal to both the def and the if, hence it ends them both.
Lines with no statement, no matter the indentation, does not matter
def foo():
print "The line below has no indentation"
print "Still part of foo"
But the statement that marks the end of the block must be indented at the same level as any existing indentation. The following, then, is an error:
def foo():
print "Still correct"
print "Error because there is no block at this indentation"
Generally, if you're used to curly braces language, just indent the code like them and you'll be fine.
BTW, the "standard" way of indenting is with spaces only, but of course tab only is possible, but please don't mix them both.
The better and dynamic solution I have found is to use $watch to trace the variable changes and then update the title.
By default, a comma is used as a delimiter in a CSV file. However, some CSV files can use delimiters other than a comma. Few popular ones are |
and \t
.
import csv
data_list = [["SN", "Name", "Contribution"],
[1, "Linus Torvalds", "Linux Kernel"],
[2, "Tim Berners-Lee", "World Wide Web"],
[3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
writer = csv.writer(file, delimiter='|')
writer.writerows(data_list)
output:
SN|Name|Contribution
1|Linus Torvalds|Linux Kernel
2|Tim Berners-Lee|World Wide Web
3|Guido van Rossum|Python Programming
import csv
row_list = [["SN", "Name", "Contribution"],
[1, "Linus Torvalds", "Linux Kernel"],
[2, "Tim Berners-Lee", "World Wide Web"],
[3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC, delimiter=';')
writer.writerows(row_list)
output:
"SN";"Name";"Contribution"
1;"Linus Torvalds";"Linux Kernel"
2;"Tim Berners-Lee";"World Wide Web"
3;"Guido van Rossum";"Python Programming"
As you can see, we have passed csv.QUOTE_NONNUMERIC
to the quoting
parameter. It is a constant defined by the csv
module.
csv.QUOTE_NONNUMERIC
specifies the writer
object that quotes should be added around the non-numeric entries.
There are 3 other predefined constants you can pass to the quoting
parameter:
csv.QUOTE_ALL
- Specifies the writer
object to write CSV file with quotes around all the entries.csv.QUOTE_MINIMAL
- Specifies the writer
object to only quote those fields which contain special characters (delimiter, quotechar or any characters in lineterminator)csv.QUOTE_NONE
- Specifies the writer
object that none of the entries should be quoted. It is the default value.import csv
row_list = [["SN", "Name", "Contribution"],
[1, "Linus Torvalds", "Linux Kernel"],
[2, "Tim Berners-Lee", "World Wide Web"],
[3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC,
delimiter=';', quotechar='*')
writer.writerows(row_list)
output:
*SN*;*Name*;*Contribution*
1;*Linus Torvalds*;*Linux Kernel*
2;*Tim Berners-Lee*;*World Wide Web*
3;*Guido van Rossum*;*Python Programming*
Here, we can see that quotechar='*'
parameter instructs the writer
object to use *
as quote for all non-numeric values.
I think the right answer is:
Why would I not use a basic operator to do a basic operation?
Try:
bash -c '[ -d my_mystery_dirname ] && run_this_command'
This will work if you can run bash on the remote machine....
In bash, [ -d something ]
checks if there is directory called 'something', returning a success code if it exists and is a directory. Chaining commands with && runs the second command only if the first one succeeded. So [ -d somedir ] && command
runs the command only if the directory exists.
The ISO 7000 / IEC 60417 Symbol for Pause; Interruption is #5111B. See Media_Controls
Current date and time
$current_date_time = date('Y-m-d H:i:s');
15 min ago Date and time
$newTime = date("Y-m-d H:i:s",strtotime("+15 minutes", strtotime($current_date)));
A solution that works for S3 modified from Minkymorgan.
Simply pass the temporary partitioned directory path (with different name than final path) as the srcPath
and single final csv/txt as destPath
Specify also deleteSource
if you want to remove the original directory.
/**
* Merges multiple partitions of spark text file output into single file.
* @param srcPath source directory of partitioned files
* @param dstPath output path of individual path
* @param deleteSource whether or not to delete source directory after merging
* @param spark sparkSession
*/
def mergeTextFiles(srcPath: String, dstPath: String, deleteSource: Boolean): Unit = {
import org.apache.hadoop.fs.FileUtil
import java.net.URI
val config = spark.sparkContext.hadoopConfiguration
val fs: FileSystem = FileSystem.get(new URI(srcPath), config)
FileUtil.copyMerge(
fs, new Path(srcPath), fs, new Path(dstPath), deleteSource, config, null
)
}
includes() is not supported by most browsers. Your options are either to use
-polyfill from MDN https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes
or to use
-indexof()
var str = "abcde";
var n = str.indexOf("cd");
Which gives you n=2
This is widely supported.
Most probably it has to do with caching on the device. Catching the exception and ignoring is not nice but my problem was fixed and it seems to work.
To clone a git repo into an empty existing directory do the following:
cd myfolder
git clone https://myrepo.com/git.git .
Notice the .
at the end of your git clone
command. That will download the repo into the current working directory.
In Java, a String is a reference to heap-allocated storage. Returning "ans" only returns the reference so there is no need for stack-allocated storage. In fact, there is no way in Java to allocate objects in stack storage.
I would change to this, though. You don't need "ans" at all.
return String.format("%d:%d", mins, secs);
Replace [True | False (default)]
Effect
1. Replace the directive element.
Dependency:
1. When replace: true, the template or templateUrl must be required.
I prefer the following command-line options:
cat req.xml | curl -X POST -H 'Content-type: text/xml' -d @- http://www.example.com
or
curl -X POST -H 'Content-type: text/xml' -d @req.xml http://www.example.com
or
curl -X POST -H 'Content-type: text/xml' -d '<XML>data</XML>' http://www.example.com
The Express API doc spells this out pretty clearly.
Additionally this answer gives the steps to create a self-signed certificate.
I have added some comments and a snippet from the Node.js HTTPS documentation:
var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');
// This line is from the Node.js HTTPS documentation.
var options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.cert')
};
// Create a service (the app object is just a callback).
var app = express();
// Create an HTTP service.
http.createServer(app).listen(80);
// Create an HTTPS service identical to the HTTP service.
https.createServer(options, app).listen(443);
Eclipse IDE for C/C++ Developers, Version: Helios Service Release 2
You need to create new profile by pressing New button inside "Window->Preferences->Code Style"
Go to Indentation tab and select "Tab policy = Space only"
Eclipse IDE for C/C++ Developers, Version: Kepler Service Release 1
Follow the path below to create new profile: "Window > Preferences > C/C++ > Code Style > Formatter"
Go to Indentation tab and select "Tab policy = Space only"
@Travis solution is right, but it loses milliseconds when a Date is generated. I have added a line to include the milliseconds into the date:
If you don't need this precision, use the Travis solution because it will be faster.
extension Date {
func toMillis() -> Int64! {
return Int64(self.timeIntervalSince1970 * 1000)
}
init(millis: Int64) {
self = Date(timeIntervalSince1970: TimeInterval(millis / 1000))
self.addTimeInterval(TimeInterval(Double(millis % 1000) / 1000 ))
}
}
You can add a new source directory with build-helper:
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/generated</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
For portable code, the macros in inttypes.h may be used. They expand to the correct ones for the platform.
E.g. for 64 bit integer, the macro PRId64
can be used.
int64_t n = 7;
printf("n is %" PRId64 "\n", n);
Apart from using an escaped value as described in my other answer, it is also possible to fix this issue by enabling the Strict Math setting.
With strict math on, only maths that are inside unnecessary parentheses will be processed, so your code:
width: calc(100% - 200px);
Would work as expected with the strict math option enabled.
However, note that Strict Math is applied globally, not only inside calc()
. That means, if you have:
font-size: 12px + 2px;
The math will no longer be processed by Less -- it will output font-size: 12px + 2px
which is, obviously, invalid CSS. You'd have to wrap all maths that should be processed by Less in (previously unnecessary) parentheses:
font-size: (12px + 2px);
Strict Math is a nice option to consider when starting a new project, otherwise you'd possibly have to rewrite a good part of the code base. For the most common use cases, the escaped string approach described in the other answer is more suitable.
Do you have access to the command prompt ?
Method 1 : Command Prompt
The specifics of the Java installed on the system can be determined by executing the following command java -version
Method 2 : Folder Structure
In case you do not have access to command prompt then determining the folder where Java.
32 Bit : C:\Program Files (x86)\Java\jdk1.6.0_30
64 Bit : C:\Program Files\Java\jdk1.6.0_25
However during the installation it is possible that the user might change the installation folder.
Method 3 : Registry
You can also see the version installed in registry editor.
Go to registry editor
Edit -> Find
Search for Java. You will get the registry entries for Java.
In the entry with name : DisplayName
& DisplayVersion
, the installed java version is displayed
you can create array follow the code below:
var arraymultidimensional = []
arraymultidimensional = [[value1,value2],[value3,value4],[value5,value6]];
Result:
[v1][v2] position 0
[v3][v4] position 1
[v5][v6] position 2
For add to array dinamically, use the method below:
//vectorvalue format = "[value,value,...]"
function addToArray(vectorvalue){
arraymultidimensional[arraymultidimensional.length] = vectorvalue;
}
Hope this helps. :)
When you share for Facebook, you have to add in your html into the head section next meta tags:
<meta property="og:title" content="title" />
<meta property="og:description" content="description" />
<meta property="og:image" content="thumbnail_image" />
And that's it!
Add the button as you should according to what FB tells you.
All the info you need is in www.facebook.com/share/
The syntax is as follows:
new Date(year, month [, day, hour, minute, second, millisecond ])
so
Date d = new Date(2011,10,30);
is correct; day, hour, minute, second, millisecond are optional.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
nil is an object pointer to nothing. Although semantically distinct from NULL, they are technically equivalent to one another.
On the framework level, Foundation defines NSNull, which defines a class method, +null, which returns the singleton NSNull object. NSNull is different from nil or NULL, in that it is an actual object, rather than a zero value.
Additionally, in Foundation/NSObjCRuntime.h, Nil is defined as a class pointer to nothing.
Just for the heck of it, I tracked this down in the jQuery code. The .val() function currently starts at line 165 of attributes.js. Here's the relevant section, with my annotations:
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
/// NO ARGUMENTS, BECAUSE NOT SETTING VALUE
if ( !arguments.length ) {
/// IF NOT DEFINED, THIS BLOCK IS NOT ENTERED. HENCE 'UNDEFINED'
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
/// IF IS DEFINED, JQUERY WILL CHECK TYPE AND RETURN APPROPRIATE 'EMPTY' VALUE
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
So, you'll either get undefined
or ""
or null
-- all of which evaluate as false in if statements.
The abstract methods are implicitly virtual. Abstract methods require an instance, but static methods do not have an instance. So, you can have a static method in an abstract class, it just cannot be static abstract (or abstract static).
If you are using Netty, you can use:
You're getting the error message
ValueError: setting an array element with a sequence.
because you're trying to set an array element with a sequence. I'm not trying to be cute, there -- the error message is trying to tell you exactly what the problem is. Don't think of it as a cryptic error, it's simply a phrase. What line is giving the problem?
kOUT[i]=func(TempLake[i],Z)
This line tries to set the ith
element of kOUT
to whatever func(TempLAke[i], Z)
returns. Looking at the i=0
case:
In [39]: kOUT[0]
Out[39]: 0.0
In [40]: func(TempLake[0], Z)
Out[40]: array([ 0., 0., 0., 0.])
You're trying to load a 4-element array into kOUT[0]
which only has a float. Hence, you're trying to set an array element (the left hand side, kOUT[i]
) with a sequence (the right hand side, func(TempLake[i], Z)
).
Probably func
isn't doing what you want, but I'm not sure what you really wanted it to do (and don't forget you can usually use vectorized operations like A*B rather than looping in numpy.) That should explain the problem, anyway.
As you have noticed, xscale
and yscale
does not support a simple linear re-scaling (unfortunately). As an alternative to Hooked's answer, instead of messing with the data, you can trick the labels like so:
ticks = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x*scale))
ax.xaxis.set_major_formatter(ticks)
A complete example showing both x and y scaling:
import numpy as np
import pylab as plt
import matplotlib.ticker as ticker
# Generate data
x = np.linspace(0, 1e-9)
y = 1e3*np.sin(2*np.pi*x/1e-9) # one period, 1k amplitude
# setup figures
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
# plot two identical plots
ax1.plot(x, y)
ax2.plot(x, y)
# Change only ax2
scale_x = 1e-9
scale_y = 1e3
ticks_x = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_x))
ax2.xaxis.set_major_formatter(ticks_x)
ticks_y = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_y))
ax2.yaxis.set_major_formatter(ticks_y)
ax1.set_xlabel("meters")
ax1.set_ylabel('volt')
ax2.set_xlabel("nanometers")
ax2.set_ylabel('kilovolt')
plt.show()
And finally I have the credits for a picture:
Note that, if you have text.usetex: true
as I have, you may want to enclose the labels in $
, like so: '${0:g}$'
.
sudo phpenmod mysqli
sudo service apache2 restart
phpenmod moduleName
enables a module to PHP 7 (restart Apache after that sudo service apache2 restart
)phpdismod moduleName
disables a module to PHP 7 (restart Apache after that sudo service apache2 restart
)php -m
lists the loaded modulesdel /s /q c:\where ever the file is\*
rmdir /s /q c:\where ever the file is\
mkdir c:\where ever the file is\
I have problem with this error handling approach: In case of web.config:
<customErrors mode="On"/>
The error handler is searching view Error.shtml and the control flow step in to Application_Error global.asax only after exception
System.InvalidOperationException: The view 'Error' or its master was not found or no view engine supports the searched locations. The following locations were searched: ~/Views/home/Error.aspx ~/Views/home/Error.ascx ~/Views/Shared/Error.aspx ~/Views/Shared/Error.ascx ~/Views/home/Error.cshtml ~/Views/home/Error.vbhtml ~/Views/Shared/Error.cshtml ~/Views/Shared/Error.vbhtml at System.Web.Mvc.ViewResult.FindView(ControllerContext context) ....................
So
Exception exception = Server.GetLastError();
Response.Clear();
HttpException httpException = exception as HttpException;
httpException is always null then
customErrors mode="On"
:(
It is misleading
Then <customErrors mode="Off"/>
or <customErrors mode="RemoteOnly"/>
the users see customErrors html,
Then customErrors mode="On" this code is wrong too
Another problem of this code that
Response.Redirect(String.Format("~/Error/{0}/?message={1}", action, exception.Message));
Return page with code 302 instead real error code(402,403 etc)
just use the core https module with the https.request function. Example for a POST
request (GET
would be similar):
var https = require('https');
var options = {
host: 'www.google.com',
port: 443,
path: '/upload',
method: 'POST'
};
var req = https.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
This does exist, but it's actually a feature of git log
:
git log -p [--follow] [-1] <path>
Note that -p
can also be used to show the inline diff from a single commit:
git log -p -1 <commit>
Options used:
-p
(also -u
or --patch
) is hidden deeeeeeeep in the git-log
man page, and is actually a display option for git-diff
. When used with log
, it shows the patch that would be generated for each commit, along with the commit information—and hides commits that do not touch the specified <path>
. (This behavior is described in the paragraph on --full-diff
, which causes the full diff of each commit to be shown.)-1
shows just the most recent change to the specified file (-n 1
can be used instead of -1
); otherwise, all non-zero diffs of that file are shown.--follow
is required to see changes that occurred prior to a rename.As far as I can tell, this is the only way to immediately see the last set of changes made to a file without using git log
(or similar) to either count the number of intervening revisions or determine the hash of the commit.
To see older revisions changes, just scroll through the log, or specify a commit or tag from which to start the log. (Of course, specifying a commit or tag returns you to the original problem of figuring out what the correct commit or tag is.)
Credit where credit is due:
log -p
thanks to this answer.--follow
option.-n 1
option and atatko for mentioning the -1
variant.-p
"means" semantically.The logic is simple. setOnClickListener
belongs to step 2.
OnClickListener
* like it's done in that example and override the onClick
-method.OnClickListener
to that button using btn.setOnClickListener(myOnClickListener);
in your fragments/activities onCreate
-method.onClick
function of the assigned OnClickListener
is called.*If you import android.view.View;
you use View.OnClickListener
. If you import android.view.View.*;
or import android.view.View.OnClickListener;
you use OnClickListener
as far as I get it.
Another way is to let you activity/fragment inherit from OnClickListener
. This way you assign your fragment/activity as the listener for your button and implement onClick
as a member-function.
First of your answer is.
sudo chmod -R 777/775 /path/project_folder
Now You need to understand permissions and options in ubuntu.
I had a similar scenario, but was also required to set a Proxy. The simplest way I could see to do this was to extend the SimpleClientHttpRequestFactory
for the ease of setting the proxy (different proxies for non-prod vs prod). This should still work even if you don't require the proxy though. Then in my extended class I override the openConnection(URL url, Proxy proxy)
method, using the same as the source, but just setting the timeouts before returning.
@Override
protected HttpURLConnection openConnection(URL url, Proxy proxy) throws IOException {
URLConnection urlConnection = proxy != null ? url.openConnection(proxy) : url.openConnection();
Assert.isInstanceOf(HttpURLConnection.class, urlConnection);
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
return (HttpURLConnection) urlConnection;
}
CODE:
import codecs
path="D:\\Users\\html\\abc.html"
file=codecs.open(path,"rb")
file1=file.read()
file1=str(file1)
Java stores all it's "chars" internally as two bytes. However, when they become strings etc, the number of bytes will depend on your encoding.
Some characters (ASCII) are single byte, but many others are multi-byte.
Java supports Unicode, thus according to:
The max value supported is "\uFFFF" (hex FFFF, dec 65535), or 11111111 11111111 binary (two bytes).
If anybody is looking for a TypeScript solution:
.ts file (change variables where applicable):
module App.Filters {
export class trustedResource {
static $inject:string[] = ['$sce'];
static filter($sce:ng.ISCEService) {
return (value) => {
return $sce.trustAsResourceUrl(value)
};
}
}
}
filters.filter('trustedResource', App.Filters.trusted.filter);
Html:
<video controls ng-if="HeaderVideoUrl != null">
<source ng-src="{{HeaderVideoUrl | trustedResource}}" type="video/mp4"/>
</video>
Step 1:
cd /etc/postgresql/12/main/
open file named postgresql.conf
sudo nano postgresql.conf
add this line to that file
listen_addresses = '*'
then open file named pg_hba.conf
sudo nano pg_hba.conf
and add this line to that file
host all all 0.0.0.0/0 md5
It allows access to all databases for all users with an encrypted password
restart your server
sudo /etc/init.d/postgresql restart
//C++ Simple Code
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<char> alphanum =
{'0','1','2','3','4',
'5','6','7','8','9',
'A','B','C','D','E','F',
'G','H','I','J','K',
'L','M','N','O','P',
'Q','R','S','T','U',
'V','W','X','Y','Z',
'a','b','c','d','e','f',
'g','h','i','j','k',
'l','m','n','o','p',
'q','r','s','t','u',
'v','w','x','y','z'
};
string s="";
int len=5;
srand(time(0));
for (int i = 0; i <len; i++) {
int t=alphanum.size()-1;
int idx=rand()%t;
s+= alphanum[idx];
}
cout<<s<<" ";
return 0;
}
You can run your Python code using sl4a. sl4a supports Python, Perl, JRuby, Lua, BeanShell, JavaScript, Tcl, and shell script.
You can learn sl4a Python Examples.
for unhashable lists. It is faster as it does not iterate about already checked entries.
def purge_dublicates(X):
unique_X = []
for i, row in enumerate(X):
if row not in X[i + 1:]:
unique_X.append(row)
return unique_X
textarea { height: auto; }
_x000D_
<textarea rows="10"></textarea>
_x000D_
This will trigger the browser to set the height of the textarea EXACTLY to the amount of rows plus the paddings around it. Setting the CSS height to an exact amount of pixels leaves arbitrary whitespaces.
Follow these steps:
Create a new branch:
git branch newfeature
Checkout new branch: (this will not reset your work.)
git checkout newfeature
Now commit your work on this new branch:
git commit -s
Using above steps will keep your original branch clean and you dont have to do any 'git reset --hard'.
In MS-DOS COMMAND.COM
shell, you have to use:
d:
cd \windows\movie
If by chance you actually meant "Windows command prompt" (which is not MS-DOS and not DOS at all), then you can use cd /d d:\windows\movie
.
value = value.setScale(2, RoundingMode.CEILING)
As a button value is an attribute you need to use the .attr() method in jquery. This should do it
<script type="text/javascript">
$(document).ready(function() {
$('.my_button').click(function() {
alert($(this).attr("value"));
});
});
</script>
You can also use attr to set attributes, more info in the docs.
This only works in JQuery 1.6+. See postpostmodern's answer for older versions.
We make Webapps statefull by overriding HTTP stateless behaviour by using session objects.When we use session objets state is carried but we still use HTTP only.
word = "<insert palindrome/string>"
reverse = word[::-1]
is_palindrome = word.find(reverse)
print is_palindrome
This was a question in Udacity comp 101, chapter 1. Gives a 0 for palindrome gives a -1 for not. Its simple, and does not use loops.
The script I use is quite similar; I post it here as an example of how to use the email.* modules to generate MIME messages; so this script can be easily modified to attach pictures, etc.
I rely on my ISP to add the date time header.
My ISP requires me to use a secure smtp connection to send mail, I rely on the smtplib module (downloadable at http://www1.cs.columbia.edu/~db2501/ssmtplib.py)
As in your script, the username and password, (given dummy values below), used to authenticate on the SMTP server, are in plain text in the source. This is a security weakness; but the best alternative depends on how careful you need (want?) to be about protecting these.
=======================================
#! /usr/local/bin/python
SMTPserver = 'smtp.att.yahoo.com'
sender = 'me@my_email_domain.net'
destination = ['recipient@her_email_domain.com']
USERNAME = "USER_NAME_FOR_INTERNET_SERVICE_PROVIDER"
PASSWORD = "PASSWORD_INTERNET_SERVICE_PROVIDER"
# typical values for text_subtype are plain, html, xml
text_subtype = 'plain'
content="""\
Test message
"""
subject="Sent from Python"
import sys
import os
import re
from smtplib import SMTP_SSL as SMTP # this invokes the secure SMTP protocol (port 465, uses SSL)
# from smtplib import SMTP # use this for standard SMTP protocol (port 25, no encryption)
# old version
# from email.MIMEText import MIMEText
from email.mime.text import MIMEText
try:
msg = MIMEText(content, text_subtype)
msg['Subject']= subject
msg['From'] = sender # some SMTP servers will do this automatically, not all
conn = SMTP(SMTPserver)
conn.set_debuglevel(False)
conn.login(USERNAME, PASSWORD)
try:
conn.sendmail(sender, destination, msg.as_string())
finally:
conn.quit()
except:
sys.exit( "mail failed; %s" % "CUSTOM_ERROR" ) # give an error message
Debug.getNativeHeapSize()
will do the trick, I should think. It's been there since 1.0, though.
The Debug
class has lots of great methods for tracking allocations and other performance concerns. Also, if you need to detect a low-memory situation, check out Activity.onLowMemory()
.
Global import is safe to go with.
import 'rxjs/Rx';
Use a list instead and replace your foreach
loop with a for
loop:
@model IList<BlockedIPViewModel>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>
@Html.HiddenFor(x => x[i].IP)
@Html.CheckBoxFor(x => x[i].Checked)
</td>
<td>
@Html.DisplayFor(x => x[i].IP)
</td>
</tr>
}
<div>
<input type="submit" value="Unblock IPs" />
</div>
}
Alternatively you could use an editor template:
@model IEnumerable<BlockedIPViewModel>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.EditorForModel()
<div>
<input type="submit" value="Unblock IPs" />
</div>
}
and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml
which will automatically be rendered for each element of the collection:
@model BlockedIPViewModel
<tr>
<td>
@Html.HiddenFor(x => x.IP)
@Html.CheckBoxFor(x => x.Checked)
</td>
<td>
@Html.DisplayFor(x => x.IP)
</td>
</tr>
The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article
.
Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.
Pros: Host on Google has benefits
Cons:
I wonder if you can INCLUDE from Google, and then check the presence of some Global variable, or somesuch, and if absence load from your server?
Here's the main class from my collision detection program.
You can see it run at: http://www.youtube.com/watch?v=JIXhCvXgjsQ
/**
*
* @author Tyler Griffin
*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.GraphicsDevice.*;
import java.util.ArrayList;
import java.awt.Graphics;
import java.awt.geom.Line2D;
public class collision extends JFrame implements KeyListener, MouseMotionListener, MouseListener
{
ArrayList everything=new ArrayList<tile>();
int time=0, x, y, width, height, up=0, down=0, left=0, right=0, mouse1=0, mouse2=0;
int mouseX, mouseY;
GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice screen = environment.getDefaultScreenDevice();
DisplayMode displayMode = screen.getDisplayMode();
//private BufferStrategy strategy;
JLayeredPane pane = new JLayeredPane();
tile Tile;
circle Circle;
rectangle Rectangle;
textPane text;
public collision()
{
setUndecorated(screen.isFullScreenSupported());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLayout(null);
setResizable(false);
screen.setFullScreenWindow(this);
width=displayMode.getWidth();
height=displayMode.getHeight();
Circle=new circle(-(int)Math.round((double)height/7*2),-(int)Math.round((double)height/7*2),(int)Math.round((double)height/7*.85),this);
Rectangle=new rectangle(-(int)Math.round((double)height/7*1.5),-(int)Math.round((double)height/7*1.5),(int)Math.round((double)height/7*1.5),(int)Math.round((double)height/7*1.5),this);
Tile=Circle;
Tile.move(mouseX-Tile.width/2, mouseY-Tile.height/2);
text=new textPane(0,0,width,height,this);
everything.add(new circle((int)Math.round((double)width/100*75),(int)Math.round((double)height/100*15),(int)Math.round((double)width/100*10),this));
everything.add(new rectangle((int)Math.round((double)width/100*70),(int)Math.round((double)height/100*60),(int)Math.round((double)width/100*20),(int)Math.round((double)height/100*20),this));
//everything.add(new line(750,250,750,750,this));
/*everything.add(new line(width/700*419,height/700*68,width/700*495,height/700*345,this));
everything.add(new line(width/700*495,height/700*345,width/700*749,height/700*350,this));
everything.add(new line(width/700*749,height/700*350,width/700*549,height/700*519,this));
everything.add(new line(width/700*549,height/700*519,width/700*624,height/700*800,this));
everything.add(new line(width/700*624,height/700*800,width/700*419,height/700*638,this));
everything.add(new line(width/700*419,height/700*638,width/700*203,height/700*800,this));
everything.add(new line(width/700*203,height/700*800,width/700*279,height/700*519,this));
everything.add(new line(width/700*279,height/700*519,width/700*76,height/700*350,this));
everything.add(new line(width/700*76,height/700*350,width/700*333,height/700*345,this));
everything.add(new line(width/700*333,height/700*345,width/700*419,height/700*68,this));
everything.add(new line(width/950*419,height/700*68,width/950*624,height/700*800,this));
everything.add(new line(width/950*419,height/700*68,width/950*203,height/700*800,this));
everything.add(new line(width/950*76,height/700*350,width/950*624,height/700*800,this));
everything.add(new line(width/950*203,height/700*800,width/950*749,height/700*350,this));
everything.add(new rectangle(width/950*76,height/700*350,width/950*673,1,this));*/
everything.add(new line((int)Math.round((double)width/1350*419),(int)Math.round((double)height/1000*68),(int)Math.round((double)width/1350*624),(int)Math.round((double)height/1000*800),this));
everything.add(new line((int)Math.round((double)width/1350*419),(int)Math.round((double)height/1000*68),(int)Math.round((double)width/1350*203),(int)Math.round((double)height/1000*800),this));
everything.add(new line((int)Math.round((double)width/1350*76),(int)Math.round((double)height/1000*350),(int)Math.round((double)width/1350*624),(int)Math.round((double)height/1000*800),this));
everything.add(new line((int)Math.round((double)width/1350*203),(int)Math.round((double)height/1000*800),(int)Math.round((double)width/1350*749),(int)Math.round((double)height/1000*350),this));
everything.add(new rectangle((int)Math.round((double)width/1350*76),(int)Math.round((double)height/1000*350),(int)Math.round((double)width/1350*673),1,this));
addKeyListener(this);
addMouseMotionListener(this);
addMouseListener(this);
}
public void keyReleased(KeyEvent e)
{
Object source=e.getSource();
int released=e.getKeyCode();
if (released==KeyEvent.VK_A){left=0;}
if (released==KeyEvent.VK_W){up=0;}
if (released==KeyEvent.VK_D){right=0;}
if (released==KeyEvent.VK_S){down=0;}
}//end keyReleased
public void keyPressed(KeyEvent e)
{
Object source=e.getSource();
int pressed=e.getKeyCode();
if (pressed==KeyEvent.VK_A){left=1;}
if (pressed==KeyEvent.VK_W){up=1;}
if (pressed==KeyEvent.VK_D){right=1;}
if (pressed==KeyEvent.VK_S){down=1;}
if (pressed==KeyEvent.VK_PAUSE&&pressed==KeyEvent.VK_P)
{
//if (paused==0){paused=1;}
//else paused=0;
}
}//end keyPressed
public void keyTyped(KeyEvent e){}
//***********************************************************************************************
public void mouseDragged(MouseEvent e)
{
mouseX=(e.getX());
mouseY=(e.getY());
//run();
}
public void mouseMoved(MouseEvent e)
{
mouseX=(e.getX());
mouseY=(e.getY());
//run();
}
//***********************************************************************************************
public void mousePressed(MouseEvent e)
{
if(e.getX()==0 && e.getY()==0){System.exit(0);}
mouseX=(e.getX()+x);
mouseY=(e.getY()+y);
if(Tile instanceof circle)
{
Circle.move(0-Circle.width, 0-Circle.height);
Circle.setBounds(Circle.x, Circle.y, Circle.width, Circle.height);
Tile=Rectangle;
}
else
{
Rectangle.move(0-Rectangle.width, 0-Rectangle.height);
Rectangle.setBounds(Rectangle.x, Rectangle.y, Rectangle.width, Rectangle.height);
Tile=Circle;
}
Tile.move(mouseX-Tile.width/2, mouseY-Tile.height/2);
}
public void mouseReleased(MouseEvent e)
{
//run();
}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseClicked(MouseEvent e){}
//***********************************************************************************************
public void run()//run collision detection
{
while (this == this)
{
Tile.move(Tile.x + ((mouseX - (Tile.x + (Tile.width / 2))) / 10), Tile.y + ((mouseY - (Tile.y + (Tile.height / 2))) / 10));
//Tile.move((mouseX - Tile.width / 2), mouseY - (Tile.height / 2));
for (int i = 0; i < everything.size(); i++)
{
tile Temp = (tile) everything.get(i);
if (Temp.x < (Tile.x + Tile.width) && (Temp.x + Temp.width) > Tile.x && Temp.y < (Tile.y + Tile.height) && (Temp.y + Temp.height) > Tile.y)//rectangles collided
{
if (Temp instanceof rectangle)
{
if (Tile instanceof rectangle){rectangleRectangle(Temp);}
else {circleRectangle(Temp);}//Tile instanceof circle
}
else
{
if (Temp instanceof circle)
{
if (Tile instanceof rectangle) {rectangleCircle(Temp);}
else {circleCircle(Temp);}
}
else//line
{
if (Tile instanceof rectangle){rectangleLine(Temp);}
else{circleLine(Temp);}
}
}
}//end if
}//end for
try {Thread.sleep(16L);}
catch (Exception e) {}
Tile.setBounds(Tile.x, Tile.y, Tile.width, Tile.height);
//Rectangle.setBounds(x, y, width, height);
//Circle.setBounds(x, y, width, height);
repaint();
text.out=" ";
}//end while loop
}//end run
//***************************************special collision detection/handling functions************************************************
void rectangleRectangle(tile Temp)
{
int lapTop, lapBot, lapLeft, lapRight, small, scootX=0, scootY=0;
lapTop=(Temp.y+Temp.height)-Tile.y;
lapBot=(Tile.y+Tile.height)-Temp.y;
lapLeft=(Temp.x+Temp.width)-Tile.x;
lapRight=(Tile.x+Tile.width)-Temp.x;
small=999999999;
if (lapTop<small){small=lapTop; scootX=0; scootY=lapTop;}
if (lapBot<small){small=lapBot; scootX=0; scootY=lapBot*-1;}
if (lapLeft<small){small=lapLeft; scootX=lapLeft; scootY=0;}
if (lapRight<small){small=lapRight; scootX=lapRight*-1; scootY=0;}
Tile.move(Tile.x+scootX, Tile.y+scootY);text.out="collision detected!";
}
void circleRectangle(tile Temp)
{
if((Tile.x+Tile.width/2<=Temp.x+Temp.width && Tile.x+Tile.width/2>=Temp.x)||(Tile.y+Tile.height/2>=Temp.y && Tile.y+Tile.height/2<=Temp.y+Temp.height))
{
rectangleRectangle(Temp);
}
else//push from nearest corner
{
int x,y;
if(Tile.x+Tile.width/2>Temp.x+Temp.width && Tile.y+Tile.height/2<Temp.y){x=Temp.x+Temp.width; y=Temp.y;}
else if(Tile.x+Tile.width/2<Temp.x && Tile.y+Tile.height/2<Temp.y){x=Temp.x; y=Temp.y;}
else if(Tile.x+Tile.width/2>Temp.x+Temp.width && Tile.y+Tile.height/2>Temp.y+Temp.height){x=Temp.x+Temp.width; y=Temp.y+Temp.height;}
else {x=Temp.x; y=Temp.y+Temp.height;}
double distance = Math.sqrt(Math.pow(Tile.x+(Tile.width/2) - x, 2) + Math.pow(Tile.y+(Tile.height/2) - y, 2));
if((int)Math.round(distance)<Tile.height/2)
{
double normY = ((Tile.y+(Tile.height/2) - y) / distance);
double normX = ((Tile.x+(Tile.width/2) - x) / distance);
Tile.move(x-Tile.width/2+(int)Math.round(normX*((Tile.width/2))) , y-Tile.height/2+(int)Math.round(normY*((Tile.height/2))));text.out="collision detected!";
}
}
}
void rectangleCircle(tile Temp)
{
if((Temp.x+Temp.width/2<=Tile.x+Tile.width && Temp.x+Temp.width/2>=Tile.x)||(Temp.y+Temp.height/2>=Tile.y && Temp.y+Temp.height/2<=Tile.y+Tile.height))
{
rectangleRectangle(Temp);
}
else//push from nearest corner
{
int x,y;
if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2<Tile.y){x=Tile.x+Tile.width; y=Tile.y;}
else if(Temp.x+Temp.width/2<Tile.x && Temp.y+Temp.height/2<Tile.y){x=Tile.x; y=Tile.y;}
else if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2>Tile.y+Tile.height){x=Tile.x+Tile.width; y=Tile.y+Tile.height;}
else {x=Tile.x; y=Tile.y+Tile.height;}
double distance = Math.sqrt(Math.pow(Temp.x+(Temp.width/2) - x, 2) + Math.pow(Temp.y+(Temp.height/2) - y, 2));
if((int)Math.round(distance)<Temp.height/2)
{
double normY = ((Temp.y+(Temp.height/2) - y) / distance);
double normX = ((Temp.x+(Temp.width/2) - x) / distance);
if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2<Tile.y){Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2)))-Tile.width,(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2))));text.out="collision detected!";}
else if(Temp.x+Temp.width/2<Tile.x && Temp.y+Temp.height/2<Tile.y){Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2))),(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2))));text.out="collision detected!";}
else if(Temp.x+Temp.width/2>Tile.x+Tile.width && Temp.y+Temp.height/2>Tile.y+Tile.height){Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2)))-Tile.width,(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2)))-Tile.height);text.out="collision detected!";}
else {Tile.move((Temp.x+Temp.width/2)-(int)Math.round(normX*((Temp.width/2))),(Temp.y+Temp.height/2)-(int)Math.round(normY*((Temp.height/2)))-Tile.height);text.out="collision detected!";}
}
}
}
void circleCircle(tile Temp)
{
double distance = Math.sqrt(Math.pow((Tile.x+(Tile.width/2)) - (Temp.x+(Temp.width/2)),2) + Math.pow((Tile.y+(Tile.height/2)) - (Temp.y+(Temp.height/2)), 2));
if((int)distance<(Tile.width/2+Temp.width/2))
{
double normX = ((Tile.x+(Tile.width/2)) - (Temp.x+(Temp.width/2))) / distance;
double normY = ((Tile.y+(Tile.height/2)) - (Temp.y+(Temp.height/2))) / distance;
Tile.move((Temp.x+(Temp.width/2))+(int)Math.round(normX*(Tile.width/2+Temp.width/2))-(Tile.width/2) , (Temp.y+(Temp.height/2))+(int)Math.round(normY*(Tile.height/2+Temp.height/2))-(Tile.height/2));text.out="collision detected!";
}
}
void circleLine(tile Temp)
{
line Line=(line)Temp;
if (Line.x1 < (Tile.x + Tile.width) && (Line.x1) > Tile.x && Line.y1 < (Tile.y + Tile.height) && Line.y1 > Tile.y)//circle may be hitting one of the end points
{
rectangle rec=new rectangle(Line.x1, Line.y1, 1, 1, this);
circleRectangle(rec);
remove(rec);
}
if (Line.x2 < (Tile.x + Tile.width) && (Line.x2) > Tile.x && Line.y2 < (Tile.y + Tile.height) && Line.y2 > Tile.y)//circle may be hitting one of the end points
{
rectangle rec=new rectangle(Line.x2, Line.y2, 1, 1, this);
circleRectangle(rec);
remove(rec);
}
int x1=0, y1=0, x2=Tile.x+(Tile.width/2), y2=Tile.y+(Tile.height/2);
x1=Tile.x+(Tile.width/2)-Line.height;//(int)Math.round(Line.xNorm*1000);
x2=Tile.x+(Tile.width/2)+Line.height;
if(Line.posSlope)
{
y1=Tile.y+(Tile.height/2)-Line.width;
y2=Tile.y+(Tile.height/2)+Line.width;
}
else
{
y1=Tile.y+(Tile.height/2)+Line.width;
y2=Tile.y+(Tile.height/2)-Line.width;
}
Point point=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection
if (point.x < (Line.x + Line.width) && point.x > Line.x && point.y < (Line.y + Line.height) && point.y > Line.y)//line intersects within line segment
{
//if(point!=null){System.out.println(point.x+","+point.y);}
double distance = Math.sqrt(Math.pow((Tile.x+(Tile.width/2)) - point.x,2) + Math.pow((Tile.y+(Tile.width/2)) - point.y, 2));
if((int)distance<Tile.width/2)
{
//System.out.println("hit");
double normX = ((Tile.x+(Tile.width/2)) - point.x) / distance;
double normY = ((Tile.y+(Tile.height/2)) - point.y) / distance;
Tile.move((point.x)+(int)Math.round(normX*(Tile.width/2))-(Tile.width/2) , (point.y)+(int)Math.round(normY*(Tile.height/2))-(Tile.height/2));text.out="collision detected!";
//System.out.println(point.x+","+point.y);
}
}
//new bullet(this, (int)Math.round(tryX), (int)Math.round(tryY));
}
void rectangleLine(tile Temp)
{
line Line=(line)Temp;
if(new Line2D.Double(Line.x1,Line.y1,Line.x2,Line.y2).intersects(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height)))
{
if (Line.x1 < (Tile.x + Tile.width) && (Line.x1) > Tile.x && Line.y1 < (Tile.y + Tile.height) && Line.y1 > Tile.y)//circle may be hitting one of the end points
{
rectangle rec=new rectangle(Line.x1, Line.y1, 1, 1, this);
rectangleRectangle(rec);
remove(rec);
}
if (Line.x2 < (Tile.x + Tile.width) && (Line.x2) > Tile.x && Line.y2 < (Tile.y + Tile.height) && Line.y2 > Tile.y)//circle may be hitting one of the end points
{
rectangle rec=new rectangle(Line.x2, Line.y2, 1, 1, this);
rectangleRectangle(rec);
remove(rec);
}
if(Line.posSlope)//positive sloped line
{
//first we'll do the top left corner
int x1=Tile.x-Line.height;
int x2=Tile.x+Line.height;
int y1=Tile.y-Line.width;
int y2=Tile.y+Line.width;
Point topPoint=new Point(-99,-99), botPoint=new Point(-99,-99);
double topDistance=0, botDistance=0;
topPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection
topDistance = Math.sqrt(Math.pow(Tile.x - topPoint.x,2) + Math.pow(Tile.y - topPoint.y, 2));
//new let's do the bottom right corner
x1=Tile.x+Tile.width-Line.height;
x2=Tile.x+Tile.width+Line.height;
y1=Tile.y+Tile.height-Line.width;
y2=Tile.y+Tile.height+Line.width;
botPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection
botDistance = Math.sqrt(Math.pow((Tile.x+Tile.width) - botPoint.x,2) + Math.pow((Tile.y+Tile.height) - botPoint.y, 2));
if(topDistance<botDistance)
{
if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(topPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(topPoint))
{
Tile.move(topPoint.x,topPoint.y);text.out="collision detected!";
}
}
else
{
if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(botPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(botPoint))
{
Tile.move(botPoint.x-Tile.width,botPoint.y-Tile.height);text.out="collision detected!";
}
}
}
else//negative sloped lne
{
//first we'll do the top right corner
int x1=Tile.x+Tile.width-Line.height;
int x2=Tile.x+Tile.width+Line.height;
int y1=Tile.y+Line.width;
int y2=Tile.y-Line.width;
Point topPoint=new Point(-99,-99), botPoint=new Point(-99,-99);
double topDistance=0, botDistance=0;
topPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection
topDistance = Math.sqrt(Math.pow(Tile.x + Tile.width - topPoint.x,2) + Math.pow(Tile.y - topPoint.y, 2));
//new let's do the bottom left corner
x1=Tile.x-Line.height;
x2=Tile.x+Line.height;
y1=Tile.y+Tile.height+Line.width;
y2=Tile.y+Tile.height-Line.width;
botPoint=intersection((double)x1,(double)y1,(double)x2,(double)y2,(double)Line.x1,(double)Line.y1,(double)Line.x2,(double)Line.y2);//find intersection
botDistance = Math.sqrt(Math.pow(Tile.x - botPoint.x,2) + Math.pow((Tile.y+Tile.height) - botPoint.y, 2));
if(topDistance<botDistance)
{
if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(topPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(topPoint))
{
Tile.move(topPoint.x-Tile.width,topPoint.y);text.out="collision detected!";
}
}
else
{
if(new Rectangle(Tile.x,Tile.y,Tile.width,Tile.height).contains(botPoint) && new Rectangle(Line.x,Line.y,Line.width,Line.height).contains(botPoint))
{
Tile.move(botPoint.x,botPoint.y-Tile.height);text.out="collision detected!";
}
}
}
}
}
public Point intersection(double x1, double y1, double x2, double y2,double x3, double y3, double x4, double y4)//I didn't write this. got it from http://www.ahristov.com/tutorial/geometry-games/intersection-lines.html (I altered it)
{
double d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
double xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d;
double yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d;
int x=(int)Math.round(xi);
int y=(int)Math.round(yi);
return new Point(x, y);
}
//***************************************************************************************
public static void main(String[] args)
{
final collision Collision=new collision();
Collision.run();
}//end main
}//end class
The difference is that, for example, a
List<HashMap<String,String>>
is a
List<? extends Map<String,String>>
but not a
List<Map<String,String>>
So:
void withWilds( List<? extends Map<String,String>> foo ){}
void noWilds( List<Map<String,String>> foo ){}
void main( String[] args ){
List<HashMap<String,String>> myMap;
withWilds( myMap ); // Works
noWilds( myMap ); // Compiler error
}
You would think a List
of HashMap
s should be a List
of Map
s, but there's a good reason why it isn't:
Suppose you could do:
List<HashMap<String,String>> hashMaps = new ArrayList<HashMap<String,String>>();
List<Map<String,String>> maps = hashMaps; // Won't compile,
// but imagine that it could
Map<String,String> aMap = Collections.singletonMap("foo","bar"); // Not a HashMap
maps.add( aMap ); // Perfectly legal (adding a Map to a List of Maps)
// But maps and hashMaps are the same object, so this should be the same as
hashMaps.add( aMap ); // Should be illegal (aMap is not a HashMap)
So this is why a List
of HashMap
s shouldn't be a List
of Map
s.
In ReactJS, things are a bit more complicated! This is because it is a compiled environment, which follows ESLint's no-undef
rule since [email protected]
(released Oct. 1st, 2018). The documentation here is helpful to anyone interested in this problem...
In JavaScript, prior to ES6, variable and function declarations are hoisted to the top of a scope, so it's possible to use identifiers before their formal declarations in code....
This [new] rule [of ES6] will warn when it encounters a reference to an identifier that has not yet been declared.
So, while it's possible to have an undefined
(or "uninitialized") variable, it is not possible to have an undeclared variable in ReactJS without turning off the eslint rules.
This can be very frustrating -- there are so many projects on GitHub that simply take advantage of the pre-ES6 standards; and directly compiling these without any adjustments is basically impossible.
But, for ReactJS, you can use eval()
. If you have an undeclared variable like...
if(undeclaredvar) {...}
You can simply rewrite this part as...
if(eval('typeof undeclaredvar !== "undefined"')) {...}
For instance...
if(eval("false")) {
console.log("NO!");
}
if(eval("true")) {
console.log("YEAH!");
}
_x000D_
For those importing GitHub repositories into a ReactJS project, this is simply the only way to check if a variable is declared. Before closing, I'd like to remind you that there are security issues with eval()
if use incorrectly.
is just going to look for a div with class="outer inner", is that correct?
No, '.outer .inner'
will look for all elements with the .inner class that also have an element with the .outer class as an ancestor. '.outer.inner'
(no space) would give the results you're thinking of.
'.outer > .inner'
will look for immediate children of an element with the .outer class for elements with the .inner class.
Both '.outer .inner'
and '.outer > .inner'
should work for your example, although the selectors are fundamentally different and you should be wary of this.
Adding my scenario. Just in case someone has similar problem and not able to identify ACTUAL issue.
I was using vue splitpanes.
Previously it required only "Splitpanes", in latest version, they made another "Pane" component (as children of splitpanes).
Now thing is, if you don't register "Pane" component in latest version of splitpanes, it was showing error for "Splitpanes". as below.
[Vue warn]: Unknown custom element: <splitpanes> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
The interface
keyword indicates that you are declaring a traditional interface class in Java.
The @interface
keyword is used to declare a new annotation type.
See docs.oracle tutorial on annotations for a description of the syntax.
See the JLS if you really want to get into the details of what @interface
means.
When using moment.js, use:
var tz = moment.tz.guess();
It will return an IANA time zone identifier, such as America/Los_Angeles
for the US Pacific time zone.
It is documented here.
Internally, it first tries to get the time zone from the browser using the following call:
Intl.DateTimeFormat().resolvedOptions().timeZone
If you are targeting only modern browsers that support this function, and you don't need Moment-Timezone for anything else, then you can just call that directly.
If Moment-Timezone doesn't get a valid result from that function, or if that function doesn't exist, then it will "guess" the time zone by testing several different dates and times against the Date
object to see how it behaves. The guess is usually a good enough approximation, but not guaranteed to exactly match the time zone setting of the computer.
You can try this.
func convertToJSONString(value: AnyObject) -> String? {
if JSONSerialization.isValidJSONObject(value) {
do{
let data = try JSONSerialization.data(withJSONObject: value, options: [])
if let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
return string as String
}
}catch{
}
}
return nil
}
You can use below method, which is quite simple.
new SelectList(items, "ID", "Name",items.Select(x=> x.Id).FirstOrDefault());
This will auto-select the first item in your list. You can modify the above query by adding a where clause.
The syntax I use is a bit different than what @Matt suggested:
find $directory -type f -name \*.in
(it's one less keystroke).
If using an interactive debugger is OK for you, you can try perldebug.
When I wanted reflection in C++ I read this article and improved upon what I saw there. Sorry, no can has. I don't own the result...but you can certainly get what I had and go from there.
I am currently researching, when I feel like it, methods to use inherit_linearly to make the definition of reflectable types much easier. I've gotten fairly far in it actually but I still have a ways to go. The changes in C++0x are very likely to be a lot of help in this area.
Edit 2: See @flodel's answer. Much better.
Try:
# assuming SFI is your data.frame
as.matrix(sapply(SFI, as.numeric))
Edit: or as @ CarlWitthoft suggested in the comments:
matrix(as.numeric(unlist(SFI)),nrow=nrow(SFI))
If you are using Bash, then use:
command >/dev/null |& grep "something"
http://www.gnu.org/software/bash/manual/bashref.html#Pipelines
I can usually resolve this problem when a computer is under my control, but it's more of a nuisance when working with a grid. When a grid is not homogenous, not all libraries may be installed, and my experience has often been that a package wasn't installed because a dependency wasn't installed. To address this, I check the following:
.libPaths()
is a good check.ldd
results for R, to be sure about shared librariesHaving encountered this quite a bit, some of these steps become fairly routine. Although #7 might seem like a good starting point, these are listed in approximate order of the frequency that I use them.
This works on the Spring Tool Suite v 3.1.0.RELEASE, but I'm guessing it's also available on Eclipse as well.
After deleting the artifacts by hand (as stated by palacsint above) in the /username/.m2
directory, re-index the files by doing the following:
Go to:
Windows->Preferences->Maven->User Settings
menu.Click the Reindex
button next to the Local Repository
text box. Click "Apply" then "OK" and you're done.
I think you are asking about Shrinking image size:
public Bitmap ShrinkBitmap(String file, int width, int height)
{
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight / (float) height);
int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth / (float) width);
if(heightRatio > 1 || widthRatio > 1)
{
if(heightRatio > widthRatio)
{
bmpFactoryOptions.inSampleSize = heightRatio;
}
else
{
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
bmpFactoryOptions.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
return bitmap;
}
Hide the body with css then show it after the page is loaded:
CSS:
html { visibility:hidden; }
Javascript
$(document).ready(function() {
document.getElementsByTagName("html")[0].style.visibility = "visible";
});
The page will go from blank to showing all content when the page is loaded, no flash of content, no watching images load etc.
These are all too long.
Just use:
new Date(System.currentTimeMillis())
private final static String MAPPING = "/foo/*";
@RequestMapping(value = MAPPING, method = RequestMethod.GET)
public @ResponseBody void foo(HttpServletRequest request, HttpServletResponse response) {
final String mapping = getMapping("foo").replace("*", "");
final String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
final String restOfPath = url.replace(mapping, "");
System.out.println(restOfPath);
}
private String getMapping(String methodName) {
Method methods[] = this.getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName() == methodName) {
String mapping[] = methods[i].getAnnotation(RequestMapping.class).value();
if (mapping.length > 0) {
return mapping[mapping.length - 1];
}
}
}
return null;
}
to get all remote branches use this :
git fetch --all
then checkout to the branch :
git checkout test
Try to open it with pandas:
import pandas as pd
data = pd.read_html('filename.xls')
Or try any other html python parser.
That's not a proper excel file, but an html readable with excel.
More details that help in logging
String client = request.getRemoteAddr();
logger.info("###### requested client: {} , Session ID : {} , URI :" + request.getMethod() + ":" + request.getRequestURI() + "", client, request.getSession().getId());
Map params = request.getParameterMap();
Iterator i = params.keySet().iterator();
while (i.hasNext()) {
String key = (String) i.next();
String value = ((String[]) params.get(key))[0];
logger.info("###### Request Param Name : {} , Value : {} ", key, value);
}
do a phpinfo(), and look for session.save_path. the directory there needs to have the correct permissions for the user and/or group that your webserver runs as
Besides CMAKE_GENERATOR_PLATFORM
variable, there is also the -A
switch
cmake -G "Visual Studio 16 2019" -A Win32
cmake -G "Visual Studio 16 2019" -A x64
https://cmake.org/cmake/help/v3.16/generator/Visual%20Studio%2016%202019.html#platform-selection
-A <platform-name> = Specify platform name if supported by
generator.
My turn:
https://play.golang.org/p/RifHKsX7Puh
package main
import (
"fmt"
"time"
)
func main() {
var n int = 77
v := time.Duration( 1.15 * float64(n) ) * time.Second
fmt.Printf("%v %T", v, v)
}
It helps to remember the simple fact, that underlyingly the time.Duration is a mere int64, which holds nanoseconds value.
This way, conversion to/from time.Duration becomes a formality. Just remember:
One can also make use of the tracemalloc
module from the Python standard library. It seems to work well for objects whose class is implemented in C (unlike Pympler, for instance).
A more concise solution:
this._Http.get(`${API_URL}/api/v1/data/logs`, {
params: {
logNamespace: logNamespace
}
})
Try removing package-lock.json
and the node_modules
folder:
rm package-lock.json
rm -r node_modules
So, with Perl 5.20, the new answer is:
foreach my $key (keys $ad_grp_ref->%*) {
(which has the advantage of transparently working with more complicated expressions:
foreach my $key (keys $ad_grp_obj[3]->get_ref()->%*) {
etc.)
See perlref for the full documentation.
Note: in Perl version 5.20 and 5.22, this syntax is considered experimental, so you need
use feature 'postderef';
no warnings 'experimental::postderef';
at the top of any file that uses it. Perl 5.24 and later don't require any pragmas for this feature.
If you want to set a date, DateTimePicker.Value is a DateTime object.
DateTimePicker.Value = new DateTime(2012,05,28);
This is the constructor of DateTime:
new DateTime(int year,int month,int date);
My Visual is 2012
You can use sp_lock
(and sp_lock2
), but in SQL Server 2005 onwards this is being deprecated in favour of querying sys.dm_tran_locks
:
select
object_name(p.object_id) as TableName,
resource_type, resource_description
from
sys.dm_tran_locks l
join sys.partitions p on l.resource_associated_entity_id = p.hobt_id
....but $('span', $('#foo')); doesn't work?
This method is called as providing selector context.
In this you provide a second argument to the jQuery selector. It can be any css object string just like you would pass for direct selecting or a jQuery element.
eg.
$("span",".cont1").css("background", '#F00');
The above line will select all spans within the container having the class named cont1
.
Use This function
private int dp2px(int dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
}
Well, Reflector itself is a .NET assembly so you can open Reflector.exe in Reflector to check out how it's built.
(new FileInfo(filePath)).Directory.Create()
Before writing to the file.
System.IO.FileInfo file = new System.IO.FileInfo(filePath);
file.Directory.Create(); // If the directory already exists, this method does nothing.
System.IO.File.WriteAllText(file.FullName, content);
jQuery normalises event.which
depending on whether event.which
, event.keyCode
or event.charCode
is supported by the browser:
// Add which for key events
if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
event.which = event.charCode != null ? event.charCode : event.keyCode;
}
An added benefit of .which
is that jQuery does it for mouse clicks too:
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && event.button !== undefined ) {
event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
}
Detailed steps to install Python 3.7 in CentOS or any redhat linux machine:
sudo yum -y install gcc gcc-c++ sudo yum -y install zlib zlib-devel sudo yum -y install libffi-devel ./configure make make install
Just to add an extra, if you want to install it in your pip file it can be added like this:
-e git+https://github.com/tangentlabs/django-oscar-paypal.git@issue/34/oscar-0.6#egg=django-oscar-paypal
It will be saved as an egg though.
Because you also ticked Scala, a solution without regex which easily deals with multiple quoted strings:
val text = "some string with 'the data i want' inside 'and even more data'"
text.split("'").zipWithIndex.filter(_._2 % 2 != 0).map(_._1)
res: Array[java.lang.String] = Array(the data i want, and even more data)
I haven't yet found a package to do all of the operations with a string path, so I ended up writing my own quick little package which supports insert(), get() (with default return), set() and remove() operations.
You can use dot notation, brackets, number indices, string number properties, and keys with non-word characters. Simple usage below:
> var jsocrud = require('jsocrud');
...
// Get (Read) ---
> var obj = {
> foo: [
> {
> 'key w/ non-word chars': 'bar'
> }
> ]
> };
undefined
> jsocrud.get(obj, '.foo[0]["key w/ non-word chars"]');
'bar'
I have had this problem on multiple projects converting Excel 2000 to 2010. Here is what I found which seems to be working. I made two changes, but not sure which caused the success:
1) I changed how I closed and saved the file (from close & save = true to save as the same file name and close the file:
...
Dim oFile As Object ' File being processed
...
[Where the error happens - where aArray(i) is just the name of an Excel.xlsb file]
Set oFile = GetObject(aArray(i))
...
'oFile.Close SaveChanges:=True - OLD CODE WHICH ERROR'D
'New Code
oFile.SaveAs Filename:=oFile.Name
oFile.Close SaveChanges:=False
2) I went back and looked for all of the .range in the code and made sure it was the full construct..
Application.Workbooks("workbook name").Worksheets("worksheet name").Range("G19").Value
or (not 100% sure if this is correct syntax, but this is the 'effort' i made)
ActiveSheet.Range("A1").Select
typeof
condition is used to check variable type, if you are check variable type in if-else condition
e.g.
if(typeof Varaible_Name "undefined")
{
}
input.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\r\n")
This will work if the input contains only one type of line breaks - either CR, or LF, or CR+LF.
Use a comma to specify a port number with SQL Server:
mycomputer.test.xxx.com,1234
It's not necessary to specify an instance name when specifying the port.
Lots more examples at http://www.connectionstrings.com/. It's saved me a few times.
I encountered a similar problem like this, problem was with the backend . I was using node server(Express). I had a get request from the frontend(angular) as shown below
onGetUser(){
return this.http.get("http://localhost:3000/user").pipe(map(
(response:Response)=>{
const user =response.json();
return user;
}
))
}
But it gave the following error
This is the backend code written using express without the headers
app.get('/user',async(req,res)=>{
const user=await getuser();
res.send(user);
})
After adding a header to the method problem was solved
app.get('/user',async(req,res)=>{
res.header("Access-Control-Allow-Origin", "*");
const user=await getuser();
res.send(user);
})
You can get more details about Enabling CORS on Node JS
I personally dont recommend to apply style on HTML tag, it might have after effects somewhere later part of the development.
so i personally suggest to apply background-image property to the body tag.
body{
width:100%;
height: 100%;
background-image: url("./images/bg.jpg");
background-position: center;
background-size: 100% 100%;
background-repeat: no-repeat;
}
This simple trick solved my problem. this works for most of the screens larger/smaller ones.
there are so many ways to do it, i found this the simpler with minimum after effects
To answer the question more generally, the answer is:
select: function( event , ui ) {
alert( "You selected: " + ui.item.label );
}
Complete example :
$('#test').each(function(i, el) {_x000D_
var that = $(el);_x000D_
that.autocomplete({_x000D_
source: ['apple','banana','orange'],_x000D_
select: function( event , ui ) {_x000D_
alert( "You selected: " + ui.item.label );_x000D_
}_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>_x000D_
_x000D_
Type a fruit here: <input type="text" id="test" />
_x000D_
Drag and drop
Simply drag-and-drop the apk file into your emulator.
You can also run your android emulator without Android Studio.
If you are using Action, Actionforward way to process business logic and next page to show, check out if redirect is called. As many others pointed out, redirecting doesn't keep your original request since it is basically forcing you to make a new request to designated path. So the value set in original request will be vanished if you use redirection instead of requestdispatch.
SMS Push uses SMS as a carrier, WAP uses download via WAP.
I created a function, that removes the white spaces from the either ends of string. Such as
" Hello World "
, will be converted into "Hello world"
.
This works similar to strip
, lstrip
and rstrip
functions, which are frequently used in python.
string strip(string str) {
while (str[str.length() - 1] == ' ') {
str = str.substr(0, str.length() - 1);
}
while (str[0] == ' ') {
str = str.substr(1, str.length() - 1);
}
return str;
}
string lstrip(string str) {
while (str[0] == ' ') {
str = str.substr(1, str.length() - 1);
}
return str;
}
string rstrip(string str) {
while (str[str.length() - 1] == ' ') {
str = str.substr(0, str.length() - 1);
}
return str;
}
For .Net 4+:
string s = "{ \"user\" : { \"id\" : 12345, \"screen_name\" : \"twitpicuser\"}}";
var serializer = new JavaScriptSerializer();
dynamic usr = serializer.DeserializeObject(s);
var UserId = usr["user"]["id"];
For .Net 2/3.5: This code should work on JSON with 1 level
samplejson.aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="System.Web.Script.Serialization" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%
string s = "{ \"id\" : 12345, \"screen_name\" : \"twitpicuser\"}";
var serializer = new JavaScriptSerializer();
Dictionary<string, object> result = (serializer.DeserializeObject(s) as Dictionary<string, object>);
var UserId = result["id"];
%>
<%=UserId %>
And for a 2 level JSON:
sample2.aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="System.Web.Script.Serialization" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%
string s = "{ \"user\" : { \"id\" : 12345, \"screen_name\" : \"twitpicuser\"}}";
var serializer = new JavaScriptSerializer();
Dictionary<string, object> result = (serializer.DeserializeObject(s) as Dictionary<string, object>);
Dictionary<string, object> usr = (result["user"] as Dictionary<string, object>);
var UserId = usr["id"];
%>
<%= UserId %>
use MD5
,
$query="INSERT INTO ptb_users (id,
user_id,
first_name,
last_name,
email )
VALUES('NULL',
'NULL',
'".$firstname."',
'".$lastname."',
'".$email."',
MD5('".$password."')
)";
but MD5
is insecure. Use SHA2
.
The easiest way is:
<h:outputText value=" " />
"use strict";
Basically it enables the strict mode.
Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.
As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.
So, there will be no major difference how "use strict";
is interpreted by the Chrome browser and Node.js.
Please read what is strict mode in JavaScript.
For more information:
ECMAScript 6 Code & strict mode. Following is brief from the specification:
10.2.1 Strict Mode Code
An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:
- Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
- Module code is always strict mode code.
- All parts of a ClassDeclaration or a ClassExpression are strict mode code.
- Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
- Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
- Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.
Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).
You can solve the problem without any new logic by just casting the thing into the number, which prevents the warning and is equivalent to the behavior in PHP 7.0 and below:
$sub_total += ((int)$item['quantity'] * (int)$product['price']);
(The answer from Daniel Schroeder is not equivalent because $sub_total would remain unset if non-numeric values are encountered. For example, if you print out $sub_total, you would get an empty string, which is probably wrong in an invoice. - by casting you make sure that $sub_total is an integer.)
On Linux/Unix, you can append files to the .gitignore file with the echo
command. For example if you want to ignore all .svn
folders, run this from the root of the project:
echo .svn/ >> .gitignore
This should do it for you:
Declare @DatePeriod datetime
Set @DatePeriod = '2011-05-30'
Select ProductName,
IsNull([1],0) as 'Week 1',
IsNull([2],0) as 'Week 2',
IsNull([3],0) as 'Week 3',
IsNull([4],0) as 'Week 4',
IsNull([5], 0) as 'Week 5'
From
(
Select ProductName,
DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, InputDate), 0), InputDate) +1 as [Weeks],
Sale as 'Sale'
From dbo.YourTable
-- Only get rows where the date is the same as the DatePeriod
-- i.e DatePeriod is 30th May 2011 then only the weeks of May will be calculated
Where DatePart(Month, InputDate)= DatePart(Month, @DatePeriod)
)p
Pivot (Sum(Sale) for Weeks in ([1],[2],[3],[4],[5])) as pv
It will calculate the week number relative to the month. So instead of week 20 for the year it will be week 2. The @DatePeriod
variable is used to fetch only rows relative to the month (in this example only for the month of May)
Output using my sample data:
TextEditingController()..text = "new text"
For me the problem was a configuration file that was missing an Element.
remove class hideByDefault. Div will remain hidden itself till value of myvalue is false.
You need to export the User.name
field so that the json
package can see it. Rename the name
field to Name
.
package main
import (
"fmt"
"encoding/json"
)
type User struct {
Name string
}
func main() {
user := &User{Name: "Frank"}
b, err := json.Marshal(user)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(b))
}
Output:
{"Name":"Frank"}
def attributeSelection():
balance = 25
print("Your SP balance is currently 25.")
strength = input("How much SP do you want to put into strength?")
balanceAfterStrength = balance - int(strength)
if balanceAfterStrength == 0:
print("Your SP balance is now 0.")
attributeConfirmation()
elif strength < 0:
print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
attributeSelection()
elif strength > balance:
print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
attributeSelection()
elif balanceAfterStrength > 0 and balanceAfterStrength < 26:
print("Ok. You're balance is now at " + str(balanceAfterStrength) + " skill points.")
else:
print("That is an invalid input. Restarting attribute selection.")
attributeSelection()
spark-csv is part of core Spark functionality and doesn't require a separate library. So you could just do for example
df = spark.read.format("csv").option("header", "true").load("csvfile.csv")
In scala,(this works for any format-in delimiter mention "," for csv, "\t" for tsv etc)
val df = sqlContext.read.format("com.databricks.spark.csv")
.option("delimiter", ",")
.load("csvfile.csv")
If you're using StringEntity
try this, using your choice of character encoding. It handles foreign characters as well.
This a system error.
Check error of the system with:
tail /var/log/httpd/error_log
It can be any reason.
One of the easiest way to remotely access ASP.net local website, without messing with adding new rules to firewall, is to use this Visual Studio extension:
Conveyor by Keyoti (Visual Studio extension)
Just install it. Every time when you run your project, it will show you URL which can be used for remote access. No other configruration required.
On newer distros (as of 2016), it seems that PIE is enabled by default so you will need to disable it explicitly when compiling.
Here's a little summary of commands which can be helpful when playing locally with buffer overflow exercises in general:
Disable canary:
gcc vuln.c -o vuln_disable_canary -fno-stack-protector
Disable DEP:
gcc vuln.c -o vuln_disable_dep -z execstack
Disable PIE:
gcc vuln.c -o vuln_disable_pie -no-pie
Disable all of protection mechanisms listed above (warning: for local testing only):
gcc vuln.c -o vuln_disable_all -fno-stack-protector -z execstack -no-pie
For 32-bit machines, you'll need to add the -m32
parameter as well.
At current, Android doesn't support Java 7, only Java 6. New features in Java 7 such as the diamond syntax are therefore not currently supported. Finding sources to support this isn't easy, but I could find that the Dalvic engine is built upon a subset of Apache Harmony which only ever supported Java up to version 6. And if you check the system requirements for developing Android apps it also states that at least JDK 6 is needed (though this of course isn't real proof, just an indication). And this says pretty much the same as I have. If I find anything more substancial, I'll add it.
Edit: It seems Java 7 support has been added since I originally wrote this answer; check the answer by Sergii Pechenizkyi.
Linked lists provide very fast insertion or deletion of a list member. Each member in a linked list contains a pointer to the next member in the list so to insert a member at position i:
The disadvantage to a linked list is that random access is not possible. Accessing a member requires traversing the list until the desired member is found.
An even cleaner and more professional look I have found is to use AngularUI Mask. Very simple to implement and the mask can be customized for other inputs as well. Then a simple required validation is all you need.
Try this:
private string GetJArrayValue(JObject yourJArray, string key)
{
foreach (KeyValuePair<string, JToken> keyValuePair in yourJArray)
{
if (key == keyValuePair.Key)
{
return keyValuePair.Value.ToString();
}
}
}
There is a bunch on here:
http://www.webservicex.net/WS/wscatlist.aspx
Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.
Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.
Please note that the solutions based on sys.exit() or any Exception may not work in a multi-threaded environment.
Since exit() ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted. (doc)
This answer from Alex Martelli for more details.
Why flush if you can commit?
As someone new to working with databases and sqlalchemy, the previous answers - that flush()
sends SQL statements to the DB and commit()
persists them - were not clear to me. The definitions make sense but it isn't immediately clear from the definitions why you would use a flush instead of just committing.
Since a commit always flushes (https://docs.sqlalchemy.org/en/13/orm/session_basics.html#committing) these sound really similar. I think the big issue to highlight is that a flush is not permanent and can be undone, whereas a commit is permanent, in the sense that you can't ask the database to undo the last commit (I think)
@snapshoe highlights that if you want to query the database and get results that include newly added objects, you need to have flushed first (or committed, which will flush for you). Perhaps this is useful for some people although I'm not sure why you would want to flush rather than commit (other than the trivial answer that it can be undone).
In another example I was syncing documents between a local DB and a remote server, and if the user decided to cancel, all adds/updates/deletes should be undone (i.e. no partial sync, only a full sync). When updating a single document I've decided to simply delete the old row and add the updated version from the remote server. It turns out that due to the way sqlalchemy is written, order of operations when committing is not guaranteed. This resulted in adding a duplicate version (before attempting to delete the old one), which resulted in the DB failing a unique constraint. To get around this I used flush()
so that order was maintained, but I could still undo if later the sync process failed.
See my post on this at: Is there any order for add versus delete when committing in sqlalchemy
Similarly, someone wanted to know whether add order is maintained when committing, i.e. if I add object1
then add object2
, does object1
get added to the database before object2
Does SQLAlchemy save order when adding objects to session?
Again, here presumably the use of a flush() would ensure the desired behavior. So in summary, one use for flush is to provide order guarantees (I think), again while still allowing yourself an "undo" option that commit does not provide.
Autoflush and Autocommit
Note, autoflush can be used to ensure queries act on an updated database as sqlalchemy will flush before executing the query. https://docs.sqlalchemy.org/en/13/orm/session_api.html#sqlalchemy.orm.session.Session.params.autoflush
Autocommit is something else that I don't completely understand but it sounds like its use is discouraged: https://docs.sqlalchemy.org/en/13/orm/session_api.html#sqlalchemy.orm.session.Session.params.autocommit
Memory Usage
Now the original question actually wanted to know about the impact of flush vs. commit for memory purposes. As the ability to persist or not is something the database offers (I think), simply flushing should be sufficient to offload to the database - although committing shouldn't hurt (actually probably helps - see below) if you don't care about undoing.
sqlalchemy uses weak referencing for objects that have been flushed: https://docs.sqlalchemy.org/en/13/orm/session_state_management.html#session-referencing-behavior
This means if you don't have an object explicitly held onto somewhere, like in a list or dict, sqlalchemy won't keep it in memory.
However, then you have the database side of things to worry about. Presumably flushing without committing comes with some memory penalty to maintain the transaction. Again, I'm new to this but here's a link that seems to suggest exactly this: https://stackoverflow.com/a/15305650/764365
In other words, commits should reduce memory usage, although presumably there is a trade-off between memory and performance here. In other words, you probably don't want to commit every single database change, one at a time (for performance reasons), but waiting too long will increase memory usage.
First page (scroll down to see the second page)_x000D_
<div style="break-after:page"></div>_x000D_
Second page_x000D_
<br>_x000D_
<br>_x000D_
<button onclick="window.print();return false;" />Print (to see the result) </button>
_x000D_
Just add this where you need the page to go to the next one (the text "page 1" will be on page 1 and the text "page 2" will be on the second page).
Page 1
<div style='page-break-after:always'></div>
Page 2
This works too:
First page (there is a break after this)
<div style="break-after:page"></div>
Second page (This will be printed in the second page)
You can use the centos-sclo-rh-testing repo to install GCC v7 without having to compile it forever, also enable V7 by default and let you switch between different versions if required.
sudo yum install -y yum-utils centos-release-scl;
sudo yum -y --enablerepo=centos-sclo-rh-testing install devtoolset-7-gcc;
echo "source /opt/rh/devtoolset-7/enable" | sudo tee -a /etc/profile;
source /opt/rh/devtoolset-7/enable;
gcc --version;
I don't know if you fixed it, but I did had the same issue, finally it was a dumb thing, I had:
<script src="jquery-ui/jquery-ui.min.css" rel="stylesheet">
but it should be:
<link href="jquery-ui/jquery-ui.min.css" rel="stylesheet">
Just change <scrip>
to <link>
and src
to href
Is there a certain form which one should choose?
You can choose either. Its matter of choice. All are equivalent. while(1) {}/while(true){}
is frequently used for infinite loop by programmers.
git config --global --unset http.proxy
git config --unset http.proxy
http_proxy=""
In pointer to an integer if pointer is incremented then it goes next integer.
in array of pointer if pointer is incremented it jumps to next array
Without any configuration, you can simply issue the following command (modifying myusername
and mydomain
with your own information):
cntlm -u myusername -d mydomain -H
or
cntlm -u myusername@mydomain -H
It will ask you the password of myusername
and will give you the following output:
PassLM 1AD35398BE6565DDB5C4EF70C0593492
PassNT 77B9081511704EE852F94227CF48A793
PassNTLMv2 A8FC9092D566461E6BEA971931EF1AEC # Only for user 'myusername', domain 'mydomain'
Then create the file cntlm.ini
(or cntlm.conf
on Linux using default path) with the following content (replacing your myusername
, mydomain
and A8FC9092D566461E6BEA971931EF1AEC
with your information and the result of the previous command):
Username myusername
Domain mydomain
Proxy my_proxy_server.com:80
NoProxy 127.0.0.*, 192.168.*
Listen 127.0.0.1:5865
Gateway yes
SOCKS5Proxy 5866
Auth NTLMv2
PassNTLMv2 A8FC9092D566461E6BEA971931EF1AEC
Then you will have a local open proxy on local port 5865
and another one understanding SOCKS5 protocol at local port 5866
.
Batteries included
while 1:
phrase = raw_input("Could you please give me a phrase to encrypt?\n")
if phrase == "" : break
print "Here it is your phrase, encrypted:"
print phrase.encode("rot_13")
print "Have a nice afternoon!"
https://docs.python.org/2/library/codecs.html#python-specific-encodings
Python 3 update
The fine docs say
[Now the
rot_13
] codec provides a text transform: astr
tostr
mapping. It is not supported bystr.encode()
(which only produces bytes output).
Or, in other words, you have to import encode
from the codecs
module and use it with the string to be encoded as its first argument
from codecs import decode
...
print(encode(phrase, 'rot13'))
Use this, one function solve all problems of comma and quote:
public static DataTable CsvToDataTable(string strFilePath)
{
if (File.Exists(strFilePath))
{
string[] Lines;
string CSVFilePathName = strFilePath;
Lines = File.ReadAllLines(CSVFilePathName);
while (Lines[0].EndsWith(","))
{
Lines[0] = Lines[0].Remove(Lines[0].Length - 1);
}
string[] Fields;
Fields = Lines[0].Split(new char[] { ',' });
int Cols = Fields.GetLength(0);
DataTable dt = new DataTable();
//1st row must be column names; force lower case to ensure matching later on.
for (int i = 0; i < Cols; i++)
dt.Columns.Add(Fields[i], typeof(string));
DataRow Row;
int rowcount = 0;
try
{
string[] ToBeContinued = new string[]{};
bool lineToBeContinued = false;
for (int i = 1; i < Lines.GetLength(0); i++)
{
if (!Lines[i].Equals(""))
{
Fields = Lines[i].Split(new char[] { ',' });
string temp0 = string.Join("", Fields).Replace("\"\"", "");
int quaotCount0 = temp0.Count(c => c == '"');
if (Fields.GetLength(0) < Cols || lineToBeContinued || quaotCount0 % 2 != 0)
{
if (ToBeContinued.GetLength(0) > 0)
{
ToBeContinued[ToBeContinued.Length - 1] += "\n" + Fields[0];
Fields = Fields.Skip(1).ToArray();
}
string[] newArray = new string[ToBeContinued.Length + Fields.Length];
Array.Copy(ToBeContinued, newArray, ToBeContinued.Length);
Array.Copy(Fields, 0, newArray, ToBeContinued.Length, Fields.Length);
ToBeContinued = newArray;
string temp = string.Join("", ToBeContinued).Replace("\"\"", "");
int quaotCount = temp.Count(c => c == '"');
if (ToBeContinued.GetLength(0) >= Cols && quaotCount % 2 == 0 )
{
Fields = ToBeContinued;
ToBeContinued = new string[] { };
lineToBeContinued = false;
}
else
{
lineToBeContinued = true;
continue;
}
}
//modified by Teemo @2016 09 13
//handle ',' and '"'
//Deserialize CSV following Excel's rule:
// 1: If there is commas in a field, quote the field.
// 2: Two consecutive quotes indicate a user's quote.
List<int> singleLeftquota = new List<int>();
List<int> singleRightquota = new List<int>();
//combine fileds if number of commas match
if (Fields.GetLength(0) > Cols)
{
bool lastSingleQuoteIsLeft = true;
for (int j = 0; j < Fields.GetLength(0); j++)
{
bool leftOddquota = false;
bool rightOddquota = false;
if (Fields[j].StartsWith("\""))
{
int numberOfConsecutiveQuotes = 0;
foreach (char c in Fields[j]) //start with how many "
{
if (c == '"')
{
numberOfConsecutiveQuotes++;
}
else
{
break;
}
}
if (numberOfConsecutiveQuotes % 2 == 1)//start with odd number of quotes indicate system quote
{
leftOddquota = true;
}
}
if (Fields[j].EndsWith("\""))
{
int numberOfConsecutiveQuotes = 0;
for (int jj = Fields[j].Length - 1; jj >= 0; jj--)
{
if (Fields[j].Substring(jj,1) == "\"") // end with how many "
{
numberOfConsecutiveQuotes++;
}
else
{
break;
}
}
if (numberOfConsecutiveQuotes % 2 == 1)//end with odd number of quotes indicate system quote
{
rightOddquota = true;
}
}
if (leftOddquota && !rightOddquota)
{
singleLeftquota.Add(j);
lastSingleQuoteIsLeft = true;
}
else if (!leftOddquota && rightOddquota)
{
singleRightquota.Add(j);
lastSingleQuoteIsLeft = false;
}
else if (Fields[j] == "\"") //only one quota in a field
{
if (lastSingleQuoteIsLeft)
{
singleRightquota.Add(j);
}
else
{
singleLeftquota.Add(j);
}
}
}
if (singleLeftquota.Count == singleRightquota.Count)
{
int insideCommas = 0;
for (int indexN = 0; indexN < singleLeftquota.Count; indexN++)
{
insideCommas += singleRightquota[indexN] - singleLeftquota[indexN];
}
if (Fields.GetLength(0) - Cols >= insideCommas) //probabaly matched
{
int validFildsCount = insideCommas + Cols; //(Fields.GetLength(0) - insideCommas) may be exceed the Cols
String[] temp = new String[validFildsCount];
int totalOffSet = 0;
for (int iii = 0; iii < validFildsCount - totalOffSet; iii++)
{
bool combine = false;
int storedIndex = 0;
for (int iInLeft = 0; iInLeft < singleLeftquota.Count; iInLeft++)
{
if (iii + totalOffSet == singleLeftquota[iInLeft])
{
combine = true;
storedIndex = iInLeft;
break;
}
}
if (combine)
{
int offset = singleRightquota[storedIndex] - singleLeftquota[storedIndex];
for (int combineI = 0; combineI <= offset; combineI++)
{
temp[iii] += Fields[iii + totalOffSet + combineI] + ",";
}
temp[iii] = temp[iii].Remove(temp[iii].Length - 1, 1);
totalOffSet += offset;
}
else
{
temp[iii] = Fields[iii + totalOffSet];
}
}
Fields = temp;
}
}
}
Row = dt.NewRow();
for (int f = 0; f < Cols; f++)
{
Fields[f] = Fields[f].Replace("\"\"", "\""); //Two consecutive quotes indicate a user's quote
if (Fields[f].StartsWith("\""))
{
if (Fields[f].EndsWith("\""))
{
Fields[f] = Fields[f].Remove(0, 1);
if (Fields[f].Length > 0)
{
Fields[f] = Fields[f].Remove(Fields[f].Length - 1, 1);
}
}
}
Row[f] = Fields[f];
}
dt.Rows.Add(Row);
rowcount++;
}
}
}
catch (Exception ex)
{
throw new Exception( "row: " + (rowcount+2) + ", " + ex.Message);
}
//OleDbConnection connection = new OleDbConnection(string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}; Extended Properties=""text;HDR=Yes;FMT=Delimited"";", FilePath + FileName));
//OleDbCommand command = new OleDbCommand("SELECT * FROM " + FileName, connection);
//OleDbDataAdapter adapter = new OleDbDataAdapter(command);
//DataTable dt = new DataTable();
//adapter.Fill(dt);
//adapter.Dispose();
return dt;
}
else
return null;
//OleDbConnection connection = new OleDbConnection(string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}; Extended Properties=""text;HDR=Yes;FMT=Delimited"";", strFilePath));
//OleDbCommand command = new OleDbCommand("SELECT * FROM " + strFileName, connection);
//OleDbDataAdapter adapter = new OleDbDataAdapter(command);
//DataTable dt = new DataTable();
//adapter.Fill(dt);
//return dt;
}
Über
is the German word for above
or over
(it's actually cognate with the English over
).
Hence, in this context, an uber-jar is an "over-jar", one level up from a simple JAR (a), defined as one that contains both your package and all its dependencies in one single JAR file. The name can be thought to come from the same stable as ultrageek, superman, hyperspace, and metadata, which all have similar meanings of "beyond the normal".
The advantage is that you can distribute your uber-jar and not care at all whether or not dependencies are installed at the destination, as your uber-jar actually has no dependencies.
All the dependencies of your own stuff within the uber-jar are also within that uber-jar. As are all dependencies of those dependencies. And so on.
(a) I probably shouldn't have to explain what a JAR is to a Java developer but I'll include it for completeness. It's a Java archive, basically a single file that typically contains a number of Java class files along with associated metadata and resources.
I have Jenkins 1.639 installed on SLES 11 SP3 via zypper (the package manager). Installation configured jenkins as a service
# service jenkins
Usage: /etc/init.d/jenkins {start|stop|status|try-restart|restart|force-reload|reload|probe}
Although /etc/init.d/jenkins
sources /etc/sysconfig/jenkins
, any env variables set there are not inherited by the jenkins process because it is started in a separate login shell with a new environment like this:
startproc -n 0 -s -e -l /var/log/jenkins.rc -p /var/run/jenkins.pid -t 1 /bin/su -l -s /bin/bash -c '/usr/java/default/bin/java -Djava.awt.headless=true -DJENKINS_HOME=/var/lib/jenkins -jar /usr/lib/jenkins/jenkins.war --javaHome=/usr/java/default --logfile=/var/log/jenkins/jenkins.log --webroot=/var/cache/jenkins/war --httpPort=8080 --ajp13Port=8009 --debug=9 --handlerCountMax=100 --handlerCountMaxIdle=20 &' jenkins
The way I managed to set env vars for the jenkins process is via .bashrc
in its home directory - /var/lib/jenkins
. I had to create /var/lib/jenkins/.bashrc
as it did not exist before.
LINQ-to-Objects generally is going to add some marginal overheads (multiple iterators, etc). It still has to do the loops, and has delegate invokes, and will generally have to do some extra dereferencing to get at captured variables etc. In most code this will be virtually undetectable, and more than afforded by the simpler to understand code.
With other LINQ providers like LINQ-to-SQL, then since the query can filter at the server it should be much better than a flat foreach
, but most likely you wouldn't have done a blanket "select * from foo"
anyway, so that isn't necessarily a fair comparison.
Re PLINQ; parallelism may reduce the elapsed time, but the total CPU time will usually increase a little due to the overheads of thread management etc.
Window
is the main JavaScript object root, aka the global object
in a browser, also can be treated as the root of the document object model. You can access it as window
window.screen
or just screen
is a small information object about physical screen dimensions.
window.document
or just document
is the main object of the potentially visible (or better yet: rendered) document object model/DOM.
Since window
is the global object you can reference any properties of it with just the property name - so you do not have to write down window.
- it will be figured out by the runtime.
You could run: mvn exec:exec -Dexec.args="arg1"
.
This will pass the argument arg1 to your program.
You should specify the main class fully qualified, for example, a Main.java that is in a package test would need
mvn exec:java -Dexec.mainClass=test.Main
By using the -f
parameter, as decribed here, you can also run it from other directories.
mvn exec:java -Dexec.mainClass=test.Main -f folder/pom.xm
For multiple arguments, simply separate them with a space as you would at the command line.
mvn exec:java -Dexec.mainClass=test.Main -Dexec.args="arg1 arg2 arg3"
For arguments separated with a space, you can group using 'argument separated with space'
inside the quotation marks.
mvn exec:java -Dexec.mainClass=test.Main -Dexec.args="'argument separated with space' 'another one'"
Using bash
:
echo "|${COMMAND/$'\n'}|"
(Note that the control character in this question is a 'newline' (\n
), not a carriage return (\r
); the latter would have output REBOOT|
on a single line.)
Uses the Bash Shell Parameter Expansion ${parameter/pattern/string}
:
The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. [...] If string is null, matches of pattern are deleted and the / following pattern may be omitted.
Also uses the $''
ANSI-C quoting construct to specify a newline as $'\n'
. Using a newline directly would work as well, though less pretty:
echo "|${COMMAND/
}|"
#!/bin/bash
COMMAND="$'\n'REBOOT"
echo "|${COMMAND/$'\n'}|"
# Outputs |REBOOT|
Or, using newlines:
#!/bin/bash
COMMAND="
REBOOT"
echo "|${COMMAND/
}|"
# Outputs |REBOOT|
Ugh, just spent an hour trying to figure this out. In my case I had a background set, however it was set to a color. This is not enough, you need to have the background of the view set to a drawable.
e.g. This won't have a shadow:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="165dp"
android:background="@color/ight_grey"
android:elevation="20dp"
android:orientation="vertical"
/>
but this will
<LinearLayout
android:layout_width="match_parent"
android:layout_height="165dp"
android:background="@drawable/selector_grey"
android:elevation="20dp"
android:orientation="vertical"
/>
EDIT: Have also discovered that if you use a selector as a background, if you don't have the corner set then the shadow won't show up in the Preview window but it will show up on the device
e.g. This doesn't have a shadow in preview:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/white" />
<stroke
android:width="1dp"
android:color="@color/grey"/>
</shape>
</item>
</selector>
but this does:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/white" />
<corners android:radius="1dp" />
<stroke
android:width="1dp"
android:color="@color/grey"/>
</shape>
</item>
</selector>
You should have a look at env.js. See my blog for an example how to write unit tests with env.js.
This is how I fixed it:
IIF(ValueA != 0, Total / ValueA, 0)
It can be wrapped in an update:
SET Pct = IIF(ValueA != 0, Total / ValueA, 0)
Or in a select:
SELECT IIF(ValueA != 0, Total / ValueA, 0) AS Pct FROM Tablename;
Thoughts?
This tool saved me a lot, since I have no Admin permission on my machine and already had nodejs installed. For some reason the configuration on my network does not give me access to other machines just pointing the IP on the browser.
# Using a local.dev vhost
$ browser-sync start --proxy
# Using a local.dev vhost with PORT
$ browser-sync start --proxy local.dev:8001
# Using a localhost address
$ browser-sync start --proxy localhost:8001
# Using a localhost address in a sub-dir
$ browser-sync start --proxy localhost:8080/site1
That's because you created a Web Site instead of a Web Application. The cs/vb
files can only be seen in a Web Application, but in a website you can't have a separate cs/vb
file.
Edit: In the website you can add a cs file behavior like..
<%@ Application CodeFile="Global.asax.cs" Inherits="ApplicationName.MyApplication" Language="C#" %>
~/Global.asax.cs:
namespace ApplicationName
{
public partial class MyApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
}
}
}
You are seeing the ffffff
because char
is signed on your system. In C, vararg functions such as printf
will promote all integers smaller than int
to int
. Since char
is an integer (8-bit signed integer in your case), your chars are being promoted to int
via sign-extension.
Since c0
and 80
have a leading 1-bit (and are negative as an 8-bit integer), they are being sign-extended while the others in your sample don't.
char int
c0 -> ffffffc0
80 -> ffffff80
61 -> 00000061
Here's a solution:
char ch = 0xC0;
printf("%x", ch & 0xff);
This will mask out the upper bits and keep only the lower 8 bits that you want.
CASE
WHEN ebv.db_no = 22978 OR
ebv.db_no = 23218 OR
ebv.db_no = 23219
THEN 'WECS 9500'
ELSE 'WECS 9520'
END as wecs_system
My solution was to have a proxy server accept REST, issue the SOAP request, and return result, using PHP.
Time to implement: 15-30 minutes.
Not most elegant, but solid.
dict(zip([1,2,3,4], [a,b,c,d]))
If the lists are big you should use itertools.izip
.
If you have more keys than values, and you want to fill in values for the extra keys, you can use itertools.izip_longest
.
Here, a
, b
, c
, and d
are variables -- it will work fine (so long as they are defined), but you probably meant ['a','b','c','d']
if you want them as strings.
zip
takes the first item from each iterable and makes a tuple, then the second item from each, etc. etc.
dict
can take an iterable of iterables, where each inner iterable has two items -- it then uses the first as the key and the second as the value for each item.
You could create a view with your criteria and then export the view?
This worked for me
.container {
overflow: hidden;
....
}
#sidebar {
margin-bottom: -5000px; /* any large number will do */
padding-bottom: 5000px;
....
}
as compared from the answer gven by mic... it doesnt validate anything in some of the platforms which i work upon... to be precise it doesnt actually work out in Dream Viewer..
hereby.. i re-write it again..which will work on any platform.. "^[0-9]+(.[0-9]{1,2})?$".. thnkss..
Are you looking for this selector?:
.ui-menu .ui-menu-item a{
background:red;
height:10px;
font-size:8px;
}
Ugly demo:
Just replace with your code:
.ui-menu .ui-menu-item a{
color: #96f226;
border-radius: 0px;
border: 1px solid #454545;
}
jQuery 1.4 also includes a .delay( duration, [ queueName ] ) method if you only need it to trigger once and have already started using that version.
$('#foo').slideUp(300).delay(800).fadeIn(400);
Ooops....my mistake you were looking for an event to continue triggering. I'll leave this here, someone may find it helpful.
OPTIONS tells you things such as "What methods are allowed for this resource".
HEAD gets the HTTP header you would get if you made a GET request, but without the body. This lets the client determine caching information, what content-type would be returned, what status code would be returned. The availability is only a small part of it.
var attr, object_information='';
for(attr in object){
//Get names and values of propertys with style (name : value)
object_information += attr + ' : ' + object[attr] + '\n';
}
alert(object_information); //Show all Object
Typescript implementation based on top rated answer
/** Represents the `setTimeout` with an ability to perform pause/resume actions */
export class Timer {
private _start: Date;
private _remaining: number;
private _durationTimeoutId?: NodeJS.Timeout;
private _callback: (...args: any[]) => void;
private _done = false;
get done () {
return this._done;
}
constructor(callback: (...args: any[]) => void, ms = 0) {
this._callback = () => {
callback();
this._done = true;
};
this._remaining = ms;
this.resume();
}
/** pauses the timer */
pause(): Timer {
if (this._durationTimeoutId && !this._done) {
this._clearTimeoutRef();
this._remaining -= new Date().getTime() - this._start.getTime();
}
return this;
}
/** resumes the timer */
resume(): Timer {
if (!this._durationTimeoutId && !this._done) {
this._start = new Date;
this._durationTimeoutId = setTimeout(this._callback, this._remaining);
}
return this;
}
/**
* clears the timeout and marks it as done.
*
* After called, the timeout will not resume
*/
clearTimeout() {
this._clearTimeoutRef();
this._done = true;
}
private _clearTimeoutRef() {
if (this._durationTimeoutId) {
clearTimeout(this._durationTimeoutId);
this._durationTimeoutId = undefined;
}
}
}
I don't like ActionView
based solutions,
my idea is:
TextView
, that TextView
will be populated by
applicationwhen you need to draw a MenuItem
:
2.1. inflate layout
2.2. call measure()
& layout()
(otherwise view
will be 0px x 0px, it's too small for most use cases)
2.3. set the TextView
's text
2.4. make "screenshot" of the view
2.6. set MenuItem
's icon based on bitmap created on 2.4
profit!
so, result should be something like
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/counterPanel" android:layout_width="32dp" android:layout_height="32dp" android:background="@drawable/ic_menu_gallery"> <RelativeLayout android:id="@+id/counterValuePanel" android:layout_width="wrap_content" android:layout_height="wrap_content" > <ImageView android:id="@+id/counterBackground" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/unread_background" /> <TextView android:id="@+id/count" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="1" android:textSize="8sp" android:layout_centerInParent="true" android:textColor="#FFFFFF" /> </RelativeLayout> </FrameLayout>
@drawable/unread_background
is that green TextView
's background,
@drawable/ic_menu_gallery
is not really required here, it's just to preview layout's result in IDE.
add code into onCreateOptionsMenu
/onPrepareOptionsMenu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem menuItem = menu.findItem(R.id.testAction);
menuItem.setIcon(buildCounterDrawable(count, R.drawable.ic_menu_gallery));
return true;
}
Implement build-the-icon method:
private Drawable buildCounterDrawable(int count, int backgroundImageId) {
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.counter_menuitem_layout, null);
view.setBackgroundResource(backgroundImageId);
if (count == 0) {
View counterTextPanel = view.findViewById(R.id.counterValuePanel);
counterTextPanel.setVisibility(View.GONE);
} else {
TextView textView = (TextView) view.findViewById(R.id.count);
textView.setText("" + count);
}
view.measure(
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.setDrawingCacheEnabled(true);
view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
return new BitmapDrawable(getResources(), bitmap);
}
The complete code is here: https://github.com/cvoronin/ActionBarMenuItemCounter
Search for EnableOptimizations
keyword in your project
So if you find
BundleTable.EnableOptimizations = true;
turn it false
.
This does disable minification, And it also disables bundling entirely
Use the formatting options available to you, use the Decimal format string. It is far more flexible and requires little to no maintenance compared to direct string manipulation.
To get the string representation using at least 4 digits:
int length = 4;
int number = 50;
string asString = number.ToString("D" + length); //"0050"
Using domain Name may solve the problem (get domain name using powershell: $env:userdomain):
Hashtable<String, Object> env = new Hashtable<String, Object>();
String principalName = "domainName\\userName";
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://URL:389/OU=ou-xx,DC=fr,DC=XXXXXX,DC=com");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, principalName);
env.put(Context.SECURITY_CREDENTIALS, "Your Password");
try {
DirContext authContext = new InitialDirContext(env);
// user is authenticated
System.out.println("USER IS AUTHETICATED");
} catch (AuthenticationException ex) {
// Authentication failed
System.out.println("AUTH FAILED : " + ex);
} catch (NamingException ex) {
ex.printStackTrace();
}
<head>
tags in a HTML page.A favicon (short for favorites icon), also known as a shortcut icon, website icon, URL icon, or bookmark icon is a 16×16 or 32×32 pixel square icon associated with a particular website or webpage.
.ico
image file that is either 16x16 pixels or 32x32 pixels. Then, in the web pages, add <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
to the <head>
element.pull
:adb pull "/sdcard/Folder1"
Output:
adb pull "/sdcard/Folder1"
pull: building file list...
pull: /sdcard/Folder1/image1.jpg -> ./image1.jpg
pull: /sdcard/Folder1/image2.jpg -> ./image2.jpg
pull: /sdcard/Folder1/image3.jpg -> ./image3.jpg
3 files pulled. 0 files skipped.
find
from BusyBox
:adb shell find "/sdcard/Folder1" -iname "*.jpg" | tr -d '\015' | while read line; do adb pull "$line"; done;
Here is an explanation:
adb shell find "/sdcard/Folder1" - use the find command, use the top folder
-iname "*.jpg" - filter the output to only *.jpg files
| - passes data(output) from one command to another
tr -d '\015' - explained here: http://stackoverflow.com/questions/9664086/bash-is-removing-commands-in-while
while read line; - while loop to read input of previous commands
do adb pull "$line"; done; - pull the files into the current running directory, finish. The quotation marks around $line are required to work with filenames containing spaces.
The scripts will start in the top folder and recursively go down and find all the "*.jpg" files and pull them from your phone to the current directory.
If you are looking for features that notebooks in JupyterLab have that traditional Jupyter Notebooks do not, check out the JupyterLab notebooks documentation. There is a simple video showing how to use each of the features in the documentation link.
JupyterLab notebooks have the following features and more:
It's easy in VS2012; just use the change mapping feature: