Move the queue to self instead of as an argument to your functions package
and send
The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.
If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.
Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.
In the sender you set:
byte [] IP= { (byte)192, (byte)168, 1, 106 };
InetAddress address = InetAddress.getByAddress(IP);
but might be simpler to use the address in string form:
InetAddress address = InetAddress.getByName("192.168.1.106");
In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.
Here's a simple UDP Receiver that works :
import java.io.IOException;
import java.net.*;
public class Receiver {
public static void main(String[] args) {
int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
new Receiver().run(port);
}
public void run(int port) {
try {
DatagramSocket serverSocket = new DatagramSocket(port);
byte[] receiveData = new byte[8];
String sendString = "polo";
byte[] sendData = sendString.getBytes("UTF-8");
System.out.printf("Listening on udp:%s:%d%n",
InetAddress.getLocalHost().getHostAddress(), port);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
while(true)
{
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData(), 0,
receivePacket.getLength() );
System.out.println("RECEIVED: " + sentence);
// now send acknowledgement packet back to sender
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
receivePacket.getAddress(), receivePacket.getPort());
serverSocket.send(sendPacket);
}
} catch (IOException e) {
System.out.println(e);
}
// should close serverSocket in finally block
}
}
Maybe just a bit of trivia, but UPnP will use HTTP formatted messages over UDP for device discovery.
Why so complicated?
I solved my problem this way simply:
<pre>{{existingCategory+thisCategory}}</pre>
It will make <br />
automatically if the string contains '\n' that contain when I was saving data from textarea.
It Seems fine to me (or raw_input()
in Python 2.X). Alternatively, you could use time.sleep()
if you want to pause for a certain number of seconds.
import time
print("something")
time.sleep(5.5) # Pause 5.5 seconds
print("something")
Wrap your formula with IFERROR
.
=IFERROR(yourformula)
run this code it will get activated if you on a windows machine
source venv/Scripts/activate
You can use jQuery bind:
$(window).bind('keydown', function(e){
if (e.keyCode == 37) {
console.log('left');
} else if (e.keyCode == 38) {
console.log('up');
} else if (e.keyCode == 39) {
console.log('right');
} else if (e.keyCode == 40) {
console.log('down');
}
});
The advice isn't that you should never use True
, False
, or None
. It's just that you shouldn't use if x == True
.
if x == True
is silly because ==
is just a binary operator! It has a return value of either True
or False
, depending on whether its arguments are equal or not. And if condition
will proceed if condition
is true. So when you write if x == True
Python is going to first evaluate x == True
, which will become True
if x
was True
and False
otherwise, and then proceed if the result of that is true. But if you're expecting x
to be either True
or False
, why not just use if x
directly!
Likewise, x == False
can usually be replaced by not x
.
There are some circumstances where you might want to use x == True
. This is because an if
statement condition is "evaluated in Boolean context" to see if it is "truthy" rather than testing exactly against True
. For example, non-empty strings, lists, and dictionaries are all considered truthy by an if statement, as well as non-zero numeric values, but none of those are equal to True
. So if you want to test whether an arbitrary value is exactly the value True
, not just whether it is truthy, when you would use if x == True
. But I almost never see a use for that. It's so rare that if you do ever need to write that, it's worth adding a comment so future developers (including possibly yourself) don't just assume the == True
is superfluous and remove it.
Using x is True
instead is actually worse. You should never use is
with basic built-in immutable types like Booleans (True
, False
), numbers, and strings. The reason is that for these types we care about values, not identity. ==
tests that values are the same for these types, while is
always tests identities.
Testing identities rather than values is bad because an implementation could theoretically construct new Boolean values rather than go find existing ones, leading to you having two True
values that have the same value, but they are stored in different places in memory and have different identities. In practice I'm pretty sure True
and False
are always reused by the Python interpreter so this won't happen, but that's really an implementation detail. This issue trips people up all the time with strings, because short strings and literal strings that appear directly in the program source are recycled by Python so 'foo' is 'foo'
always returns True
. But it's easy to construct the same string 2 different ways and have Python give them different identities. Observe the following:
>>> stars1 = ''.join('*' for _ in xrange(100))
>>> stars2 = '*' * 100
>>> stars1 is stars2
False
>>> stars1 == stars2
True
EDIT: So it turns out that Python's equality on Booleans is a little unexpected (at least to me):
>>> True is 1
False
>>> True == 1
True
>>> True == 2
False
>>> False is 0
False
>>> False == 0
True
>>> False == 0.0
True
The rationale for this, as explained in the notes when bools were introduced in Python 2.3.5, is that the old behaviour of using integers 1 and 0 to represent True and False was good, but we just wanted more descriptive names for numbers we intended to represent truth values.
One way to achieve that would have been to simply have True = 1
and False = 0
in the builtins; then 1 and True really would be indistinguishable (including by is
). But that would also mean a function returning True
would show 1
in the interactive interpreter, so what's been done instead is to create bool
as a subtype of int
. The only thing that's different about bool
is str
and repr
; bool
instances still have the same data as int
instances, and still compare equality the same way, so True == 1
.
So it's wrong to use x is True
when x
might have been set by some code that expects that "True is just another way to spell 1", because there are lots of ways to construct values that are equal to True
but do not have the same identity as it:
>>> a = 1L
>>> b = 1L
>>> c = 1
>>> d = 1.0
>>> a == True, b == True, c == True, d == True
(True, True, True, True)
>>> a is b, a is c, a is d, c is d
(False, False, False, False)
And it's wrong to use x == True
when x
could be an arbitrary Python value and you only want to know whether it is the Boolean value True
. The only certainty we have is that just using x
is best when you just want to test "truthiness". Thankfully that is usually all that is required, at least in the code I write!
A more sure way would be x == True and type(x) is bool
. But that's getting pretty verbose for a pretty obscure case. It also doesn't look very Pythonic by doing explicit type checking... but that really is what you're doing when you're trying to test precisely True
rather than truthy; the duck typing way would be to accept truthy values and allow any user-defined class to declare itself to be truthy.
If you're dealing with this extremely precise notion of truth where you not only don't consider non-empty collections to be true but also don't consider 1 to be true, then just using x is True
is probably okay, because presumably then you know that x
didn't come from code that considers 1 to be true. I don't think there's any pure-python way to come up with another True
that lives at a different memory address (although you could probably do it from C), so this shouldn't ever break despite being theoretically the "wrong" thing to do.
And I used to think Booleans were simple!
End Edit
In the case of None
, however, the idiom is to use if x is None
. In many circumstances you can use if not x
, because None
is a "falsey" value to an if
statement. But it's best to only do this if you're wanting to treat all falsey values (zero-valued numeric types, empty collections, and None
) the same way. If you are dealing with a value that is either some possible other value or None
to indicate "no value" (such as when a function returns None
on failure), then it's much better to use if x is None
so that you don't accidentally assume the function failed when it just happened to return an empty list, or the number 0.
My arguments for using ==
rather than is
for immutable value types would suggest that you should use if x == None
rather than if x is None
. However, in the case of None
Python does explicitly guarantee that there is exactly one None
in the entire universe, and normal idiomatic Python code uses is
.
Regarding whether to return None
or raise an exception, it depends on the context.
For something like your get_attr
example I would expect it to raise an exception, because I'm going to be calling it like do_something_with(get_attr(file))
. The normal expectation of the callers is that they'll get the attribute value, and having them get None
and assume that was the attribute value is a much worse danger than forgetting to handle the exception when you can actually continue if the attribute can't be found. Plus, returning None
to indicate failure means that None
is not a valid value for the attribute. This can be a problem in some cases.
For an imaginary function like see_if_matching_file_exists
, that we provide a pattern to and it checks several places to see if there's a match, it could return a match if it finds one or None
if it doesn't. But alternatively it could return a list of matches; then no match is just the empty list (which is also "falsey"; this is one of those situations where I'd just use if x
to see if I got anything back).
So when choosing between exceptions and None
to indicate failure, you have to decide whether None
is an expected non-failure value, and then look at the expectations of code calling the function. If the "normal" expectation is that there will be a valid value returned, and only occasionally will a caller be able to work fine whether or not a valid value is returned, then you should use exceptions to indicate failure. If it will be quite common for there to be no valid value, so callers will be expecting to handle both possibilities, then you can use None
.
Try
mysqldump databaseExample > file.sql
I got this error when I was trying to access a url using curl:
curl 'https://example.com:80/some/page'
The solution was to change https
to http
curl 'http://example.com:80/some/page'
I wrote a module win-node-env with which you can run your command just like you would in *nix.
NODE_ENV=production node myapp/app.js
It works by creating a NODE_ENV.cmd
that sets the NODE_ENV
environment variable and spawns a child process with the rest of the command and its args.
Just install it (globally), and run your npm script commands, it should automatically make them work.
npm install -g win-node-env
Here is a sample helper class which converts an Object and returns an Expando with all public properties of the given object.
public static class dynamicHelper
{
public static ExpandoObject convertToExpando(object obj)
{
//Get Properties Using Reflections
BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = obj.GetType().GetProperties(flags);
//Add Them to a new Expando
ExpandoObject expando = new ExpandoObject();
foreach (PropertyInfo property in properties)
{
AddProperty(expando, property.Name, property.GetValue(obj));
}
return expando;
}
public static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
{
//Take use of the IDictionary implementation
var expandoDict = expando as IDictionary;
if (expandoDict.ContainsKey(propertyName))
expandoDict[propertyName] = propertyValue;
else
expandoDict.Add(propertyName, propertyValue);
}
}
Usage:
//Create Dynamic Object
dynamic expandoObj= dynamicHelper.convertToExpando(myObject);
//Add Custom Properties
dynamicHelper.AddProperty(expandoObj, "dynamicKey", "Some Value");
This thread seems unnecessarily controversial.
If you really want to solve this question correctly, using jQuery, please see the solution below.
The question is "jQuery How do you get an image to fade in on load?"
First, a quick note.
This is not a good candidate for $(document).ready...
Why? Because the document is ready when the HTML DOM is loaded. The logo image will not be ready at this point - it may still be downloading in fact!
So to answer first the general question "jQuery How do you get an image to fade in on load?" - the image in this example has an id="logo" attribute:
$("#logo").bind("load", function () { $(this).fadeIn(); });
This does exactly what the question asks. When the image has loaded, it will fade in. If you change the source of the image, when the new source has loaded, it will fade in.
There is a comment about using window.onload alongside jQuery. This is perfectly possible. It works. It can be done. However, the window.onload event needs a particular bit of care. This is because if you use it more than once, you overwrite your previous events. Example (feel free to try it...).
function SaySomething(words) {
alert(words);
}
window.onload = function () { SaySomething("Hello"); };
window.onload = function () { SaySomething("Everyone"); };
window.onload = function () { SaySomething("Oh!"); };
Of course, you wouldn't have three onload events so close together in your code. You would most likely have a script that does something onload, and then add your window.onload handler to fade in your image - "why has my slide show stopped working!!?" - because of the window.onload problem.
One great feature of jQuery is that when you bind events using jQuery, they ALL get added.
So there you have it - the question has already been marked as answered, but the answer seems to be insufficient based on all the comments. I hope this helps anyone arriving from the world's search engines!
Simply use this for the so far latest version 4.1.0.
pip install opencv-contrib-python==4.1.0.25
For default version use this:
pip install opencv-contrib-python
How about .delay()
?
$("#test").animate({"top":"-=80px"},1500)
.delay(1000)
.animate({"opacity":"0"},500);
Update: Apparently possible by passing a flag to mysql_connect()
. See Executing multiple SQL queries in one statement with PHP Nevertheless, any current reader should avoid using the mysql_
-class of functions and prefer PDO.
You can't do that using the regular mysql-api in PHP. Just execute two queries. The second one will be so fast that it won't matter. This is a typical example of micro optimization. Don't worry about it.
For the record, it can be done using mysqli and the mysqli_multi_query-function.
Compare them as other values:
if($array_a == $array_b) {
//they are the same
}
You can read about all array operators here:
http://php.net/manual/en/language.operators.array.php
Note for example that ===
also checks that the types and order of the elements in the arrays are the same.
Just use
int listCount = data.size();
That tells you how many lists there are (assuming none are null). If you want to find out how many strings there are, you'll need to iterate:
int total = 0;
for (List<String> sublist : data) {
// TODO: Null checking
total += sublist.size();
}
// total is now the total number of strings
In javascript you can use
s3.listObjects(params, function (err, result) {});
to get all objects inside bucket. you have to pass bucket name inside params (Bucket: name).
You can use len(list(generator_function())
. However, this consumes the generator, but that's the only way you can find out how many elements are generated. So you may want to save the list somewhere if you also want to use the items.
a = list(generator_function())
print(len(a))
print(a[0])
df.aree <- as.data.frame(t(df.aree))
colnames(df.aree) <- df.aree[1, ]
df.aree <- df.aree[-1, ]
df.aree$myfactor <- factor(row.names(df.aree))
Alternatively, you can use Commons Lang ArrayUtils class:
int[] arr = new int{3, 5, 1, 4, 2};
int indexOfTwo = ArrayUtils.indexOf(arr, 2);
There are overloaded variants of indexOf()
method for different array types.
None of the above solutions worked for me, however instead I wrapped my content in a div (#outer-wrap) and then used the following CSS:
body {
overflow: hidden;
}
#outer-wrap {
-webkit-overflow-scrolling: touch;
height: 100vh;
overflow: auto;
}
Obviously only works in browsers that support viewport widths/heights of course.
Wrote this method to do this very thing on my own project only with the replace file if existing logic in it.
// we use the older file i/o operations for this rather than the newer jdk7+ Files.move() operation
private boolean moveFileToDirectory(File sourceFile, String targetPath) {
File tDir = new File(targetPath);
if (tDir.exists()) {
String newFilePath = targetPath+File.separator+sourceFile.getName();
File movedFile = new File(newFilePath);
if (movedFile.exists())
movedFile.delete();
return sourceFile.renameTo(new File(newFilePath));
} else {
LOG.warn("unable to move file "+sourceFile.getName()+" to directory "+targetPath+" -> target directory does not exist");
return false;
}
}
In Python, execution does NOT have to begin at main. The first line of "executable code" is executed first.
def main():
print("main code")
def meth1():
print("meth1")
meth1()
if __name__ == "__main__":main() ## with if
Output -
meth1
main code
More on main() - http://ibiblio.org/g2swap/byteofpython/read/module-name.html
A module's __name__
Every module has a name and statements in a module can find out the name of its module. This is especially handy in one particular situation - As mentioned previously, when a module is imported for the first time, the main block in that module is run. What if we want to run the block only if the program was used by itself and not when it was imported from another module? This can be achieved using the name attribute of the module.
Using a module's __name__
#!/usr/bin/python
# Filename: using_name.py
if __name__ == '__main__':
print 'This program is being run by itself'
else:
print 'I am being imported from another module'
Output -
$ python using_name.py
This program is being run by itself
$ python
>>> import using_name
I am being imported from another module
>>>
How It Works -
Every Python module has it's __name__
defined and if this is __main__
, it implies that the module is being run standalone by the user and we can do corresponding appropriate actions.
If you wont to forward your ref
, in Props interface you need to use RefObject<CmpType>
type from import React, { RefObject } from 'react';
I believe, you need to change your code little bit like follows alongside with your database filed type.
mysql_query("INSERT INTO table (`dateposted`) VALUES ($datetime)");
Hope, will work perfectly.
Non greedy search in vim is done using {-} operator. Like this:
%s/style=".\{-}"//g
just try:
:help non-greedy
I know it's malapropos, but IMHO easy way is:
def insert (source_str, insert_str, pos):
return source_str[:pos]+insert_str+source_str[pos:]
I'd like to add on for the #else
case:
#if 0
/* Code here will NOT be complied. */
#else
/* Code will be compiled. */
#endif
#if 1
/* Code will be complied. */
#else
/* Code will NOT be compiled. */
#endif
Yeah, as others have suggested, this error seems to mean that ssh-agent is installed but its service (on windows) hasn't been started.
You can check this by running in Windows PowerShell:
> Get-Service ssh-agent
And then check the output of status is not running.
Status Name DisplayName
------ ---- -----------
Stopped ssh-agent OpenSSH Authentication Agent
Then check that the service has been disabled by running
> Get-Service ssh-agent | Select StartType
StartType
---------
Disabled
I suggest setting the service to start manually. This means that as soon as you run ssh-agent, it'll start the service. You can do this through the Services GUI or you can run the command in admin mode:
> Get-Service -Name ssh-agent | Set-Service -StartupType Manual
Alternatively, you can set it through the GUI if you prefer.
I know, old post ... but it might be helpful to leave this here.
Modern browsers are now supporting the Fetch API.
You can use it like this:
fetch("<url>")
.then(data => data.json()) // could be .text() or .blob() depending on the data you are expecting
.then(console.log); // print your data
ps: It will make all CORS checks, since it's an improved XmlHttpRequest
.
Use composition not extends (yes I mean extends, as in a reference to the extends keyword in java and yes this is inheritance). Composition is superier because it completely shields your implementation, allowing you to change the implementation without impacting the users of your class.
I recommend trying something like this (I'm typing directly into this window, so buyer beware of syntax errors):
public LimitedSizeQueue implements Queue
{
private int maxSize;
private LinkedList storageArea;
public LimitedSizeQueue(final int maxSize)
{
this.maxSize = maxSize;
storageArea = new LinkedList();
}
public boolean offer(ElementType element)
{
if (storageArea.size() < maxSize)
{
storageArea.addFirst(element);
}
else
{
... remove last element;
storageArea.addFirst(element);
}
}
... the rest of this class
A better option (based on the answer by Asaf) might be to wrap the Apache Collections CircularFifoBuffer with a generic class. For example:
public LimitedSizeQueue<ElementType> implements Queue<ElementType>
{
private int maxSize;
private CircularFifoBuffer storageArea;
public LimitedSizeQueue(final int maxSize)
{
if (maxSize > 0)
{
this.maxSize = maxSize;
storateArea = new CircularFifoBuffer(maxSize);
}
else
{
throw new IllegalArgumentException("blah blah blah");
}
}
... implement the Queue interface using the CircularFifoBuffer class
}
console.log()
and console.dir()
:Here is the difference in a nutshell:
console.log(input)
: The browser logs in a nicely formatted mannerconsole.dir(input)
: The browser logs just the object with all its propertiesThe following code:
let obj = {a: 1, b: 2};
let DOMel = document.getElementById('foo');
let arr = [1,2,3];
console.log(DOMel);
console.dir(DOMel);
console.log(obj);
console.dir(obj);
console.log(arr);
console.dir(arr);
Logs the following in google dev tools:
desired o/p: Enabling feature XYZ......Done
you can use below command
$a = "Enabling feature XYZ"
Write-output "$a......Done"
you have to add variable and statement inside quotes. hope this is helpful :)
Thanks Techiegal
You may use fnDrawCallback or fnInfoCallback to detect changes, when next is clicked both of them are fired.
But beware, page changes are not the only source that can fire those callbacks.
My problem was I was registering table view cell inside dispatch queue asynchronously. If you have registered table view source and delegate reference in storyboard then dispatch queue would delay the registration of cell as name suggests it will happen asynchronously and your table view is looking for the cells.
DispatchQueue.main.async {
self.tableView.register(CampaignTableViewCell.self, forCellReuseIdentifier: CampaignTableViewCell.identifier())
self.tableView.reloadData()
}
Either you shouldn't use dispatch queue for registration OR do this:
DispatchQueue.main.async {
self.tableView.dataSource = self
self.tableView.delegate = self
self.tableView.register(CampaignTableViewCell.self, forCellReuseIdentifier: CampaignTableViewCell.identifier())
self.tableView.reloadData()
}
The message:
Waiting for available socket...
is shown, because you've reached a limit on the ssl_socket_pool either per Host, Proxy or Group.
Here are the maximum number of HTTP connections which you can make with a Chrome browser:
Maximum per Host: 6 connections.
This is likely hardcoded in the source code of the web browser, so you can't change it.
Total 256 HTTP connections pooled per browser.
Source: Enterprise networking for Chrome devices
The above limits can be checked or flushed at chrome://net-internals/#sockets
(or in real-time at chrome://net-internals/#events&q=type:SOCKET%20is:active
).
Your issue with audio can be related to Chrome bug 162627 where HTML5 audio fails to load and it hits max simultaneous connections per server:proxy. This is still active issue at the time of writing (2016).
Much older issue related to HTML5 video request stay pending, then it's probably related to Issue #234779 which has been fixed 2014. And related to SPDY which can be found in Issue 324653: SPDY issue: waiting for available sockets, but this was already fixed in 2014, so probably it's not related.
Other related issue now marked as duplicate can be found in Issue 401845: Failure to preload audio metadata. Loaded only 6 of 10+ which was related to the problem with the media player code leaving a bunch of paused requests hanging around.
This also may be related to some Chrome adware or antivirus extensions using your sockets in the backgrounds (like Sophos or Kaspersky), so check for Network activity in DevTools.
The problem is with sprintf
sprintf(aa,"%lf",a);
%lf says to interpet "a" as a "long double" (16 bytes) but it is actually a "double" (8 bytes). Use this instead:
sprintf(aa, "%f", a);
More details here on cplusplus.com
If you write a function then once you leave it all names inside disappear.
The concept is called namespace and it's so good, it made it into the Zen of Python:
Namespaces are one honking great idea -- let's do more of those!
The namespace of IPython can likewise be reset with the magic command %reset -f
. (The -f
means "force"; in other words, "don't ask me if I really want to delete all the variables, just do it.")
if by Blue Border thats on top of the Window Form
you mean titlebar, set Forms ControlBox
property to false
and Text
property to empty string ("").
here's a snippet:
this.ControlBox = false;
this.Text = String.Empty;
You can use password from text box like key... With this code you can encrypt/decrypt text, picture, word document, pdf....
public class Rijndael
{
private byte[] key;
private readonly byte[] vector = { 255, 64, 191, 111, 23, 3, 113, 119, 231, 121, 252, 112, 79, 32, 114, 156 };
ICryptoTransform EnkValue, DekValue;
public Rijndael(byte[] key)
{
this.key = key;
RijndaelManaged rm = new RijndaelManaged();
rm.Padding = PaddingMode.PKCS7;
EnkValue = rm.CreateEncryptor(key, vector);
DekValue = rm.CreateDecryptor(key, vector);
}
public byte[] Encrypt(byte[] byte)
{
byte[] enkByte= byte;
byte[] enkNewByte;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, EnkValue, CryptoStreamMode.Write))
{
cs.Write(enkByte, 0, enkByte.Length);
cs.FlushFinalBlock();
ms.Position = 0;
enkNewByte= new byte[ms.Length];
ms.Read(enkNewByte, 0, enkNewByte.Length);
}
}
return enkNeyByte;
}
public byte[] Dekrypt(byte[] enkByte)
{
byte[] dekByte;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, DekValue, CryptoStreamMode.Write))
{
cs.Write(enkByte, 0, enkByte.Length);
cs.FlushFinalBlock();
ms.Position = 0;
dekByte= new byte[ms.Length];
ms.Read(dekByte, 0, dekByte.Length);
}
}
return dekByte;
}
}
Convert password from text box to byte array...
private byte[] ConvertPasswordToByte(string password)
{
byte[] key = new byte[32];
for (int i = 0; i < passwprd.Length; i++)
{
key[i] = Convert.ToByte(passwprd[i]);
}
return key;
}
DECLARE @IncrementValue int
SET @IncrementValue = 0
UPDATE Samples SET qty = @IncrementValue,@IncrementValue=@IncrementValue+1
I did installing watchman, changing limit etc. and it didn't work in Gulp.
Restarting iterm2 actually helped though.
Math.Ceiling
always rounds up (towards the ceiling)
Math.Floor
always rounds down (towards to floor)
what you are after is simply
Math.Round
which rounds as per this post
And in C# (.net core) using Selenium.Webdriver
and Selenium.Chrome.Webdriver
like this:
ChromeOptions options = new ChromeOptions();
options.AddArgument("--ignore-certificate-errors");
using (var driver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),options))
{
...
}
playSound is a static method in your class, but you are referring to members like audioSounds
or minTime
which are not declared static
so they would require a SoundManager sm = new SoundManager();
to operate as sm.audioSounds
or sm.minTime
respectively
Solution:
public static List<AudioSource> audioSounds = new List<AudioSource>();
public static double minTime = 0.5;
I agree with srboisvert. Don't do it on Windows. You can add Ubuntu (version of Linux) to Windows and have dual boot. It requires some work, but it is easier than going against the grain and trying to get everything working on Widows.
Ubuntu, Heroku and Git work wonderfully. Just know the learning curve is steep at first. Hire someone from Guru.com or Elance to help you.
Also, running Textmate on Mac is the preferred solution, so if you are considering getting a Mac or have access to one, that is the best thing to do. I don't think you need very much computing power...
Finally, my favorite book is Agile Web Development for Rails. Googling around doesn't work so well because most of the information is from old versions of Rails and is deprecated or doesn't work.
I went through a similar issue. If you consider your "YeagerTechResources.Resources", it means that your Resources.resx is at the root folder of your project.
Be careful to include the full path eg : "project\subfolder(s)\file[.resx]" to the ResourceManager constructor.
CommonJS modules allow two ways to define exported properties. In either case you are returning an Object/Function. Because functions are first class citizens in JavaScript they to can act just like Objects (technically they are Objects). That said your question about using the new
keywords has a simple answer: Yes. I'll illustrate...
You can either use the exports
variable provided to attach properties to it. Once required in another module those assign properties become available. Or you can assign an object to the module.exports property. In either case what is returned by require()
is a reference to the value of module.exports
.
A pseudo-code example of how a module is defined:
var theModule = {
exports: {}
};
(function(module, exports, require) {
// Your module code goes here
})(theModule, theModule.exports, theRequireFunction);
In the example above module.exports
and exports
are the same object. The cool part is that you don't see any of that in your CommonJS modules as the whole system takes care of that for you all you need to know is there is a module object with an exports property and an exports variable that points to the same thing the module.exports does.
Since you can attach a function directly to module.exports
you can essentially return a function and like any function it could be managed as a constructor (That's in italics since the only difference between a function and a constructor in JavaScript is how you intend to use it. Technically there is no difference.)
So the following is perfectly good code and I personally encourage it:
// My module
function MyObject(bar) {
this.bar = bar;
}
MyObject.prototype.foo = function foo() {
console.log(this.bar);
};
module.exports = MyObject;
// In another module:
var MyObjectOrSomeCleverName = require("./my_object.js");
var my_obj_instance = new MyObjectOrSomeCleverName("foobar");
my_obj_instance.foo(); // => "foobar"
Same thing goes for non-constructor like functions:
// My Module
exports.someFunction = function someFunction(msg) {
console.log(msg);
}
// In another module
var MyModule = require("./my_module.js");
MyModule.someFunction("foobar"); // => "foobar"
Check this out,
body {
background-color: black;
background: url(img/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Just wrap your WebElement into Select Object as shown below
Select dropdown = new Select(driver.findElement(By.id("identifier")));
Once this is done you can select the required value in 3 ways. Consider an HTML file like this
<html>
<body>
<select id = "designation">
<option value = "MD">MD</option>
<option value = "prog"> Programmer </option>
<option value = "CEO"> CEO </option>
</option>
</select>
<body>
</html>
Now to identify dropdown do
Select dropdown = new Select(driver.findElement(By.id("designation")));
To select its option say 'Programmer' you can do
dropdown.selectByVisibleText("Programmer ");
or
dropdown.selectByIndex(1);
or
dropdown.selectByValue("prog");
Happy Coding :)
Here is a workaround to copy all the objects from one arrayList to another:
ArrayList<Object> myObject = new ArrayList<Object>();
ArrayList<Object> myTempObject = new ArrayList<Object>();
myObject.addAll(myTempObject.subList(0, myTempObject.size()));
subList is intended to return a List with a range of data. so you can copy the whole arrayList or part of it.
Support, unfortunately, is brutal at best. Here's a post on the topic:
https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/
And the post content:
I see this is a little old, but there might be a better solution here.
When you want a string, but you want the string to only match certain values, you can use enums.
For example:
enum Fruit {
Orange = "Orange",
Apple = "Apple",
Banana = "Banana"
}
let myFruit: Fruit = Fruit.Banana;
Now you'll know that no matter what, myFruit will always be the string "Banana" (Or whatever other enumerable value you choose). This is useful for many things, whether it be grouping similar values like this, or mapping user-friendly values to machine-friendly values, all while enforcing and restricting the values the compiler will allow.
you may use
ImageSourceConverter class
to get what you want
img1.Source = (ImageSource)new ImageSourceConverter().ConvertFromString("/Assets/check.png");
I made a parent div expand around content of a child div by having the child div as a single column that does not have any positioning attribute such as absolute specified.
Example:
#wrap {width:400px;padding:10px 200px 10px 200px;position:relative;margin:0px auto;}
#maincolumn {width:400px;}
Based on maincolumn div being the deepest child div of #wrap this defines the depth of the #wrap div and the 200px padding on either side creates two big blank columns for you to place absolutely positioned divs in as you please. You could even change the padding top and bottom to place header divs and footer divs using position:absolute.
Here is the simple explanation of Redux over Flux. Redux does not have a dispatcher.It relies on pure functions called reducers. It does not need a dispatcher. Each actions are handled by one or more reducers to update the single store. Since data is immutable, reducers returns a new updated state that updates the store
For more information Flux vs Redux
My guess is that it indicates "Unicode", is it correct?
Yes.
If so, since when is it available?
Python 2.x.
In Python 3.x the strings use Unicode by default and there's no need for the u
prefix. Note: in Python 3.0-3.2, the u is a syntax error. In Python 3.3+ it's legal again to make it easier to write 2/3 compatible apps.
Actually, I think the problem is that your variable "lines" is bad. You defined lines as a tuple, but I believe that write() requires a string. All you have to change is your commas into pluses (+).
nl = "\n"
lines = line1+nl+line2+nl+line3+nl
textdoc.writelines(lines)
should work.
It forces the browser to use hardware acceleration to access the device’s graphical processing unit (GPU) to make pixels fly. Web applications, on the other hand, run in the context of the browser, which lets the software do most (if not all) of the rendering, resulting in less horsepower for transitions. But the Web has been catching up, and most browser vendors now provide graphical hardware acceleration by means of particular CSS rules.
Using -webkit-transform: translate3d(0,0,0);
will kick the GPU into action for the CSS transitions, making them smoother (higher FPS).
Note: translate3d(0,0,0)
does nothing in terms of what you see. It moves the object by 0px in x,y and z axis. It's only a technique to force the hardware acceleration.
Good read here: http://www.smashingmagazine.com/2012/06/21/play-with-hardware-accelerated-css/
The native PHP function mail()
does not work for me. It issues the message:
503 This mail server requires authentication when attempting to send to a non-local e-mail address
So, I usually use PHPMailer
package
I've downloaded the version 5.2.23 from: GitHub.
I've just picked 2 files and put them in my source PHP root
class.phpmailer.php
class.smtp.php
In PHP, the file needs to be added
require_once('class.smtp.php');
require_once('class.phpmailer.php');
After this, it's just code:
require_once('class.smtp.php');
require_once('class.phpmailer.php');
...
//----------------------------------------------
// Send an e-mail. Returns true if successful
//
// $to - destination
// $nameto - destination name
// $subject - e-mail subject
// $message - HTML e-mail body
// altmess - text alternative for HTML.
//----------------------------------------------
function sendmail($to,$nameto,$subject,$message,$altmess) {
$from = "[email protected]";
$namefrom = "yourname";
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->isSMTP(); // by SMTP
$mail->SMTPAuth = true; // user and password
$mail->Host = "localhost";
$mail->Port = 25;
$mail->Username = $from;
$mail->Password = "yourpassword";
$mail->SMTPSecure = ""; // options: 'ssl', 'tls' , ''
$mail->setFrom($from,$namefrom); // From (origin)
$mail->addCC($from,$namefrom); // There is also addBCC
$mail->Subject = $subject;
$mail->AltBody = $altmess;
$mail->Body = $message;
$mail->isHTML(); // Set HTML type
//$mail->addAttachment("attachment");
$mail->addAddress($to, $nameto);
return $mail->send();
}
It works like a charm
If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149
To summarize, open up a Terminal window and type the following command:
defaults write NSGlobalDomain KeyRepeat -int 0
More detail from the article:
Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:
defaults write NSGlobalDomain KeyRepeat -int 0
Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.
You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.
function sendAjaxRequest(element,urlToSend) {
var clickedButton = element;
$.ajax({type: "POST",
url: urlToSend,
data: { id: clickedButton.val(), access_token: $("#access_token").val() },
success:function(result){
alert('ok');
},
error:function(result)
{
alert('error');
}
});
}
$(document).ready(function(){
$("#button_1").click(function(e){
e.preventDefault();
sendAjaxRequest($(this),'/pages/test/');
});
$("#button_2").click(function(e){
e.preventDefault();
sendAjaxRequest($(this),'/pages/test/');
});
});
If it's just a vector of integers, I'd first try:
memset(&my_vector[0], 0, my_vector.size() * sizeof my_vector[0]);
It's not very C++, so I'm sure someone will provide the proper way of doing this. :)
This is what I use. I do this first query to find the sessions and the users:
select s.sid, s.serial#, p.spid, s.username, s.schemaname
, s.program, s.terminal, s.osuser
from v$session s
join v$process p
on s.paddr = p.addr
where s.type != 'BACKGROUND';
This will let me know if there are multiple sessions for the same user. Then I usually check to verify if a session is blocking the database.
SELECT SID, SQL_ID, USERNAME, BLOCKING_SESSION, COMMAND, MODULE, STATUS FROM v$session WHERE BLOCKING_SESSION IS NOT NULL;
Then I run an ALTER statement to kill a specific session in this format:
ALTER SYSTEM KILL SESSION 'sid,serial#';
For example:
ALTER SYSTEM KILL SESSION '314, 2643';
Cross join and inner join are the same with the only difference that in inner join we booleanly filter some of the outcomes of the cartesian product
table1
x--------------------------------------x
| fieldA | fieldB | fieldC |
x----------|-------------|-------------x
| A | B | option1 |
| A | B1 | option2 |
x--------------------------------------x
table2
x--------------------------------------x
| fieldA | fieldB | fieldC |
x----------|-------------|-------------x
| A | B | optionB1 |
| A1 | B1 | optionB2 |
x--------------------------------------x
cross join
A,B,option1,A,B,optionB1
A,B,option1,A1,B1,optionB2
A,B1,option2,A,B,optionB1
A,B1,option2,A1,B1,optionB2
inner join on field1 (only with the value is the same in both tables)
A,B,option1,A,B,optionB1
A,B1,option2,A,B,optionB1
inner join on field1
A,B,option1,A,B,optionB1
It is on design of our data where we decide that there is only one case of the field we are using for the join. Join only cross join both tables and get only the lines accomplishing special boolean expression.
Note that if the fields we are doing our Joins on would be null in both tables we would pass the filter. It is up to us or the database manufacturer to add extra rules to avoid or permit nulls. Adhering to the basics it is just a cross join followed by a filter.
mvn install:install-file -DgroupId=com.paic.maven -DartifactId=tplconfig-maven-plugin -Dversion=1.0 -Dpackaging=jar -Dfile=tplconfig-maven-plugin-1.0.jar -DgeneratePom=true
Install the jar to local repository.
This answer is not accurate because it mix description of UTM and UTM itself (Universal Turing Machine).
We have good answer but from different perspective and it do not show directly flaws in current top answer.
First of all we can agree that human can work as UTM. This mean if we do
CSS + Human == UTM
Then CSS
part is useless because all work can be done by Human
who will do UTM part. Act of clicking can be UTM, because you do not click at random but only in specific places.
Instead of CSS I could use this text (Rule 110):
000 -> 0
001 -> 1
010 -> 1
011 -> 1
100 -> 0
101 -> 1
110 -> 1
111 -> 0
To guide my actions and result will be same. This mean this text UTM? No this is only input (description) that other UTM (human or computer) can read and run. Clicking is enough to run any UTM.
Critical part that CSS lack is ability to change of it own state in arbitrary way, if CSS could generate clicks then it would be UTM. Argument that your clicks are "crank" for CSS is not accurate because real "crank" for CSS is Layout Engine that run it and it should be enough to prove that CSS is UTM.
I used Ctrl+Shift+F. Next, put a \n
in the search box and enable regular expressions box. Then in the find results, in the end of the screen are the number of files searched and lines of code found.
You can use [^\n\s]\r\n
to skip blank and space-only lines (credits to Zach in the comments).
A couple of tips:
My problem was a combination of previously stated: I have set the compiler version to 15 instead of 14 and when corrected, I had to delete the cache.
I also started the Visual Studio command prompt as an administrator and from there I ran the cmake-gui.exe
Then everything worked as it was supposed to.
You can call helper class in any controller
//view
@Html.ActionLink("Export to Excel", "Excel")
//controller Action
public void Excel()
{
var model = db.GetModel()
Export export = new Export();
export.ToExcel(Response, model);
}
//helper class
public class Export
{ public void ToExcel(HttpResponseBase Response, object clientsList)
{
var grid = new System.Web.UI.WebControls.GridView();
grid.DataSource = clientsList;
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
}
It is quite easy. Here is the API Interface
public interface Api {
@Multipart
@POST("upload")
Call<MyResponse> uploadImage(@Part("image\"; filename=\"myfile.jpg\" ") RequestBody file, @Part("desc") RequestBody desc);
}
And you can use the following code to make a call.
private void uploadFile(File file, String desc) {
//creating request body for file
RequestBody requestFile = RequestBody.create(MediaType.parse(getContentResolver().getType(fileUri)), file);
RequestBody descBody = RequestBody.create(MediaType.parse("text/plain"), desc);
//The gson builder
Gson gson = new GsonBuilder()
.setLenient()
.create();
//creating retrofit object
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
//creating our api
Api api = retrofit.create(Api.class);
//creating a call and calling the upload image method
Call<MyResponse> call = api.uploadImage(requestFile, descBody);
//finally performing the call
call.enqueue(new Callback<MyResponse>() {
@Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
if (!response.body().error) {
Toast.makeText(getApplicationContext(), "File Uploaded Successfully...", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Some error occurred...", Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<MyResponse> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
Source: Retrofit Upload File Tutorial.
If you are trying to "Submit and Reset" the the "form" with one Button click, Try this!
Here I have used jQuery function, it can be done by simple JavaScript also...
<form id="form_data">
<input type="anything" name="anything" />
<input type="anything" name="anything" />
<!-- Save and Reset button -->
<button type="button" id="btn_submit">Save</button>
<button type="reset" id="btn_reset" style="display: none;"></button>
</form>
<script type="text/javascript">
$(function(){
$('#btn_submit').click(function(){
// Do what ever you want
$('#btn_reset').click(); // Clicking reset button
});
});
</script>
As others have said, %% will escape the %.
Note, however, that you should never do this:
char c[100];
char *c2;
...
printf(c); /* OR */
printf(c2);
Whenever you have to print a string, always, always, always print it using
printf("%s", c)
to prevent an embedded % from causing problems [memory violations, segfault, etc]
It's a Python version problem. If you are using the latest, then your old syntax won't work and give you this error. Please follow @Josav09's code and you will be fine.
So you are asking for ArgMin
or ArgMax
. C# doesn't have a built-in API for those.
I've been looking for a clean and efficient (O(n) in time) way to do this. And I think I found one:
The general form of this pattern is:
var min = data.Select(x => (key(x), x)).Min().Item2;
^ ^ ^
the sorting key | take the associated original item
Min by key(.)
Specially, using the example in original question:
For C# 7.0 and above that supports value tuple:
var youngest = people.Select(p => (p.DateOfBirth, p)).Min().Item2;
For C# version before 7.0, anonymous type can be used instead:
var youngest = people.Select(p => new {age = p.DateOfBirth, ppl = p}).Min().ppl;
They work because both value tuple and anonymous type have sensible default comparers: for (x1, y1) and (x2, y2), it first compares x1
vs x2
, then y1
vs y2
. That's why the built-in .Min
can be used on those types.
And since both anonymous type and value tuple are value types, they should be both very efficient.
NOTE
In my above ArgMin
implementations I assumed DateOfBirth
to take type DateTime
for simplicity and clarity. The original question asks to exclude those entries with null DateOfBirth
field:
Null DateOfBirth values are set to DateTime.MaxValue in order to rule them out of the Min consideration (assuming at least one has a specified DOB).
It can be achieved with a pre-filtering
people.Where(p => p.DateOfBirth.HasValue)
So it's immaterial to the question of implementing ArgMin
or ArgMax
.
NOTE 2
The above approach has a caveat that when there are two instances that have the same min value, then the Min()
implementation will try to compare the instances as a tie-breaker. However, if the class of the instances does not implement IComparable
, then a runtime error will be thrown:
At least one object must implement IComparable
Luckily, this can still be fixed rather cleanly. The idea is to associate a distanct "ID" with each entry that serves as the unambiguous tie-breaker. We can use an incremental ID for each entry. Still using the people age as example:
var youngest = Enumerable.Range(0, int.MaxValue)
.Zip(people, (idx, ppl) => (ppl.DateOfBirth, idx, ppl)).Min().Item3;
The better way I found here:
action="javascript: void(0)"
or action="return false;"
(doesn't work on me)
One way to solve this error is to put the ForeignKey
attribute on top of the property you want as a foreign key and add the navigation property.
Note: In the ForeignKey
attribute, between parentheses and double quotes, place the name of the class referred to in this way.
AES.
(I also am assuming you mean twofish not the much older and weaker blowfish)
Both (AES & twofish) are good algorithms. However even if they were equal or twofish was slightly ahead on technical merit I would STILL chose AES.
Why? Publicity. AES is THE standard for government encryption and thus millions of other entities also use it. A talented cryptanalyst simply gets more "bang for the buck" finding a flaw in AES then it does for the much less know and used twofish.
Obscurity provides no protection in encryption. More bodies looking, studying, probing, attacking an algorithm is always better. You want the most "vetted" algorithm possible and right now that is AES. If an algorithm isn't subject to intense and continual scrutiny you should place a lower confidence of it's strength. Sure twofish hasn't been compromised. Is that because of the strength of the cipher or simply because not enough people have taken a close look ..... YET
Click somewhere on the chart to select it.
You should now see 3 new tabs appear at the top of the screen called "Design", "Layout" and "Format".
Click on the "Design" tab.
There will be a button called "Switch Row/Column" within the "data" group, click it.
There is way to do that ;)
Thanks to "http://it.toolbox.com/wiki/index.php/Use_curl_from_PHP_-_processing_response_headers":
<?php
/**
* Facebook user photo downloader
*/
class sfFacebookPhoto {
private $useragent = 'Loximi sfFacebookPhoto PHP5 (cURL)';
private $curl = null;
private $response_meta_info = array();
private $header = array(
"Accept-Encoding: gzip,deflate",
"Accept-Charset: utf-8;q=0.7,*;q=0.7",
"Connection: close"
);
public function __construct() {
$this->curl = curl_init();
register_shutdown_function(array($this, 'shutdown'));
}
/**
* Get the real URL for the picture to use after
*/
public function getRealUrl($photoLink) {
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->header);
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, false);
curl_setopt($this->curl, CURLOPT_HEADER, false);
curl_setopt($this->curl, CURLOPT_USERAGENT, $this->useragent);
curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($this->curl, CURLOPT_TIMEOUT, 15);
curl_setopt($this->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($this->curl, CURLOPT_URL, $photoLink);
//This assumes your code is into a class method, and
//uses $this->readHeader as the callback function.
curl_setopt($this->curl, CURLOPT_HEADERFUNCTION, array(&$this, 'readHeader'));
$response = curl_exec($this->curl);
if (!curl_errno($this->curl)) {
$info = curl_getinfo($this->curl);
var_dump($info);
if ($info["http_code"] == 302) {
$headers = $this->getHeaders();
if (isset($headers['fileUrl'])) {
return $headers['fileUrl'];
}
}
}
return false;
}
/**
* Download Facebook user photo
*
*/
public function download($fileName) {
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->header);
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->curl, CURLOPT_HEADER, false);
curl_setopt($this->curl, CURLOPT_USERAGENT, $this->useragent);
curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($this->curl, CURLOPT_TIMEOUT, 15);
curl_setopt($this->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($this->curl, CURLOPT_URL, $fileName);
$response = curl_exec($this->curl);
$return = false;
if (!curl_errno($this->curl)) {
$parts = explode('.', $fileName);
$ext = array_pop($parts);
$return = sfConfig::get('sf_upload_dir') . '/tmp/' . uniqid('fbphoto') . '.' . $ext;
file_put_contents($return, $response);
}
return $return;
}
/**
* cURL callback function for reading and processing headers.
* Override this for your needs.
*
* @param object $ch
* @param string $header
* @return integer
*/
private function readHeader($ch, $header) {
//Extracting example data: filename from header field Content-Disposition
$filename = $this->extractCustomHeader('Location: ', '\n', $header);
if ($filename) {
$this->response_meta_info['fileUrl'] = trim($filename);
}
return strlen($header);
}
private function extractCustomHeader($start, $end, $header) {
$pattern = '/'. $start .'(.*?)'. $end .'/';
if (preg_match($pattern, $header, $result)) {
return $result[1];
}
else {
return false;
}
}
public function getHeaders() {
return $this->response_meta_info;
}
/**
* Cleanup resources
*/
public function shutdown() {
if($this->curl) {
curl_close($this->curl);
}
}
}
I think you're looking for the stat
function (perldoc -f stat
)
In particular, the 9th field (10th, index #9) of the returned list is the last modify time of the file in seconds since the epoch.
So:
my $last_modified = (stat($fh))[9];
my solution, hope help
custom ObjectMapper and config to spring xml(register message conveters)
public class PyResponseConfigObjectMapper extends ObjectMapper {
public PyResponseConfigObjectMapper() {
disable(SerializationFeature.WRITE_NULL_MAP_VALUES); //map no_null
setSerializationInclusion(JsonInclude.Include.NON_NULL); // bean no_null
}
}
A bit of powershell magic will do the trick:
cmdkey /add:"SERVER:1433" /user:"DOMAIN\USERNAME" /pass:"PASSWORD"
Then just select windows authentication
You don't have to use jQuery or Javascript.
Use the name
tag of the select and let the form do it's job.
<select name="agent_id" id="agent_id">
var query = list.Where(r => listofIds.Any(id => id == r.Id));
Another approach, useful if the listOfIds array is large:
HashSet<int> hash = new HashSet<int>(listofIds);
var query = list.Where(r => hash.Contains(r.Id));
Try this:
list.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3)
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
There is no build-in variable for this purpose, but you can always find out the playbook's absolute path with "pwd" command, and register its output to a variable.
- name: Find out playbook's path
shell: pwd
register: playbook_path_output
- debug: var=playbook_path_output.stdout
Now the path is available in variable playbook_path_output.stdout
As mentioned above you can wait for active connections to get closed:
private static void WaitForReady() {
WebDriverWait wait = new WebDriverWait(webDriver, waitForElement);
wait.Until(driver => (bool)((IJavaScriptExecutor)driver).ExecuteScript("return jQuery.active == 0"));
}
My observation is this is not reliable as data transfer happens very quickly. Much more time is consumed on data processing and rendering on the page and even jQuery.active == 0
data might not be yet on the page.
Much wiser is to use an explicit wait for element to be shown on the page, see some of the answers related to this.
The best situation is if your web application have some custom loader or indication that data is being processed. In this case you can just wait for this indication to hide.
Create a script with name your-app.service (rest-app.service). We should place this script in /etc/systemd/system directory. Here is the sample content of the script
[Unit]
Description=Spring Boot REST Application
After=syslog.target
[Service]
User=javadevjournal
ExecStart=/var/rest-app/restdemo.jar
SuccessExitStatus=200
[Install]
WantedBy=multi-user.target
Next:
service rest-app start
References
Using OVER()
and LIMIT 1
:
SELECT COUNT(1) OVER()
FROM posts
INNER JOIN votes ON votes.post_id = posts.id
GROUP BY posts.id
LIMIT 1;
Alternatively, you can use pseudo-elements to do so :) the advantage of the pseudo-element solution is that you can use it to space the inner border at an arbitrary distance away from the actual border, and the background will show through that space. The markup:
body {_x000D_
background-image: linear-gradient(180deg, #ccc 50%, #fff 50%);_x000D_
background-repeat: no-repeat;_x000D_
height: 100vh;_x000D_
}_x000D_
.double-border {_x000D_
background-color: #ccc;_x000D_
border: 4px solid #fff;_x000D_
padding: 2em;_x000D_
width: 16em;_x000D_
height: 16em;_x000D_
position: relative;_x000D_
margin: 0 auto;_x000D_
}_x000D_
.double-border:before {_x000D_
background: none;_x000D_
border: 4px solid #fff;_x000D_
content: "";_x000D_
display: block;_x000D_
position: absolute;_x000D_
top: 4px;_x000D_
left: 4px;_x000D_
right: 4px;_x000D_
bottom: 4px;_x000D_
pointer-events: none;_x000D_
}
_x000D_
<div class="double-border">_x000D_
<!-- Content -->_x000D_
</div>
_x000D_
If you want borders that are consecutive to each other (no space between them), you can use multiple box-shadow
declarations (separated by commas) to do so:
body {_x000D_
background-image: linear-gradient(180deg, #ccc 50%, #fff 50%);_x000D_
background-repeat: no-repeat;_x000D_
height: 100vh;_x000D_
}_x000D_
.double-border {_x000D_
background-color: #ccc;_x000D_
border: 4px solid #fff;_x000D_
box-shadow:_x000D_
inset 0 0 0 4px #eee,_x000D_
inset 0 0 0 8px #ddd,_x000D_
inset 0 0 0 12px #ccc,_x000D_
inset 0 0 0 16px #bbb,_x000D_
inset 0 0 0 20px #aaa,_x000D_
inset 0 0 0 20px #999,_x000D_
inset 0 0 0 20px #888;_x000D_
/* And so on and so forth, if you want border-ception */_x000D_
margin: 0 auto;_x000D_
padding: 3em;_x000D_
width: 16em;_x000D_
height: 16em;_x000D_
position: relative;_x000D_
}
_x000D_
<div class="double-border">_x000D_
<!-- Content -->_x000D_
</div>
_x000D_
Here's @Daniel Vérité's function with progress reporting functionality. It reports progress in three ways:
_
CREATE OR REPLACE FUNCTION search_columns(
needle text,
haystack_tables name[] default '{}',
haystack_schema name[] default '{public}',
progress_seq text default NULL
)
RETURNS table(schemaname text, tablename text, columnname text, rowctid text)
AS $$
DECLARE
currenttable text;
columnscount integer;
foundintables text[];
foundincolumns text[];
begin
currenttable='';
columnscount = (SELECT count(1)
FROM information_schema.columns c
JOIN information_schema.tables t ON
(t.table_name=c.table_name AND t.table_schema=c.table_schema)
WHERE (c.table_name=ANY(haystack_tables) OR haystack_tables='{}')
AND c.table_schema=ANY(haystack_schema)
AND t.table_type='BASE TABLE')::integer;
PERFORM setval(progress_seq::regclass, columnscount);
FOR schemaname,tablename,columnname IN
SELECT c.table_schema,c.table_name,c.column_name
FROM information_schema.columns c
JOIN information_schema.tables t ON
(t.table_name=c.table_name AND t.table_schema=c.table_schema)
WHERE (c.table_name=ANY(haystack_tables) OR haystack_tables='{}')
AND c.table_schema=ANY(haystack_schema)
AND t.table_type='BASE TABLE'
LOOP
EXECUTE format('SELECT ctid FROM %I.%I WHERE cast(%I as text)=%L',
schemaname,
tablename,
columnname,
needle
) INTO rowctid;
IF rowctid is not null THEN
RETURN NEXT;
foundintables = foundintables || tablename;
foundincolumns = foundincolumns || columnname;
RAISE NOTICE 'FOUND! %, %, %, %', schemaname,tablename,columnname, rowctid;
END IF;
IF (progress_seq IS NOT NULL) THEN
PERFORM nextval(progress_seq::regclass);
END IF;
IF(currenttable<>tablename) THEN
currenttable=tablename;
IF (progress_seq IS NOT NULL) THEN
RAISE NOTICE 'Columns left to look in: %; looking in table: %', currval(progress_seq::regclass), tablename;
EXECUTE 'COPY (SELECT unnest(string_to_array(''Current table (column ' || columnscount-currval(progress_seq::regclass) || ' of ' || columnscount || '): ' || tablename || '\n\nFound in tables/columns:\n' || COALESCE(
(SELECT string_agg(c1 || '/' || c2, '\n') FROM (SELECT unnest(foundintables) AS c1,unnest(foundincolumns) AS c2) AS t1)
, '') || ''',''\n''))) TO ''c:\WINDOWS\temp\' || progress_seq || '.txt''';
END IF;
END IF;
END LOOP;
END;
$$ language plpgsql;
If you are using jQuery you can also do this:
$('#leaveCode').val('14');
This will select the <option>
with the value of 14.
With plain Javascript, this can also be achieved with two Document
methods:
With document.querySelector
, you can select an element based on a CSS selector:
document.querySelector('#leaveCode').value = '14'
Using the more established approach with document.getElementById()
, that will, as the name of the function implies, let you select an element based on its id
:
document.getElementById('leaveCode').value = '14'
You can run the below code snipped to see these methods and the jQuery function in action:
const jQueryFunction = () => {_x000D_
_x000D_
$('#leaveCode').val('14'); _x000D_
_x000D_
}_x000D_
_x000D_
const querySelectorFunction = () => {_x000D_
_x000D_
document.querySelector('#leaveCode').value = '14' _x000D_
_x000D_
}_x000D_
_x000D_
const getElementByIdFunction = () => {_x000D_
_x000D_
document.getElementById('leaveCode').value='14' _x000D_
_x000D_
}
_x000D_
input {_x000D_
display:block;_x000D_
margin: 10px;_x000D_
padding: 10px_x000D_
}
_x000D_
<select id="leaveCode" name="leaveCode">_x000D_
<option value="10">Annual Leave</option>_x000D_
<option value="11">Medical Leave</option>_x000D_
<option value="14">Long Service</option>_x000D_
<option value="17">Leave Without Pay</option>_x000D_
</select>_x000D_
_x000D_
<input type="button" value="$('#leaveCode').val('14');" onclick="jQueryFunction()" />_x000D_
<input type="button" value="document.querySelector('#leaveCode').value = '14'" onclick="querySelectorFunction()" />_x000D_
<input type="button" value="document.getElementById('leaveCode').value = '14'" onclick="getElementByIdFunction()" />_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
You can build random ascii characters like:
import random
print chr(random.randint(0,255))
And then build up a longer string like:
len = 50
print ''.join( [chr(random.randint(0,255)) for i in xrange(0,len)] )
This worked for me:
find ./ -type f -exec sed -i '' 's#NEEDLE#REPLACEMENT#' *.php {} \;
Alternatively, you could try the following,
resp.setStatus(301);
resp.setHeader("Location", "index.jsp");
resp.setHeader("Connection", "close");
I found this for online php validation:-
http://www.icosaedro.it/phplint/phplint-on-line.html
Hope this helps.
Your code snippet,
if number >= 10000 and number >= 30000:
print ("you have to pay 5% taxes")
actually checks if number is larger than both 10000 and 30000.
Assuming you want to check that the number is in the range 10000 - 30000, you could use the Python interval comparison:
if 10000 <= number <= 30000:
print ("you have to pay 5% taxes")
This Python feature is further described in the Python documentation.
You are getting this error because you are calling $apply
inside an existing digestion cycle.
The big question is: why are you calling $apply
? You shouldn't ever need to call $apply
unless you are interfacing from a non-Angular event. The existence of $apply
usually means I am doing something wrong (unless, again, the $apply happens from a non-Angular event).
If $apply
really is appropriate here, consider using a "safe apply" approach:
cat ~/.ssh/id_rsa.pub
ssh login from Git bash on your computer
ssh -i ~/.ssh/id_rsa [email protected]
You can download the streaming subtitles from YouTube with KeepSubs DownSub and SaveSubs.
You can choose from the Automatic Transcript or author supplied close captions. It also offers the possibility to automatically translate the English subtitles into other languages using Google Translate.
Another common solution is adding "Other.." option to the drop down and when selected show text box that is otherwise hidden. Then when submitting the form, assign hidden field value with either the drop down or textbox value and in the server side code check the hidden value.
Example: http://jsfiddle.net/c258Q/
HTML code:
Please select: <form onsubmit="FormSubmit(this);">
<input type="hidden" name="fruit" />
<select name="fruit_ddl" onchange="DropDownChanged(this);">
<option value="apple">Apple</option>
<option value="orange">Apricot </option>
<option value="melon">Peach</option>
<option value="">Other..</option>
</select> <input type="text" name="fruit_txt" style="display: none;" />
<button type="submit">Submit</button>
</form>
JavaScript:
function DropDownChanged(oDDL) {
var oTextbox = oDDL.form.elements["fruit_txt"];
if (oTextbox) {
oTextbox.style.display = (oDDL.value == "") ? "" : "none";
if (oDDL.value == "")
oTextbox.focus();
}
}
function FormSubmit(oForm) {
var oHidden = oForm.elements["fruit"];
var oDDL = oForm.elements["fruit_ddl"];
var oTextbox = oForm.elements["fruit_txt"];
if (oHidden && oDDL && oTextbox)
oHidden.value = (oDDL.value == "") ? oTextbox.value : oDDL.value;
}
And in the server side, read the value of "fruit" from the Request.
Run it in parallel with
cat text_file.txt | parallel --gnu "wget {}"
The following function will work in JDK version 1.5 and above.
public String getSimpleName()
You can download a custom compiled bootstrap 3, just customize the @modal-backdrop-opacity from:
https://getbootstrap.com/docs/3.4/customize/
Customizing bootstrap 4 requires compiling from source, overriding $modal-backdrop-bg as described in:
https://getbootstrap.com/docs/4.4/getting-started/theming/
In the answers to Bootstrap 4 custom build generator / download there is a NodeJS workflow for compiling Bootstrap 4 from source, alone with some non-official Bootstrap 4 customizers.
It is because Gerrit is configured to require Change-Id in the commit messages.
http://gerrit.googlecode.com/svn-history/r6114/documentation/2.1.7/error-missing-changeid.html
You have to change the messages of every commit that you are pushing to include the change id ( using git filter-branch
) and only then push.
You can still use the textmode and force the linefeed-newline with the keyword argument newline
f = open("./foo",'w',newline='\n')
Tested with Python 3.4.2.
Edit: This does not work in Python 2.7.
Now there is a shorter way with Java 8 using Map::merge
.
myMap.merge(key, 1, Integer::sum)
What it does:
More information here.
If I understand correctly you have an iframe that contains a second iframe (the youtube one).
Try adding the allowfullscreen
attribute to the "parent" iframe.
For full browser support it should look like this:
<iframe src="your_page_url"
allowfullscreen="allowfullscreen"
mozallowfullscreen="mozallowfullscreen"
msallowfullscreen="msallowfullscreen"
oallowfullscreen="oallowfullscreen"
webkitallowfullscreen="webkitallowfullscreen"> </iframe>
The right way to update the page currently displayed in the user's browser (without reloading it) is to have some code executing in the browser update the page's DOM.
That code is typically javascript that is embedded in or linked from the HTML page, hence the AJAX suggestion. (In fact, if we assume that the updated text comes from the server via an HTTP request, this is classic AJAX.)
It is also possible to implement this kind of thing using some browser plugin or add-on, though it may be tricky for a plugin to reach into the browser's data structures to update the DOM. (Native code plugins normally write to some graphics frame that is embedded in the page.)
import java.util.ArrayList;
import java.util.List;
class ArrLst{
public static void main(String args[]){
List l=new ArrayList();
l.add(10);
l.add(11);
l.add(12);
l.add(13);
l.add(14);
l.forEach((a)->System.out.println(a));
}
}
I had an old Excel database with "human-readable" dates, like 2010.03.28 20:12:30 Theese dates were in UTC+1 (CET) and needed to convert it to epoch time.
I used the =(A4-DATE(1970;1;1))*86400-3600 formula to convert the dates to epoch time from the A column to B column values. Check your timezone offset and make a math with it. 1 hour is 3600 seconds.
The only thing why i write here an anwser, you can see that this topic is more than 5 years old is that i use the new Excel versions and also red posts in this topic, but they're incorrect. The DATE(1970;1;1). Here the 1970 and the January needs to be separated with ; and not with ,
If you're also experiencing this issue, hope it helps you. Have a nice day :)
My solution:
long unsigned int i;
for(i = 0u; i < sizeof(integer) * CHAR_BIT; i++) {
if(integer & LONG_MIN)
printf("1");
else
printf("0");
integer <<= 1;
}
printf("\n");
It's possible to change default fonts, both for the axes and for other text, by adding the following lines to the startup.m
file.
% Change default axes fonts.
set(0,'DefaultAxesFontName', 'Times New Roman')
set(0,'DefaultAxesFontSize', 14)
% Change default text fonts.
set(0,'DefaultTextFontname', 'Times New Roman')
set(0,'DefaultTextFontSize', 14)
If you don't know if you have a startup.m
file, run
which startup
to find its location. If Matlab says there isn't one, run
userpath
to know where it should be placed.
A solution with numpy for quick access to all indexes:
string_array = np.array(list(my_string))
char_indexes = np.where(string_array == 'C')
See my comment above, and I believe you have to use NSInvocation when there is more than one parameter
more information on NSInvocation here
http://cocoawithlove.com/2008/03/construct-nsinvocation-for-any-message.html
DISTINCT is the keyword you're looking for.
In MSSQL, copying unique rows from a table to another can be done like this:
SELECT DISTINCT column_name
INTO newTable
FROM srcTable
The column_name
is the column you're searching the unique values from.
Tested and works.
try {
WebElement button = driver.findElement(By.xpath("xpath"));
button.click();
}
catch(org.openqa.selenium.StaleElementReferenceException ex)
{
WebElement button = driver.findElement(By.xpath("xpath"));
button.click();
}
This try/catch code actually worked for me. I got the same stale element error.
In addition to the answer of @Charles-Duffy, you can use winpty directly without installing/downloading anything extra. Just run winpty c:/Python27/python.exe
. The utility winpty.exe can be found at Git\usr\bin. I'm using Git for Windows v2.7.1
The prebuilt binaries from @Charles-Duffy is version 0.1.1(according to the file name), while the included one is 0.2.2
It sounds like your printMousePos
function should:
Currently, it does this:
See the problem? Your variables are never getting set, because as soon as you add your function to the "mousemove" event you print them.
It seems like you probably don't need that mousemove event at all; I would try something like this:
function printMousePos(e) {
var cursorX = e.pageX;
var cursorY = e.pageY;
document.getElementById('test').innerHTML = "x: " + cursorX + ", y: " + cursorY;
}
The path is in the registry but usually you edit through this interface:
Control Panel
-> System
-> System settings
-> Environment Variables
.PATH
.c:\path;c:\path2
With postgres 9.3 use -> for object access. 4 example
seed.rb
se = SmartElement.new
se.data =
{
params:
[
{
type: 1,
code: 1,
value: 2012,
description: 'year of producction'
},
{
type: 1,
code: 2,
value: 30,
description: 'length'
}
]
}
se.save
rails c
SELECT data->'params'->0 as data FROM smart_elements;
returns
data
----------------------------------------------------------------------
{"type":1,"code":1,"value":2012,"description":"year of producction"}
(1 row)
You can continue nesting
SELECT data->'params'->0->'type' as data FROM smart_elements;
return
data
------
1
(1 row)
Including its "big result", this paper describes a couple of variants of in-place merge sort (PDF):
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.22.5514&rep=rep1&type=pdf
In-place sorting with fewer moves
Jyrki Katajainen, Tomi A. Pasanen
It is shown that an array of n elements can be sorted using O(1) extra space, O(n log n / log log n) element moves, and n log2n + O(n log log n) comparisons. This is the first in-place sorting algorithm requiring o(n log n) moves in the worst case while guaranteeing O(n log n) comparisons, but due to the constant factors involved the algorithm is predominantly of theoretical interest.
I think this is relevant too. I have a printout of it lying around, passed on to me by a colleague, but I haven't read it. It seems to cover basic theory, but I'm not familiar enough with the topic to judge how comprehensively:
http://comjnl.oxfordjournals.org/cgi/content/abstract/38/8/681
Optimal Stable Merging
Antonios Symvonis
This paper shows how to stably merge two sequences A and B of sizes m and n, m = n, respectively, with O(m+n) assignments, O(mlog(n/m+1)) comparisons and using only a constant amount of additional space. This result matches all known lower bounds...
You have to add this to your pg_hba.conf and restart your PostgreSQL.
host all all 192.168.56.1/24 md5
This works with VirtualBox and host-only adapter enabled. If you don't use Virtualbox you have to replace the IP address.
In case you still need it, have you tried to set the property
self.tableView.tableHeaderView
If you calculate the heigh you need, and set a new view for tableHeaderView
:
CGRect frame = self.tableView.tableHeaderView.frame;
frame.size.height = newHeight;
self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:frame];
It should work.
var ids = [];
$(document).ready(function($) {
$(".color_cell").bind('click', function() {
alert('Test');
ids.push(this.id);
});
});
The easiest way would be to use a GUI:
For Gnome use gnome-schedule (universe)
sudo apt-get install gnome-schedule
For KDE use kde-config-cron
It should be pre installed on Kubuntu
But if you use a headless linux or don´t want GUI´s you may use:
crontab -e
If you type it into Terminal you´ll get a table.
You have to insert your cronjobs now.
Format a job like this:
* * * * * YOURCOMMAND
- - - - -
| | | | |
| | | | +----- Day in Week (0 to 7) (Sunday is 0 and 7)
| | | +------- Month (1 to 12)
| | +--------- Day in Month (1 to 31)
| +----------- Hour (0 to 23)
+------------- Minute (0 to 59)
There are some shorts, too (if you don´t want the *):
@reboot --> only once at startup
@daily ---> once a day
@midnight --> once a day at midnight
@hourly --> once a hour
@weekly --> once a week
@monthly --> once a month
@annually --> once a year
@yearly --> once a year
If you want to use the shorts as cron (because they don´t work or so):
@daily --> 0 0 * * *
@midnight --> 0 0 * * *
@hourly --> 0 * * * *
@weekly --> 0 0 * * 0
@monthly --> 0 0 1 * *
@annually --> 0 0 1 1 *
@yearly --> 0 0 1 1 *
The programming language of iOS(and Mac OS) is Objective-C and C. You have to use Xcode platform to develop iOS apps, on the next version that is now available on beta release, Xcode 4 supports also C++.
You can create a dict and pass this as the data param to the dataframe constructor:
In [235]:
df = pd.DataFrame({'Gene':s.index, 'count':s.values})
df
Out[235]:
Gene count
0 Ezh2 2
1 Hmgb 7
2 Irf1 1
Alternatively you can create a df from the series, you need to call reset_index
as the index will be used and then rename the columns:
In [237]:
df = pd.DataFrame(s).reset_index()
df.columns = ['Gene', 'count']
df
Out[237]:
Gene count
0 Ezh2 2
1 Hmgb 7
2 Irf1 1
f you need to preserve the old array, slice the old one and unshift the new value(s) to the beginning of the slice.
var oldA=[4,5,6];
newA=oldA.slice(0);
newA.unshift(1,2,3)
oldA+'\n'+newA
/* returned value:
4,5,6
1,2,3,4,5,6
*/
private void Add_Click(object sender, EventArgs e) {
OleDbConnection con = new OleDbConnection(@ "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\HP\Desktop\DS Project.mdb");
OleDbCommand cmd = con.CreateCommand();
con.Open();
cmd.CommandText = "Insert into DSPro (Playlist) values('" + textBox1.Text + "')";
cmd.ExecuteNonQuery();
MessageBox.Show("Record Submitted", "Congrats");
con.Close();
}
Personally, I use something close from fubo's solution and it works well:
image.ScaleToFit(document.PageSize);
image.SetAbsolutePosition(0,0);
To increase size of your figure N times you need to insert this just before your pl.show():
N = 2
params = pl.gcf()
plSize = params.get_size_inches()
params.set_size_inches( (plSize[0]*N, plSize[1]*N) )
It also works well with ipython notebook.
You can use LINQ to achieve that too:
var exists = array.ElementAtOrDefault(index) != null;
Alongside nmaier's answer, as he said you'll always receive code 1006. However, if you were to somehow theoretically receive other codes, here is code to display the results (via RFC6455).
var websocket;
if ("WebSocket" in window)
{
websocket = new WebSocket("ws://yourDomainNameHere.org/");
websocket.onopen = function (event) {
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was opened");
};
websocket.onclose = function (event) {
var reason;
alert(event.code);
// See http://tools.ietf.org/html/rfc6455#section-7.4.1
if (event.code == 1000)
reason = "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
else if(event.code == 1001)
reason = "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page.";
else if(event.code == 1002)
reason = "An endpoint is terminating the connection due to a protocol error";
else if(event.code == 1003)
reason = "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).";
else if(event.code == 1004)
reason = "Reserved. The specific meaning might be defined in the future.";
else if(event.code == 1005)
reason = "No status code was actually present.";
else if(event.code == 1006)
reason = "The connection was closed abnormally, e.g., without sending or receiving a Close control frame";
else if(event.code == 1007)
reason = "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).";
else if(event.code == 1008)
reason = "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.";
else if(event.code == 1009)
reason = "An endpoint is terminating the connection because it has received a message that is too big for it to process.";
else if(event.code == 1010) // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.
reason = "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason;
else if(event.code == 1011)
reason = "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.";
else if(event.code == 1015)
reason = "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).";
else
reason = "Unknown reason";
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was closed for reason: " + reason);
};
websocket.onmessage = function (event) {
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "New message arrived: " + event.data);
};
websocket.onerror = function (event) {
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "There was an error with your websocket.");
};
}
else
{
alert("Websocket is not supported by your browser");
return;
}
websocket.send("Yo wazzup");
websocket.close();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
String text = date.toString(formatter);
LocalDate date = LocalDate.parse(text, formatter);
I believe this might help, you may need to use some sort of localdate variation instead of instant
$(document).ready(function() {_x000D_
$('#openFile').on('change', function(evt) {_x000D_
console.log(this.files[0].size);_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form action="upload.php" enctype="multipart/form-data" method="POST" id="uploadform">_x000D_
<input id="openFile" name="img" type="file" />_x000D_
</form>
_x000D_
I had the same problem recently. In my case my windows 7 machine automatically downloaded java and added C:\ProgramData\Oracle\Java\javapath
to the beginning of my path environment variable, which messed up my java. Once I got rid of that from the path, it worked.
$sumArray = array();
foreach ($myArray as $k=>$subArray) {
foreach ($subArray as $id=>$value) {
if(!isset($sumArray[$id])){
$sumArray[$id] =$value;
}else {
$sumArray[$id]+=$value;
}
}
}
print_r($sumArray);
`
Even if you don't control the server, you can still see the error messages by adding the following line to the Web.config file in your project (bewlow <system.web>
):
<customErrors mode="off" />
borrowed this shamely from here
Process process = new ProcessBuilder("C:\\PathToExe\\MyExe.exe","param1","param2").start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:", Arrays.toString(args));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
More information here
For those trying to use Anvaka's solution above, I was having issues with the binding only working the first time, as lostfocus would not update the property to false. You can manually set the property to false and then true every time, but a better solution could be to do something like this in your property:
bool _isFocused = false;
public bool IsFocused
{
get { return _isFocused ; }
set
{
_isFocused = false;
_isFocused = value;
base.OnPropertyChanged("IsFocused ");
}
}
This way you only ever need to set it to true, and it will get focus.
Apache Http Client APIs are very commonly used for calling HTTP Rest services.
Here is one of example of consuming HTTP GET call.
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;
public class CallHTTPGetService {
public static void main(String[] args) throws ClientProtocolException, IOException {
HttpClient client = HttpClientBuilder.create().build();
HttpUriRequest httpUriRequest = new HttpGet("URL");
HttpResponse response = client.execute(httpUriRequest);
System.out.println(response);
}
}
Use following maven dependency if using Maven project.
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.1</version>
</dependency>
One important thing to check that no one has mentioned so far: Check your local firewall, make sure it's turned OFF.
See my response here: https://stackoverflow.com/a/41400708/1459275
You'll need to create a new array if you want to add an index.
Try this:
public static void main(String[] args) {
int[] series = new int[0];
int x = 5;
series = addInt(series, x);
//print out the array with commas as delimiters
System.out.print("New series: ");
for (int i = 0; i < series.length; i++){
if (i == series.length - 1){
System.out.println(series[i]);
}
else{
System.out.print(series[i] + ", ");
}
}
}
// here, create a method
public static int[] addInt(int [] series, int newInt){
//create a new array with extra index
int[] newSeries = new int[series.length + 1];
//copy the integers from series to newSeries
for (int i = 0; i < series.length; i++){
newSeries[i] = series[i];
}
//add the new integer to the last index
newSeries[newSeries.length - 1] = newInt;
return newSeries;
}
Please check that your key exists in the array or not, instead of simply trying to access it.
Replace:
$myVar = $someArray['someKey']
With something like:
if (isset($someArray['someKey'])) {
$myVar = $someArray['someKey']
}
or something like:
if(is_array($someArray['someKey'])) {
$theme_img = 'recent_works_iso_thumbnail';
}else {
$theme_img = 'recent_works_iso_thumbnail';
}
If you want to run several commands in the cmd shell then you can construct a single command like this:
rt.exec("cmd /c start cmd.exe /K \"cd c:/ && dir\"");
This page explains more.
Though this is an old post, I am posting how I resolved in case it helps others. Since I used sudo to do the install of the boto3 library the permissions on the boto3 directory was set to 700. Either change the permissions to be readable by others or run the python command as sudo.
It's very simple steps to push your node js application from local to GitHub.
Steps:
git clone repo-url
git add -A
git commit -a -m "First Commit"
git push origin master
Regex.Replace(strInput, strToken.Replace("$", "[$]"), strReplaceWith, RegexOptions.IgnoreCase);
I have done it something like below for sending my model class from the Second Activity to First Activity. I used LiveData to achieve this, with the help of answers from Rupesh and TheCodeFather.
Second Activity
public static MutableLiveData<AudioListModel> getLiveSong() {
MutableLiveData<AudioListModel> result = new MutableLiveData<>();
result.setValue(liveSong);
return result;
}
"liveSong" is AudioListModel declared globally
Call this method in the First Activity
PlayerActivity.getLiveSong().observe(this, new Observer<AudioListModel>() {
@Override
public void onChanged(AudioListModel audioListModel) {
if (PlayerActivity.mediaPlayer != null && PlayerActivity.mediaPlayer.isPlaying()) {
Log.d("LiveSong--->Changes-->", audioListModel.getSongName());
}
}
});
May this help for new explorers like me.
In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size
like this:
#include <vector>
int main () {
std::vector<int> v;
auto size = v.size();
}
Your third call
int size = v.size();
triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.
int size = static_cast<int>(v.size());
would always compile cleanly and also explicitly states that your conversion from std::vector::size_type
to int
was intended.
Note that if the size of the vector
is greater than the biggest number an int
can represent, size
will contain an implementation defined (de facto garbage) value.
Here is a solution using boxplot.stats
# create a dummy data frame with outliers
df = data.frame(y = c(-100, rnorm(100), 100))
# create boxplot that includes outliers
p0 = ggplot(df, aes(y = y)) + geom_boxplot(aes(x = factor(1)))
# compute lower and upper whiskers
ylim1 = boxplot.stats(df$y)$stats[c(1, 5)]
# scale y limits based on ylim1
p1 = p0 + coord_cartesian(ylim = ylim1*1.05)
I fixed it just by changing target compile version to 1.8. Its in:
File >> Settings >> Build, Execution, Deployment >> Compiler >> Java Compiler
If you've been doing unit testing for a decent amount of time, I see no reason for it not to be approaching 95%+. However, at a minimum, I've always worked with 80%, even when new to testing.
This number should only include code written in the project (excludes frameworks, plugins, etc.) and maybe even exclude certain classes composed entirely of code written of calls to outside code. This sort of call should be mocked/stubbed.
I don't think there is any real legitimate way to access this via the DOM. It would be a security risk that browsers have of late locked down on to prevent drive-by uploads.
Small And Better One
var i = 0;
$("#container > option").each(function(){
if($(this).val().length > i) {
i = $(this).val().length;
console.log(i);
console.log($(this).val());
}
});
I just installed Sql server 2008, but i was unable to connect to any database instances. The commands @G Mastros posted listed no active instances.
So i looked in services and found that the SQL server agent was disabled. I fixed it by setting it to automatic and then starting it.
How many thousands of users?
I've run some TCP/IP client/server connection tests in the past on Windows 2003 Server and managed more than 70,000 connections on a reasonably low spec VM. (see here for details: http://www.lenholgate.com/blog/2005/10/the-64000-connection-question.html). I would be extremely surprised if Windows 2008 Server is limited to less than 2003 Server and, IMHO, the posting that Cloud links to is too vague to be much use. This kind of question comes up a lot, I blogged about why I don't really think that it's something that you should actually worry about here: http://www.serverframework.com/asynchronousevents/2010/12/one-million-tcp-connections.html.
Personally I'd test it and see. Even if there is no inherent limit in the Windows 2008 Server version that you intend to use there will still be practical limits based on memory, processor speed and server design.
If you want to run some 'generic' tests you can use my multi-client connection test and the associated echo server. Detailed here: http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html and here: http://www.lenholgate.com/blog/2005/11/simple-echo-servers.html. These are what I used to run my own tests for my server framework and these are what allowed me to create 70,000 active connections on a Windows 2003 Server VM with 760MB of memory.
Edited to add details from the comment below...
If you're already thinking of multiple servers I'd take the following approach.
Use the free tools that I link
to and prove to yourself that you
can create a reasonable number of
connections onto your target OS
(beware of the Windows limits on
dynamic ports which may cause your
client connections to fail, search
for MAX_USER_PORT
).
during development regularly test your actual server with test clients that can create connections and actually 'do something' on the server. This will help to prevent you building the server in ways that restrict its scalability. See here: http://www.serverframework.com/asynchronousevents/2010/10/how-to-support-10000-or-more-concurrent-tcp-connections-part-2-perf-tests-from-day-0.html
Another way of doing it is using HttpResponsePermanentRedirect like so:
In view.py
def url_redirect(request):
return HttpResponsePermanentRedirect("/new_url/")
In the url.py
url(r'^old_url/$', "website.views.url_redirect", name="url-redirect"),
java.time.LocalDate
From Java 1.8, you can use the method lengthOfMonth
on java.time.LocalDate
:
LocalDate date = LocalDate.of(2010, 1, 19);
int days = date.lengthOfMonth();
AngularJS form elements look for the required
attribute to perform validation functions. ng-required
allows you to set the required
attribute depending on a boolean test (for instance, only require field B - say, a student number - if the field A has a certain value - if you selected "student" as a choice)
As an example, <input required>
and <input ng-required="true">
are essentially the same thing
If you are wondering why this is this way, (and not just make <input required="true">
or <input required="false">
), it is due to the limitations of HTML - the required
attribute has no associated value - its mere presence means (as per HTML standards) that the element is required - so angular needs a way to set/unset required value (required="false"
would be invalid HTML)
Adding the option insides Eclipse immediately resolves the issue. To add the option
open preferences via application menu Window => Preferences (or on OSX Eclipse => Settings). Navigate to Team => Git => Configuration click Add entry..., then put http.sslVerify in the key box and false in the value box.
No, but you should be careful when using IF...ELSE...END IF in stored procs. If your code blocks are radically different, you may suffer from poor performance because the procedure plan will need to be re-cached each time. If it's a high-performance system, you may want to compile separate stored procs for each code block, and have your application decide which proc to call at the appropriate time.
Most likely the path you are trying to access does not exist. It seems you are trying to save to a relative location and you do not have an file extension in that string. If you need to use relative paths you can parse the path from ActiveWorkbook.FullName
EDIT: Better syntax would also be
ActiveWorkbook.SaveAs Filename:=myFileName, FileFormat:=xlWorkbookNormal
Python threads cannot take advantage of many cores. This is due to an internal implementation detail called the GIL (global interpreter lock) in the C implementation of python (cPython) which is almost certainly what you use.
The workaround is the multiprocessing
module http://www.python.org/dev/peps/pep-0371/ which was developed for this purpose.
Documentation: http://docs.python.org/library/multiprocessing.html
(Or use a parallel language.)
XDocument xdoc = XDocument.Load("data.xml");
var lv1s = xdoc.Root.Descendants("level1");
var lvs = lv1s.SelectMany(l=>
new string[]{ l.Attribute("name").Value }
.Union(
l.Descendants("level2")
.Select(l2=>" " + l2.Attribute("name").Value)
)
);
foreach (var lv in lvs)
{
result.AppendLine(lv);
}
Ps. You have to use .Root on any of these versions.
I did my back-to-top button like this
<li class="nav-item"><a class="nav-link active" href="#home">HOME</a></li>
<button type="button" class= "btn btn-light" name="button" style="float: right;"><a href="#top">Top</a></button>
Theoretically, yes. Practice, not. Most kernels (incl. linux) doesn't allow you a second bind()
to an already allocated port. It weren't a really big patch to make this allowed.
Conceptionally, we should differentiate between socket and port. Sockets are bidirectional communication endpoints, i.e. "things" where we can send and receive bytes. It is a conceptional thing, there is no such field in a packet header named "socket".
Port is an identifier which is capable to identify a socket. In case of the TCP, a port is a 16 bit integer, but there are other protocols as well (for example, on unix sockets, a "port" is essentially a string).
The main problem is the following: if an incoming packet arrives, the kernel can identify its socket by its destination port number. It is a most common way, but it is not the only possibility:
Because you are working on an application server, it will be able to do that.
In C, you can "simulate" exceptions along with automatic "object reclamation" through manual use of if + goto for explicit error handling.
I often write C code like the following (boiled down to highlight error handling):
#include <assert.h>
typedef int errcode;
errcode init_or_fail( foo *f, goo *g, poo *p, loo *l )
{
errcode ret = 0;
if ( ( ret = foo_init( f ) ) )
goto FAIL;
if ( ( ret = goo_init( g ) ) )
goto FAIL_F;
if ( ( ret = poo_init( p ) ) )
goto FAIL_G;
if ( ( ret = loo_init( l ) ) )
goto FAIL_P;
assert( 0 == ret );
goto END;
/* error handling and return */
/* Note that we finalize in opposite order of initialization because we are unwinding a *STACK* of initialized objects */
FAIL_P:
poo_fini( p );
FAIL_G:
goo_fini( g );
FAIL_F:
foo_fini( f );
FAIL:
assert( 0 != ret );
END:
return ret;
}
This is completely standard ANSI C, separates the error handling away from your mainline code, allows for (manual) stack unwinding of initialized objects much like C++ does, and it is completely obvious what is happening here. Because you are explicitly testing for failure at each point it does make it easier to insert specific logging or error handling at each place an error can occur.
If you don't mind a little macro magic, then you can make this more concise while doing other things like logging errors with stack traces. For example:
#include <assert.h>
#include <stdio.h>
#include <string.h>
#define TRY( X, LABEL ) do { if ( ( X ) ) { fprintf( stderr, "%s:%d: Statement '" #X "' failed! %d, %s\n", __FILE__, __LINE__, ret, strerror( ret ) ); goto LABEL; } while ( 0 )
typedef int errcode;
errcode init_or_fail( foo *f, goo *g, poo *p, loo *l )
{
errcode ret = 0;
TRY( ret = foo_init( f ), FAIL );
TRY( ret = goo_init( g ), FAIL_F );
TRY( ret = poo_init( p ), FAIL_G );
TRY( ret = loo_init( l ), FAIL_P );
assert( 0 == ret );
goto END;
/* error handling and return */
FAIL_P:
poo_fini( p );
FAIL_G:
goo_fini( g );
FAIL_F:
foo_fini( f );
FAIL:
assert( 0 != ret );
END:
return ret;
}
Of course, this isn't as elegant as C++ exceptions + destructors. For example, nesting multiple error handling stacks within one function this way isn't very clean. Instead, you'd probably want to break those out into self contained sub functions that similarly handle errors, initialize + finalize explicitly like this.
This also only works within a single function and won't keep jumping up the stack unless higher level callers implement similar explicit error handling logic, whereas a C++ exception will just keep jumping up the stack until it finds an appropriate handler. Nor does it allow you to throw an arbitrary type, but instead only an error code.
Systematically coding this way (i.e. - with a single entry and single exit point) also makes it very easy to insert pre and post ("finally") logic that will execute no matter what. You just put your "finally" logic after the END label.
I believe you could addClass to the element. But either way you'd have to use Jquery or reg JS
div {
opacity:0;
transition:opacity 1s linear;*
}
div.SomeClass {
opacity:1;
}
As Tmdean correctly pointed out you can use the Mid()
function. The MSDN Library also has a great reference section on VBScript which you can find here:
jQuery's empty()
function does just that:
$('#masterdiv').empty();
clears the master div
.
$('#masterdiv div').empty();
clears all the child div
s, but leaves the master intact.
componentDidUpdate(prevProps){
if (this.state.authToken==null&&prevProps.authToken==null) {
AccountKit.getCurrentAccessToken()
.then(token => {
if (token) {
AccountKit.getCurrentAccount().then(account => {
this.setState({
authToken: token,
loggedAccount: account
});
});
} else {
console.log("No user account logged");
}
})
.catch(e => console.log("Failed to get current access token", e));
}
}
item.date = $filter('date')(item.date, "dd/MM/yyyy"); // for conversion to string
http://docs.angularjs.org/api/ng.filter:date
But if you are using HTML5 type="date" then the ISO format yyyy-MM-dd MUST be used.
item.dateAsString = $filter('date')(item.date, "yyyy-MM-dd"); // for type="date" binding
<input type="date" ng-model="item.dateAsString" value="{{ item.dateAsString }}" pattern="dd/MM/YYYY"/>
http://www.w3.org/TR/html-markup/input.date.html
NOTE: use of pattern="" with type="date" looks non-standard, but it appears to work in the expected way in Chrome 31.
If this is your code, the correct solution is to rewrite it to not use Session()
, since that's no longer necessary in TensorFlow 2
If this is just code you're running, you can downgrade to TensorFlow 1 by running
pip3 install --upgrade --force-reinstall tensorflow-gpu==1.15.0
(or whatever the latest version of TensorFlow 1 is)
Here's another solution: Use the Database Publishing Wizard to export your schema, security and data to sql scripts. You can then take your current DB offline and re-create it with the scripts.
Sounds kind of foolish, but there are a couple advantages. First, there's no chance of losing data. Your original db (as long as you don't delete your DB when dropping it!) is safe, the new DB will be roughly as small as it can be, and you'll have two different snapshots of your current database - one ready to roll, one minified - you can choose from to back up.
For a bit more flexibility than with micronyks answer, you can do it like that:
1. In your template, add #myIdentifier
to the element you want to obtain the width from. Example:
<p #myIdentifier>
my-component works!
</p>
2. In your controller, you can use this with @ViewChild('myIdentifier')
to get the width:
import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.scss']
})
export class MyComponentComponent implements AfterViewInit {
constructor() { }
ngAfterViewInit() {
console.log(this.myIdentifier.nativeElement.offsetWidth);
}
@ViewChild('myIdentifier')
myIdentifier: ElementRef;
}
Security
About the security risk with ElementRef
, like this, there is none. There would be a risk, if you would modify the DOM using an ElementRef. But here you are only getting DOM Elements so there is no risk. A risky example of using ElementRef
would be: this.myIdentifier.nativeElement.onclick = someFunctionDefinedBySomeUser;
. Like this Angular doesn't get a chance to use its sanitisation mechanisms since someFunctionDefinedBySomeUser
is inserted directly into the DOM, skipping the Angular sanitisation.
You can also use numpy assuming if you are using python3.x here is an example
import numpy as np
x = 2.3
print(np.rint(x))
>>> 2.0
See ?read.table
. Basically, when you use read.table
, you specify a number indicating the column:
##Row names in the first column
read.table(filname.txt, row.names=1)
It seems like there is permission on mobile keypad setting, so the easiest way to do this is:
editText.setFilters(new InputFilter[]{new InputFilter.AllCaps()});
hope this will work
One alternative is to change up your module. Generally if you are exporting an object with a bunch of functions on it, it's easier to export a bunch of named functions, e.g.
export function foo() { console.log('foo') },
export function bar() { console.log('bar') },
export function baz() { foo(); bar() }
In this case you are export all of the functions with names, so you could do
import * as fns from './foo';
to get an object with properties for each function instead of the import you'd use for your first example:
import fns from './foo';
You can bulk import all aliases from one keystore to another:
keytool -importkeystore -srckeystore source.jks -destkeystore dest.jks
I have 2 servers setup on docker, reverse proxy & web server. This error started happening for all my websites all of a sudden after 1 year. When setting up earlier, I generated a self signed certificate on the web server.
So, I had to generate the SSL certificate again and it started working...
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ssl.key -out ssl.crt
The Gradle answer is to add a jar/manifest/attributes setting like this:
apply plugin: 'java'
jar {
manifest {
attributes 'Main-Class': 'com.package.app.Class'
}
}
Here is a snippet I wrote; to ask for users' password and set it in /etc/passwd. You can manipulate it a little probably to get what you need:
echo -n " Please enter the password for the given user: "
read userPass
useradd $userAcct && echo -e "$userPass\n$userPass\n" | passwd $userAcct > /dev/null 2>&1 && echo " User account has been created." || echo " ERR -- User account creation failed!"
!
I like to think of this as an explosive change that destroys all that has gone before it. Bang or exclamation mark means that you are making a permanent saved change in your code.
If you use for example Ruby's method for global substitutiongsub!
the substitution you make is permanent.
Another way you can imagine it, is opening a text file and doing find and replace, followed by saving. !
does the same in your code.
Another useful reminder if you come from the bash world is sed -i
has this similar effect of making permanent saved change.
use <textarea></textarea>
instead of leaving a space between the opening and closing tags as <textarea>
</textarea>
Also note that you can also "protect" a block from being formatted with @formatter:off and @formatter:on, avoiding a reformat on a comment for example, like in:
// Master dataframe
Dataset<Row> countyStateDf = df
.withColumn(
"countyState",
split(df.col("label"), ", "));
// I could split the column in one operation if I wanted:
// @formatter:off
// Dataset<Row> countyState0Df = df
// .withColumn(
// "state",
// split(df.col("label"), ", ").getItem(1))
// .withColumn(
// "county",
// split(df.col("label"), ", ").getItem(0));
// @formatter:on
countyStateDf.sample(.01).show(5, false);
I'm writing this to make sure I understand it properly.
Move semantics were created to avoid the unnecessary copying of large objects. Bjarne Stroustrup in his book "The C++ Programming Language" uses two examples where unnecessary copying occurs by default: one, the swapping of two large objects, and two, the returning of a large object from a method.
Swapping two large objects usually involves copying the first object to a temporary object, copying the second object to the first object, and copying the temporary object to the second object. For a built-in type, this is very fast, but for large objects these three copies could take a large amount of time. A "move assignment" allows the programmer to override the default copy behavior and instead swap references to the objects, which means that there is no copying at all and the swap operation is much faster. The move assignment can be invoked by calling the std::move() method.
Returning an object from a method by default involves making a copy of the local object and its associated data in a location which is accessible to the caller (because the local object is not accessible to the caller and disappears when the method finishes). When a built-in type is being returned, this operation is very fast, but if a large object is being returned, this could take a long time. The move constructor allows the programmer to override this default behavior and instead "reuse" the heap data associated with the local object by pointing the object being returned to the caller to heap data associated with the local object. Thus no copying is required.
In languages which do not allow the creation of local objects (that is, objects on the stack) these types of problems do not occur as all objects are allocated on the heap and are always accessed by reference.
Old way:
SELECT DATE_COLUMN + 1 is adding a day
SELECT DATE_COLUMN + N /24 to add hour(s) - N being number of hours
SELECT DATE_COLUMN + N /1440 to add minute(s) - N being number of minutes
SELECT DATE_COLUMN + N /86400 to add second(s) - N being number of seconds
Using INTERVAL:
SELECT DATE_COLUMN + INTERVAL 'N' HOUR or MINUTE or SECOND - N being a number of hours or minutes or seconds.
A panel expands to a span (or a div), with it's content within it. A placeholder is just that, a placeholder that's replaced by whatever you put in it.
Use continue;
instead of break;
to enter the next iteration of the loop without executing any more of the contained code.
foreach (Item item in myItemsList)
{
if (item.Name == string.Empty)
{
// Display error message and move to next item in list. Skip/ignore all validation
// that follows beneath
continue;
}
if (item.Weight > 100)
{
// Display error message and move to next item in list. Skip/ignore all validation
// that follows beneath
continue;
}
}
Official docs are here, but they don't add very much color.