You will have to access db through the ip of host machine, or if you want to access it via localhost:1521, then run webserver like -
docker run --net=host --name oracle-wls wls-image:latest
For Redmi and Mi devices turn off MIUI Optimization
Settings > Additional Settings > Developer Options > MIUI Optimization
Just run the following simple command on Raspberry Pi 3 running Raspbian Jessie.
run terminal and type
sudo raspi-config
Go to: >Advanced Option > Resolution > just set your resolution compatible fit with your screen.
then
reboot
If you didn't found the menu on configuration, please update your raspberry pi software configuration tool (raspi-config).
That's all TQ.
you can use instead of click :
$('#whatever').on('touchstart click', function(){ /* do something... */ });
I found the solution to this problem in a "}". I did some changes to my sketch and forgot to check for "}" and I had an extra one. As soon as I deleted it and compiled everything was fine.
Or echo 'put {path to file}' | sftp {user}@{host}:{dir}
, which would work in both unix and powershell.
set DSKTOPDIR="D:\test"
set IPADDRESS="23.23.3.23"
>%DSKTOPDIR%\script.ftp ECHO cd %PAY_REP%
>>%DSKTOPDIR%\script.ftp ECHO mget *.report
>>%DSKTOPDIR%\script.ftp ECHO bye
:: run PSFTP Commands
psftp <domain>@%IPADDRESS% -b %DSKTOPDIR%\script.ftp
Set values using set commands before above lines.
I believe this helps you.
Referre psfpt setup for below link https://www.ssh.com/ssh/putty/putty-manuals/0.68/Chapter6.html
I was searching why % doesn't seem to work. So, I tested out using 100vh instead of just setting it at 100% it seems that 100vh works really well across almost all browsers/devices.
example: you want to only display the top div to the user before it scrolls, like a hero banner module. But, at the top of the page is a navbar which is 68px in height. The following doesn't work for me at all doing just %
height: calc(100% - 68px);
There's was no change. The page just stayed the same. However, when swapping this to "vh" instead it works great! The div block you assign it too will stay on the viewer's device hight only. Until they decide to scroll down the page.
height: calc(100vh - 68px);
Change the +/- to include how big your header is on the top. If your navbar is say 120px in height then change 68px to 120px.
Hope this helps anyone who cannot get this working with using normal height: calc();
Try the line below to convert editText to integer.
int intVal = Integer.parseInt(mEtValue.getText().toString());
the reason of the exception has been explained already, however the suggested solution isn't really the best.
You should create a class that keeps a Scanner as private using Singleton Pattern, that makes that scanner unique on your code.
Then you can implement the methods you need or you can create a getScanner ( not recommended ) and you can control it with a private boolean, something like alreadyClosed.
If you are not aware how to use Singleton Pattern, here's a example:
public class Reader {
private Scanner reader;
private static Reader singleton = null;
private boolean alreadyClosed;
private Reader() {
alreadyClosed = false;
reader = new Scanner(System.in);
}
public static Reader getInstance() {
if(singleton == null) {
singleton = new Reader();
}
return singleton;
}
public int nextInt() throws AlreadyClosedException {
if(!alreadyClosed) {
return reader.nextInt();
}
throw new AlreadyClosedException(); //Custom exception
}
public double nextDouble() throws AlreadyClosedException {
if(!alreadyClosed) {
return reader.nextDouble();
}
throw new AlreadyClosedException();
}
public String nextLine() throws AlreadyClosedException {
if(!alreadyClosed) {
return reader.nextLine();
}
throw new AlreadyClosedException();
}
public void close() {
alreadyClosed = true;
reader.close();
}
}
Reference Decoder of CRL,CRT,CSR,NEW CSR,PRIVATE KEY, PUBLIC KEY,RSA,RSA Public Key Parser
RSA Public Key
-----BEGIN RSA PUBLIC KEY-----
-----END RSA PUBLIC KEY-----
Encrypted Private Key
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
-----END RSA PRIVATE KEY-----
CRL
-----BEGIN X509 CRL-----
-----END X509 CRL-----
CRT
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
CSR
-----BEGIN CERTIFICATE REQUEST-----
-----END CERTIFICATE REQUEST-----
NEW CSR
-----BEGIN NEW CERTIFICATE REQUEST-----
-----END NEW CERTIFICATE REQUEST-----
PEM
-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----
PKCS7
-----BEGIN PKCS7-----
-----END PKCS7-----
PRIVATE KEY
-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----
DSA KEY
-----BEGIN DSA PRIVATE KEY-----
-----END DSA PRIVATE KEY-----
Elliptic Curve
-----BEGIN EC PRIVATE KEY-----
-----END EC PRIVATE KEY-----
PGP Private Key
-----BEGIN PGP PRIVATE KEY BLOCK-----
-----END PGP PRIVATE KEY BLOCK-----
PGP Public Key
-----BEGIN PGP PUBLIC KEY BLOCK-----
-----END PGP PUBLIC KEY BLOCK-----
If you are generating a heap of commands to be run, then call that script from a terminal, you can try the following.
sftp login@host < /path/to/command/list
You will then be asked to enter your password (as per normal) however all the commands in the script run after that.
This is clearly not a completely automated option that can be used in a cron
job, but it can be used from a terminal.
All the above answers really help me to construct my answer, because of this I voted for all the answers that other users put it out: But I finally put together my own answer to exact problem I was dealing with:
As question clearly defined I had to access some of the siblings and its children in a dom structure: This solution will iterate over the images in the dom structure and construct image name using product title and save the image to the local directory.
import urlparse
from urllib2 import urlopen
from urllib import urlretrieve
from BeautifulSoup import BeautifulSoup as bs
import requests
def getImages(url):
#Download the images
r = requests.get(url)
html = r.text
soup = bs(html)
output_folder = '~/amazon'
#extracting the images that in div(s)
for div in soup.findAll('div', attrs={'class':'image'}):
modified_file_name = None
try:
#getting the data div using findNext
nextDiv = div.findNext('div', attrs={'class':'data'})
#use findNext again on previous object to get to the anchor tag
fileName = nextDiv.findNext('a').text
modified_file_name = fileName.replace(' ','-') + '.jpg'
except TypeError:
print 'skip'
imageUrl = div.find('img')['src']
outputPath = os.path.join(output_folder, modified_file_name)
urlretrieve(imageUrl, outputPath)
if __name__=='__main__':
url = r'http://www.amazon.com/s/ref=sr_pg_1?rh=n%3A172282%2Ck%3Adigital+camera&keywords=digital+camera&ie=UTF8&qid=1343600585'
getImages(url)
I have found that ASCII 12 make a Form feed, that is a new page. here is a wikipedia definition
"Form feed is a page-breaking ASCII control character. It forces the printer to eject the current page and to continue printing at the top of another"
The code is
Serial.write(12);
Arduino Terminate doesn't support the character but Putty a light open source telnet client can do it
An Example of the code
void setup() {
Serial.begin(9600);//Initializase the serial transmiter speed
}
void loop() {
//Code tested with Putty terminal
Serial.write(12);//ASCII for a Form feed
Serial.println("This is the title of a new page");// your code
delay(500);//delay for visual
}
Fix for new Android 6.0 Marshmallow Fixed my issue when I updated to API 23 (Android 6.0 Marshmallow) by updating the build tools version to 23.0.0 as follows:
android {
buildToolsVersion '23.0.0'
...
And went to File > Project Structure , chose Properties tab then updated the Compile Sdk version to "API 23: Android 5.X (MNC)" and the Build tools version to "23.0.0"
<object classid="CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701"
height="285" id="mediaPlayer" standby="Loading Microsoft Windows Media Player components..."
type="application/x-oleobject" width="360" style="margin-bottom:30px;">
<param name="fileName" value="mms://my_IP_Address:my_port" />
<param name="animationatStart" value="true" />
<param name="transparentatStart" value="true" />
<param name="autoStart" value="true" />
<param name="showControls" value="true" />
<param name="loop" value="true" />
<embed autosize="-1" autostart="true" bgcolor="darkblue" designtimesp="5311" displaysize="4"
height="285" id="mediaPlayer" loop="true" name="mediaPlayer" pluginspage="http://microsoft.com/windows/mediaplayer/en/download/"
showcontrols="true" showdisplay="0" showstatusbar="-1" showtracker="-1" src="mms://my_IP_Address:my_port"
type="application/x-mplayer2" videoborder3d="-1" width="360"></embed>
</object>
Try this one:
$("div.subtab_left li.notebook a").click(function(e) {
e.preventDefault();
return false;
});
in my case I updated the SDK (on the settings in genymotion), or then the genymotion update
Try echo_read_request_body.
"echo_read_request_body ... Explicitly reads request body so that the $request_body variable will always have non-empty values (unless the body is so big that it has been saved by Nginx to a local temporary file)."
location /log {
log_format postdata $request_body;
access_log /mnt/logs/nginx/my_tracking.access.log postdata;
echo_read_request_body;
}
My requirements were a bit stricter:
My initial thought was to substitute our clunky Path class for a case insensitive unicode subclass - but:
some_dict[CIstr(path)]
is ugly)So I had finally to write down that case insensitive dict. Thanks to code by @AaronHall that was made 10 times easier.
class CIstr(unicode):
"""See https://stackoverflow.com/a/43122305/281545, especially for inlines"""
__slots__ = () # does make a difference in memory performance
#--Hash/Compare
def __hash__(self):
return hash(self.lower())
def __eq__(self, other):
if isinstance(other, CIstr):
return self.lower() == other.lower()
return NotImplemented
def __ne__(self, other):
if isinstance(other, CIstr):
return self.lower() != other.lower()
return NotImplemented
def __lt__(self, other):
if isinstance(other, CIstr):
return self.lower() < other.lower()
return NotImplemented
def __ge__(self, other):
if isinstance(other, CIstr):
return self.lower() >= other.lower()
return NotImplemented
def __gt__(self, other):
if isinstance(other, CIstr):
return self.lower() > other.lower()
return NotImplemented
def __le__(self, other):
if isinstance(other, CIstr):
return self.lower() <= other.lower()
return NotImplemented
#--repr
def __repr__(self):
return '{0}({1})'.format(type(self).__name__,
super(CIstr, self).__repr__())
def _ci_str(maybe_str):
"""dict keys can be any hashable object - only call CIstr if str"""
return CIstr(maybe_str) if isinstance(maybe_str, basestring) else maybe_str
class LowerDict(dict):
"""Dictionary that transforms its keys to CIstr instances.
Adapted from: https://stackoverflow.com/a/39375731/281545
"""
__slots__ = () # no __dict__ - that would be redundant
@staticmethod # because this doesn't make sense as a global function.
def _process_args(mapping=(), **kwargs):
if hasattr(mapping, 'iteritems'):
mapping = getattr(mapping, 'iteritems')()
return ((_ci_str(k), v) for k, v in
chain(mapping, getattr(kwargs, 'iteritems')()))
def __init__(self, mapping=(), **kwargs):
# dicts take a mapping or iterable as their optional first argument
super(LowerDict, self).__init__(self._process_args(mapping, **kwargs))
def __getitem__(self, k):
return super(LowerDict, self).__getitem__(_ci_str(k))
def __setitem__(self, k, v):
return super(LowerDict, self).__setitem__(_ci_str(k), v)
def __delitem__(self, k):
return super(LowerDict, self).__delitem__(_ci_str(k))
def copy(self): # don't delegate w/ super - dict.copy() -> dict :(
return type(self)(self)
def get(self, k, default=None):
return super(LowerDict, self).get(_ci_str(k), default)
def setdefault(self, k, default=None):
return super(LowerDict, self).setdefault(_ci_str(k), default)
__no_default = object()
def pop(self, k, v=__no_default):
if v is LowerDict.__no_default:
# super will raise KeyError if no default and key does not exist
return super(LowerDict, self).pop(_ci_str(k))
return super(LowerDict, self).pop(_ci_str(k), v)
def update(self, mapping=(), **kwargs):
super(LowerDict, self).update(self._process_args(mapping, **kwargs))
def __contains__(self, k):
return super(LowerDict, self).__contains__(_ci_str(k))
@classmethod
def fromkeys(cls, keys, v=None):
return super(LowerDict, cls).fromkeys((_ci_str(k) for k in keys), v)
def __repr__(self):
return '{0}({1})'.format(type(self).__name__,
super(LowerDict, self).__repr__())
Implicit vs explicit is still a problem, but once dust settles, renaming of attributes/variables to start with ci (and a big fat doc comment explaining that ci stands for case insensitive) I think is a perfect solution - as readers of the code must be fully aware that we are dealing with case insensitive underlying data structures. This will hopefully fix some hard to reproduce bugs, which I suspect boil down to case sensitivity.
Comments/corrections welcome :)
Shell calls to reverse (as mentioned above) are very good to debug these problems, but there are two critical conditions:
Yes, it's logical. Yes, it's also confusing because reverse will only throw the exception and won't give you any further hints.
An example of URL pattern:
url(r'^cookies/(?P<hostname>[^/]+)/(?P<url_id>\d+)/$', 'register_site.views.show_cookies', name='show_cookies'),
And then what happens in shell:
>>> from register_site.views import show_cookies
>>> reverse(show_cookies)
NoReverseMatch: Reverse for 'register_site.views.show_cookies' with arguments '()' and keyword arguments '{}' not found.
It doesn't work because I supplied no arguments.
>>> reverse('show_cookies', kwargs={'url_id':123,'hostname': 'aaa'})
'/cookies/aaa/123'
Now it worked, but...
>>> reverse('show_cookies', kwargs={'url_id':'x','hostname': 'www.dupa.com'})
NoReverseMatch: Reverse for 'show_cookies' with arguments '()' and keyword arguments '{'url_id': 'x', 'hostname': 'www.dupa.com'}' not found.
Now it didn't work because url_id didn't match the regexp (expected numeric, supplied string).
You can use reverse with both positional arguments and keyword arguments. The syntax is:
reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None)
As it comes to the url template tag, there's funny thing about it. Django documentation gives example of using quoted view name:
{% url 'news.views.year_archive' yearvar %}
So I used it in a similar way in my HTML template:
{% url 'show_cookies' hostname=u.hostname url_id=u.pk %}
But this didn't work for me. But the exception message gave me a hint of what could be wrong - note the double single quotes around view name:
Reverse for ''show_cookies'' with arguments...
It started to work when I removed the quotes:
{% url show_cookies hostname=u.hostname url_id=u.pk %}
And this is confusing.
Here's the mysql reference for cursors. So I'm guessing it's something like this:
DECLARE done INT DEFAULT 0;
DECLARE products_id INT;
DECLARE result varchar(4000);
DECLARE cur1 CURSOR FOR SELECT products_id FROM sets_products WHERE set_id = 1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur1;
REPEAT
FETCH cur1 INTO products_id;
IF NOT done THEN
CALL generate_parameter_list(@product_id, @result);
SET param = param + "," + result; -- not sure on this syntax
END IF;
UNTIL done END REPEAT;
CLOSE cur1;
-- now trim off the trailing , if desired
If you are not able to upgrade your Python version to 2.7.9, and want to suppress warnings,
you can downgrade your 'requests' version to 2.5.3:
pip install requests==2.5.3
In response to rgrig's benchmark, the time taken to open/close the FileChannel & RandomAccessFile instances also needs to be taken into account, as these classes will open a stream for reading the file.
After modifying the benchmark, I got these results for 1 iterations on a 85MB file:
file totalTime: 48000 (48 us)
raf totalTime: 261000 (261 us)
channel totalTime: 7020000 (7 ms)
For 10000 iterations on same file:
file totalTime: 80074000 (80 ms)
raf totalTime: 295417000 (295 ms)
channel totalTime: 368239000 (368 ms)
If all you need is the file size, file.length() is the fastest way to do it. If you plan to use the file for other purposes like reading/writing, then RAF seems to be a better bet. Just don't forget to close the file connection :-)
import java.io.File;
import java.io.FileInputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Map;
public class FileSizeBench
{
public static void main(String[] args) throws Exception
{
int iterations = 1;
String fileEntry = args[0];
Map<String, Long> times = new HashMap<String, Long>();
times.put("file", 0L);
times.put("channel", 0L);
times.put("raf", 0L);
long fileSize;
long start;
long end;
File f1;
FileChannel channel;
RandomAccessFile raf;
for (int i = 0; i < iterations; i++)
{
// file.length()
start = System.nanoTime();
f1 = new File(fileEntry);
fileSize = f1.length();
end = System.nanoTime();
times.put("file", times.get("file") + end - start);
// channel.size()
start = System.nanoTime();
channel = new FileInputStream(fileEntry).getChannel();
fileSize = channel.size();
channel.close();
end = System.nanoTime();
times.put("channel", times.get("channel") + end - start);
// raf.length()
start = System.nanoTime();
raf = new RandomAccessFile(fileEntry, "r");
fileSize = raf.length();
raf.close();
end = System.nanoTime();
times.put("raf", times.get("raf") + end - start);
}
for (Map.Entry<String, Long> entry : times.entrySet()) {
System.out.println(entry.getKey() + " totalTime: " + entry.getValue() + " (" + getTime(entry.getValue()) + ")");
}
}
public static String getTime(Long timeTaken)
{
if (timeTaken < 1000) {
return timeTaken + " ns";
} else if (timeTaken < (1000*1000)) {
return timeTaken/1000 + " us";
} else {
return timeTaken/(1000*1000) + " ms";
}
}
}
Both or
and ||
evaluate to true if either operand is true. They evaluate their second operand only if the first is false.
As with and
, the only difference between or
and ||
is their precedence.
Just to make life interesting, and
and or
have the same precedence, while &&
has a higher precedence than ||
.
To address the question
How to use Apple's new San Francisco font on a webpage
font-family: -apple-system, system-ui, BlinkMacSystemFont;
or (even shorter):
font-family: -apple-system, BlinkMacSystemFont;
should suffice.
If you want to default to system font on multiple platforms, though, I'd suggest:
font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, Ubuntu;
-apple-system
— San Francisco in Safari (on Mac OS X and iOS); Neue Helvetica and Lucida Grande on older versions of Mac OS X.system-ui
— default UI font on a given platform.BlinkMacSystemFont
— equivalent of -apple-system
, for Chrome on Mac OS X."Segoe UI"
— Windows (Vista+) and Windows Phone.Roboto
— Android (Ice Cream Sandwich (4.0)+) and Chrome OS.Ubuntu
— all versions of Ubuntu.The idea is borrowed from the following issue on github.
You can look up fonts for other OS or older versions of them in this article on css-tricks.
Well done Sebastian J above.
I had the "buffer problem" with a few lines of test code I had, and added the encoding information and it solved it, see below.
software
// process.stdin.setEncoding('utf8');
process.stdin.on('data', (data) => {
console.log(typeof(data), data);
});
input
hello world
output
object <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64 0d 0a>
software
process.stdin.setEncoding('utf8'); // <- Activate!
process.stdin.on('data', (data) => {
console.log(typeof(data), data);
});
input
hello world
output
string hello world
I had countless issues doing this but finally came up with a solution that works.
Basically the code below is adding a click handler to the video but ignoring all the clicks on the lower part (0.82 is arbitrary but seems to work on all sizes).
$("video").click(function(e){
// get click position
var clickY = (e.pageY - $(this).offset().top);
var height = parseFloat( $(this).height() );
// avoids interference with controls
if(y > 0.82*height) return;
// toggles play / pause
this.paused ? this.play() : this.pause();
});
Use column selection. Column selection is one of the unique features of Sublime2; it is used to give you multiple matched cursors (tutorial here). To get multiple cursors, do one of the following:
Mouse:
Hold down the shift (Windows/Linux) or option key (Mac) while selecting a region with the mouse.
Clicking middle mouse button (or scroll) will select as a column also.
Keyboard:
You now have multiple lines selected, so you could type a quotation mark at the beginning and end of each line. It would be better to take advantage of Sublime's capabilities, and just type ". When you do this, Sublime automatically quotes the selected text.
Type esc to exit multiple cursor mode.
In my case I was trying to do dependency injection for an object which required constructor arguments. In this case, during Startup I just provided the arguments from the configuration file, for example:
var config = Configuration.GetSection("subservice").Get<SubServiceConfig>();
services.AddScoped<ISubService>(provider => new SubService(config.value1, config.value2));
To make a clean install of Python 3.6.5 use:
brew unlink python # ONLY if you have installed (with brew) another version of python 3
brew install --ignore-dependencies https://raw.githubusercontent.com/Homebrew/homebrew-core/f2a764ef944b1080be64bd88dca9a1d80130c558/Formula/python.rb
If you prefer to recover a previously installed version, then:
brew info python # To see what you have previously installed
brew switch python 3.x.x_x # Ex. 3.6.5_1
There are two formulas for installing Python with Homebrew: python@2
and python
.
The first is for Python 2 and the second for Python 3.
Note: You can find outdated answers on the web where it is mentioned python3
as the formula name for installing Python version 3. Now it's just python
!
By default, with these formulas you can install the latest version of the corresponding major version of Python. So, you cannot directly install a minor version like 3.6.
With brew
, you can install a package using the address of the formula, for example in a git repository.
brew install https://the/address/to/the/formula/FORMULA_NAME.rb
Or specifically for Python 3
brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/COMMIT_IDENTIFIER/Formula/python.rb
The address you must specify is the address to the last commit of the formula (python.rb) for the desired version. You can find the commint identifier by looking at the history for homebrew-core/Formula/python.rb
https://github.com/Homebrew/homebrew-core/commits/master/Formula/python.rb
In the link above you will not find a formula for a version of Python above 3.6.5. After the maintainers of that (official) repository released Python 3.7, they only submit updates to the recipe of Python 3.7.
As explained above, with homebrew you have only Python 2 (python@2) and Python 3 (python), there is no explicit formula for Python 3.6.
Although those minor updates are mostly irrelevant in most cases and for most users, I will search if someone has done an explicit formula for 3.6.
first get the profiler Exe from: http://expressprofiler.codeplex.com
then you can add it simply to the Management studio:
Tools -> External tools... ->
a- locate the exe file on your disk (If installed, it's typically C:\Program Files (x86)\ExpressProfiler\ExpressProfiler.exe)
b- give it a name e.g. Express Profiler
that's it :) you have your Profiler with your sql express edition
Try using an ImageList
ImageList imgList = new ImageList;
imgList.TransparentColor = Color.White;
Load the image like this:
picturebox.Image = imgList.Images[img_index];
Use the IP instead:
DROP USER 'root'@'127.0.0.1'; GRANT ALL PRIVILEGES ON . TO 'root'@'%';
For more possibilities, see this link.
To create the root user, seeing as MySQL is local & all, execute the following from the command line (Start > Run > "cmd" without quotes):
mysqladmin -u root password 'mynewpassword'
You can expend the following function in order to pull out more parameters from the DB before the insert:
--
-- insert_employee (Function)
--
CREATE OR REPLACE FUNCTION insert_employee(p_emp_id in number, p_emp_name in varchar2, p_emp_address in varchar2, p_emp_state in varchar2, p_emp_position in varchar2, p_emp_manager in varchar2)
RETURN VARCHAR2 AS
p_state_id varchar2(30) := '';
BEGIN
select state_id
into p_state_id
from states where lower(emp_state) = state_name;
INSERT INTO Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager) VALUES
(p_emp_id, p_emp_name, p_emp_address, p_state_id, p_emp_position, p_emp_manager);
return 'SUCCESS';
EXCEPTION
WHEN others THEN
RETURN 'FAIL';
END;
/
I needed this functionality for an RSS feed on our company's website. This is what I came up with:
// Create Variables_x000D_
var allOSB = [];_x000D_
var mxh = '';_x000D_
_x000D_
window.onload = function() {_x000D_
// Set Variables_x000D_
allOSB = document.getElementsByClassName("only-so-big");_x000D_
_x000D_
if (allOSB.length > 0) {_x000D_
mxh = window.getComputedStyle(allOSB[0]).getPropertyValue('max-height');_x000D_
mxh = parseInt(mxh.replace('px', ''));_x000D_
_x000D_
// Add read-more button to each OSB section_x000D_
for (var i = 0; i < allOSB.length; i++) {_x000D_
var el = document.createElement("button");_x000D_
el.innerHTML = "Read More";_x000D_
el.setAttribute("type", "button");_x000D_
el.setAttribute("class", "read-more hid");_x000D_
_x000D_
insertAfter(allOSB[i], el);_x000D_
}_x000D_
}_x000D_
_x000D_
// Add click function to buttons_x000D_
var readMoreButtons = document.getElementsByClassName("read-more");_x000D_
for (var i = 0; i < readMoreButtons.length; i++) {_x000D_
readMoreButtons[i].addEventListener("click", function() { _x000D_
revealThis(this);_x000D_
}, false);_x000D_
}_x000D_
_x000D_
// Update buttons so only the needed ones show_x000D_
updateReadMore();_x000D_
}_x000D_
// Update on resize_x000D_
window.onresize = function() {_x000D_
updateReadMore();_x000D_
}_x000D_
_x000D_
// show only the necessary read-more buttons_x000D_
function updateReadMore() {_x000D_
if (allOSB.length > 0) {_x000D_
for (var i = 0; i < allOSB.length; i++) {_x000D_
if (allOSB[i].scrollHeight > mxh) {_x000D_
if (allOSB[i].hasAttribute("style")) {_x000D_
updateHeight(allOSB[i]);_x000D_
}_x000D_
allOSB[i].nextElementSibling.className = "read-more";_x000D_
} else {_x000D_
allOSB[i].nextElementSibling.className = "read-more hid";_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
function revealThis(current) {_x000D_
var el = current.previousElementSibling;_x000D_
if (el.hasAttribute("style")) {_x000D_
current.innerHTML = "Read More";_x000D_
el.removeAttribute("style");_x000D_
} else {_x000D_
updateHeight(el);_x000D_
current.innerHTML = "Show Less";_x000D_
}_x000D_
}_x000D_
_x000D_
function updateHeight(el) {_x000D_
el.style.maxHeight = el.scrollHeight + "px";_x000D_
}_x000D_
_x000D_
// thanks to karim79 for this function_x000D_
// http://stackoverflow.com/a/4793630/5667951_x000D_
function insertAfter(referenceNode, newNode) {_x000D_
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);_x000D_
}
_x000D_
@import url('https://fonts.googleapis.com/css?family=Open+Sans:600');_x000D_
_x000D_
*,_x000D_
*:before,_x000D_
*:after {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
html,_x000D_
body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
width: 100%;_x000D_
}_x000D_
body {_x000D_
font-family: 'Open Sans', sans-serif;_x000D_
}_x000D_
h1 {_x000D_
text-align: center;_x000D_
}_x000D_
.main-container {_x000D_
margin: 30px auto;_x000D_
max-width: 1000px;_x000D_
padding: 20px;_x000D_
}_x000D_
.only-so-big p {_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
}_x000D_
p {_x000D_
font-size: 15px;_x000D_
line-height: 20px;_x000D_
}_x000D_
hr {_x000D_
background: #ccc;_x000D_
display: block;_x000D_
height: 1px;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
_x000D_
/*_x000D_
NECESSARY SECTION_x000D_
*/_x000D_
.only-so-big {_x000D_
background: rgba(178, 252, 255, .3);_x000D_
height: 100%;_x000D_
max-height: 100px;_x000D_
overflow: hidden;_x000D_
-webkit-transition: max-height .75s;_x000D_
transition: max-height .75s;_x000D_
}_x000D_
_x000D_
.read-more {_x000D_
background: none;_x000D_
border: none;_x000D_
color: #1199f9;_x000D_
cursor: pointer;_x000D_
font-size: 1em;_x000D_
outline: none; _x000D_
}_x000D_
.read-more:hover {_x000D_
text-decoration: underline;_x000D_
}_x000D_
.read-more:focus {_x000D_
outline: none;_x000D_
}_x000D_
.read-more::-moz-focus-inner {_x000D_
border: 0;_x000D_
}_x000D_
.hid {_x000D_
display: none;_x000D_
}
_x000D_
<div class="main-container">_x000D_
<h1>Controlling Different Content Size</h1>_x000D_
<p>We're working with an RSS feed and have had issues with some being much larger than others (content wise). I only want to show the "Read More" button if it's needed.</p>_x000D_
<div class="only-so-big">_x000D_
<p>This is just a short guy. No need for the read more button.</p>_x000D_
</div>_x000D_
<hr>_x000D_
<div class="only-so-big">_x000D_
<p>This one has way too much content to show. Best be saving it for those who want to read everything in here.</p>_x000D_
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia_x000D_
voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi THE END!</p>_x000D_
</div>_x000D_
<hr>_x000D_
<div class="only-so-big">_x000D_
<p>Another small section with not a lot of content</p>_x000D_
</div>_x000D_
<hr>_x000D_
<div class="only-so-big">_x000D_
<p>Make Window smaller to show "Read More" button.<br> totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed?</p>_x000D_
</div>_x000D_
</div>
_x000D_
You can use the wmic command:
wmic path CIM_LogicalDevice where "Description like 'USB%'" get /value
It is generally expected that modules of code such as .cpp
files are compiled once and linked to in multiple projects, to avoid unnecessary repetitive compilation of logic. For example, g++ -o class.cpp
would produce class.o
which you could then link from multiple projects to using g++ main.cpp class.o
.
We could use #include
as our linker, as you seem to be implying, but that would just be silly when we know how to link properly using our compiler with less keystrokes and less wasteful repetition of compilation, rather than our code with more keystrokes and more wasteful repetition of compilation...
The header files are still required to be included into each of the multiple projects, however, because this provides the interface for each module. Without these headers the compiler wouldn't know about any of the symbols introduced by the .o
files.
It is important to realise that the header files are what introduce the definitions of symbols for those modules; once that is realised then it makes sense that multiple inclusions could cause redefinitions of symbols (which causes errors), so we use include guards to prevent such redefinitions.
One way is by creating a soft link to whichever directory you want to list in the /var/www/html/ directory.
sudo ln -s /home/ /var/www/html/
Keep in mind the security.
Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.
You should read Working with Auto Layout Programmatically and Visual Format Language.
You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.
You need to make your regex pattern 'non-greedy' by adding a '?' after the '.+'
By default, '*' and '+' are greedy in that they will match as long a string of chars as possible, ignoring any matches that might occur within the string.
Non-greedy makes the pattern only match the shortest possible match.
See Watch Out for The Greediness! for a better explanation.
Or alternately, change your regex to
\(([^\)]+)\)
which will match any grouping of parens that do not, themselves, contain parens.
Try:
SELECT COALESCE(NULLIF(field, ''), another_field) FROM table_name
Actually I use _ method names when I need to differ between parent and child class names. I've read some codes that used this way of creating parent-child classes. As an example I can provide this code:
class ThreadableMixin:
def start_worker(self):
threading.Thread(target=self.worker).start()
def worker(self):
try:
self._worker()
except tornado.web.HTTPError, e:
self.set_status(e.status_code)
except:
logging.error("_worker problem", exc_info=True)
self.set_status(500)
tornado.ioloop.IOLoop.instance().add_callback(self.async_callback(self.results))
...
and the child that have a _worker method
class Handler(tornado.web.RequestHandler, ThreadableMixin):
def _worker(self):
self.res = self.render_string("template.html",
title = _("Title"),
data = self.application.db.query("select ... where object_id=%s", self.object_id)
)
...
One additional suggestion to be explicit. It seems best to go from specific to general down the stack of errors to get the desired error to be caught, so the specific ones don't get masked by the general one.
url='http://www.google.com/blahblah'
try:
r = requests.get(url,timeout=3)
r.raise_for_status()
except requests.exceptions.HTTPError as errh:
print ("Http Error:",errh)
except requests.exceptions.ConnectionError as errc:
print ("Error Connecting:",errc)
except requests.exceptions.Timeout as errt:
print ("Timeout Error:",errt)
except requests.exceptions.RequestException as err:
print ("OOps: Something Else",err)
Http Error: 404 Client Error: Not Found for url: http://www.google.com/blahblah
vs
url='http://www.google.com/blahblah'
try:
r = requests.get(url,timeout=3)
r.raise_for_status()
except requests.exceptions.RequestException as err:
print ("OOps: Something Else",err)
except requests.exceptions.HTTPError as errh:
print ("Http Error:",errh)
except requests.exceptions.ConnectionError as errc:
print ("Error Connecting:",errc)
except requests.exceptions.Timeout as errt:
print ("Timeout Error:",errt)
OOps: Something Else 404 Client Error: Not Found for url: http://www.google.com/blahblah
Seems that new browsers support most of the tags: <header>
, <section>
etc. For older browsers (IE, Fx2, Camino etc) then you can use this to allow styling of these tags:
document.createElement('header');
Would make these older browsers allow CSS styling of a header tag, instead of just ignoring it.
This means that you can now use the new tags without any loss of functionality, which is a good start!
One may write an extension method like this:
/// <summary>
/// Includes an array of navigation properties for the specified query
/// </summary>
/// <typeparam name="T">The type of the entity</typeparam>
/// <param name="query">The query to include navigation properties for that</param>
/// <param name="navProperties">The array of navigation properties to include</param>
/// <returns></returns>
public static IQueryable<T> Include<T>(this IQueryable<T> query, params string[] navProperties)
where T : class
{
foreach (var navProperty in navProperties)
query = query.Include(navProperty);
return query;
}
And use it like this even in a generic implementation:
string[] includedNavigationProperties = new string[] { "NavProp1.SubNavProp", "NavProp2" };
var query = context.Set<T>()
.Include(includedNavigationProperties);
If none of the above solutions worked, then stop and do a sanity check.
I got burned using the wrong -G <config>
string and it gave me this misleading error.
First, run from the VS Command Prompt not the regular command prompt. You can find it in
Start Menu -> Visual Studio 2015 -> MSBuild Command Prompt for VS2015
This sets up all the correct paths to VS tools, etc.
Now see what generators are available from cmake...
cmake -help
...<snip>...
The following generators are available on this platform:
Visual Studio 15 [arch] = Generates Visual Studio 15 project files.
Optional [arch] can be "Win64" or "ARM".
Visual Studio 14 2015 [arch] = Generates Visual Studio 2015 project files.
Optional [arch] can be "Win64" or "ARM".
Visual Studio 12 2013 [arch] = Generates Visual Studio 2013 project files.
Optional [arch] can be "Win64" or "ARM".
Visual Studio 11 2012 [arch] = Generates Visual Studio 2012 project files.
Optional [arch] can be "Win64" or "ARM".
Visual Studio 10 2010 [arch] = Generates Visual Studio 2010 project files.
Optional [arch] can be "Win64" or "IA64".
...
Then chose the appropriate string with the [arch] added.
mkdir _build
cd _build
cmake .. -G "Visual Studio 15 Win64"
Running cmake in a subdirectory makes it easier to do a 'clean' since you can just delete everything in that directory.
I upgraded to Visual Studio 15 but wasn't paying attention and was trying to generate for 2012.
Based on your comment, moddify this:
$( '.bgHeaderH2' ).html (); // will return whatever is inside the DIV
to:
$( '.bgHeaderH2', $( this ) ).html (); // will return whatever is inside the DIV
More about selectors: https://api.jquery.com/category/selectors/
This took me a while to figure out so this is how I got it working - Angular WebAPI ASP Routing without the # for SEO
Add $locationProvider.html5Mode(true); to app.config
I needed a certain controller (which was in the home controller) to be ignored for uploading images so I added that rule to RouteConfig
routes.MapRoute(
name: "Default2",
url: "Home/{*.}",
defaults: new { controller = "Home", action = "SaveImage" }
);
In Global.asax add the following - making sure to ignore api and image upload paths let them function as normal otherwise reroute everything else.
private const string ROOT_DOCUMENT = "/Index.html";
protected void Application_BeginRequest(Object sender, EventArgs e)
{
var path = Request.Url.AbsolutePath;
var isApi = path.StartsWith("/api", StringComparison.InvariantCultureIgnoreCase);
var isImageUpload = path.StartsWith("/home", StringComparison.InvariantCultureIgnoreCase);
if (isApi || isImageUpload)
return;
string url = Request.Url.LocalPath;
if (!System.IO.File.Exists(Context.Server.MapPath(url)))
Context.RewritePath(ROOT_DOCUMENT);
}
Make sure to use $location.url('/XXX') and not window.location ... to redirect
Reference the CSS files with absolute path
and not
<link href="app/content/bootstrapwc.css" rel="stylesheet" />
Final note - doing it this way gave me full control and I did not need to do anything to the web config.
Hope this helps as this took me a while to figure out.
Finally got working :)
using System.Net.Mail;
using System.Text;
...
// Command line argument must the the SMTP host.
SmtpClient client = new SmtpClient();
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("[email protected]","password");
MailMessage mm = new MailMessage("[email protected]", "[email protected]", "test", "test");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
client.Send(mm);
sorry about poor spelling before
To attempt command line arguments directly is not possible.
One alternative might be environment variables (https://superuser.com/questions/728951/systemd-giving-my-service-multiple-arguments).
This is where I found the answer: http://www.freedesktop.org/software/systemd/man/systemctl.html
so sudo systemctl restart myprog -v
-- systemctl will think you're trying to set one of its flags, not myprog's flag.
sudo systemctl restart myprog someotheroption
-- systemctl will restart myprog and the someotheroption service, if it exists.
It should just be:
git diff --cached
--cached
means show the changes in the cache/index (i.e. staged changes) against the current HEAD
. --staged
is a synonym for --cached
.
--staged
and --cached
does not point to HEAD
, just difference with respect to HEAD
. If you cherry pick what to commit using git add --patch
(or git add -p
), --staged
will return what is staged.
If you want it to be legitimate, you have two options, cloud based Mac solutions or cross-platform development tools. You may consider the hackintosh approach or virtual machines if you don't care about legal stuff. If you have a decent PC, running a virtual machine would be the easiest way to go. You may never know which hardware will have driver issues on a hackintosh.
I've tried all these approaches and they all have pros and cons, but for the second group, I feel kind of guilty. I develop apps to make a living and I wouldn't want to rip off someone else for it.
If you are making a small project, cloud based Macs may prove useful. Rent it for a short time, develop your project and off you go. Don't bother learning anything new.
However, if your project is getting big, cross-platform frameworks seem to be the only alternative. The critical thing is that you need to choose wisely. There are so many hybrid frameworks, but what they do can be summarized in one sentence as "diplaying web pages in an app wrapper" and developers' negative experience with hybrid frameworks also affects native frameworks.
I tried three of these (Titanium, Smartface and Xamarin) and they all claim to produce "real native output" and in my opinion their claims are correct. You need to test and see it yoursrlf, it's not easy to describe the native feeling. In a previous comment, it was indicated that it takes some effort to learn these platforms, but once you get to know them, you can develop not just iOS applications but Android applications as well, all with the common code base. And of course, they are much cheaper than a cloud Mac. Some of them are even free. You would need a Mac only for store submission.
If you know JavaScript, try Titanium and Smartface and if you know C#, try Xamarin. Just note that for the device simuator, Titanium is dependent on a Mac, but Smartface has a simulator app for Windows development and it works better than I expected. On the other hand, Xamarin requires a Mac in your network.
In SQL Management Studio you can:
Right click on the result set grid, select 'Save Result As...' and save in.
On a tool bar toggle 'Result to Text' button. This will prompt for file name on each query run.
If you need to automate it, use bcp tool.
If you happen to use Spring Boot you can make use of the BuildProperties class.
Take the following snippet from our OpenAPI configuration class as an example:
@Configuration
@RequiredArgsConstructor // <- lombok
public class OpenApi {
private final BuildProperties buildProperties; // <- you can also autowire it
@Bean
public OpenAPI yourBeautifulAPI() {
return new OpenAPI().info(new Info()
.title(buildProperties.getName())
.description("The description")
.version(buildProperties.getVersion())
.license(new License().name("Your company")));
}
}
let urlString = "http://heyhttp.org/me.json"
var request = URLRequest(url: URL(string: urlString)!)
let session = URLSession.shared
session.dataTask(with: request) {data, response, error in
if error != nil {
print(error!.localizedDescription)
return
}
do {
let jsonResult: NSDictionary? = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
print("Synchronous\(jsonResult)")
} catch {
print(error.localizedDescription)
}
}.resume()
I use this for a couple built-in primitive functions that I felt were really missing. One example is a find function that has the same usage semantics as filter, map, reduce.
def builtin_find(f, x, d=None):
for i in x:
if f(i):
return i
return d
import __builtin__
__builtin__.find = builtin_find
Once this is run (for instance, by importing near your entry point) all your modules can use find() as though, obviously, it was built in.
find(lambda i: i < 0, [1, 3, 0, -5, -10]) # Yields -5, the first negative.
Note: You can do this, of course, with filter and another line to test for zero length, or with reduce in one sort of weird line, but I always felt it was weird.
Sameer:
float l = new Float(x/y)
will not work, as it will compute integer division of x and y first, then construct a float from it.
float result = (float) x / (float) y;
Is semantically the best candidate.
That's something I'm not sure that you can change through the HTML of the webpage itself, it's a client-side setting to tell their browser if they want security to be high. Most other browsers will not do this but from what I'm aware of this is not possible to stop unless the user disables the feature.
Does it still do what you want it to do after you click on 'Allow'? If so then it shouldn't be too much of a problem
cvWaitKey(milliseconds)
simply wait for milliseconds provided as a parameter for a next key stroke of keyboard.
Human eyes not able to see the thing moving in less than 1/10 second, so we use this to hold same image frame for some time on screen. As soon as the key of keyboard is pressed the next operation will be perform.
In short cvWaitKey(milliseconds)
wait either for key press or millisecond
time provided.
if you are going to step down, then change your project's source to 1.7 as well,
right click on your Project -> Properties -> Sources window and set 1.7 here" Jigar Joshi
Also go to the build-impl.xml
and look for the property excludeFromCopy="${copylibs.excludes}"
and delete this property on my code was at line 827 but I`ve seen it on other lines
for me was taking a code from MAC OS java 1.8 to WIN XP java 1.7
I have done this using this method
save the id in some variable
var someVariable = document.getElementById("someId");
then use if condition
if(someVariable === ""){
//logic
} else if(someVariable !== ""){
//logic
}
I always used the FileSystemObject
for this sort of thing. Here's a little wrapper function I used. Be sure to reference the Microsoft Scripting Runtime
.
Function StripFilename(sPathFile As String) As String
'given a full path and file, strip the filename off the end and return the path
Dim filesystem As New FileSystemObject
StripFilename = filesystem.GetParentFolderName(sPathFile) & "\"
Exit Function
End Function
Artisan comes with Laravel by default, if your php
command works fine, then the only thing you need to do is to navigate to the project's root folder. The root folder is the parent folder of the app
folder. For example:
cd c:\Program Files\xampp\htdocs\your-project-name
Now the php artisan list
command should work fine, because PHP runs the file called artisan
in the project's folder.
Keep in mind that Artisan runs scripts stored in the vendor
folder, so if you installed Laravel without Composer, like downloading and extracting the Laravel GitHub repo, then you don't have the framework itself and you may get the following error when you try to use Artisan:
Could not open input file: artisan
To solve this you have to install the framework itself by running composer install
in your project's root folder.
If you're already using jQuery, you could try this:
$(window).bind("load", function() {
// code here
});
It's Unicode.
Just put the variable between str()
, and it will work fine.
But in case you have two lists like the following:
a = ['co32','co36']
b = [u'co32',u'co36']
If you check set(a)==set(b)
, it will come as False, but if you do as follows:
b = str(b)
set(a)==set(b)
Now, the result will be True.
You could wrapping the transaction over try..catch or even reverse them,
here my example code I used to in laravel 5,, if you look deep inside DB:transaction()
in Illuminate\Database\Connection
that the same like you write manual transaction.
Laravel Transaction
public function transaction(Closure $callback)
{
$this->beginTransaction();
try {
$result = $callback($this);
$this->commit();
}
catch (Exception $e) {
$this->rollBack();
throw $e;
} catch (Throwable $e) {
$this->rollBack();
throw $e;
}
return $result;
}
so you could write your code like this, and handle your exception like throw message back into your form via flash or redirect to another page. REMEMBER return inside closure is returned in transaction() so if you return redirect()->back()
it won't redirect immediately, because the it returned at variable which handle the transaction.
Wrap Transaction
$result = DB::transaction(function () use ($request, $message) {
try{
// execute query 1
// execute query 2
// ..
return redirect(route('account.article'));
} catch (\Exception $e) {
return redirect()->back()->withErrors(['error' => $e->getMessage()]);
}
});
// redirect the page
return $result;
then the alternative is throw boolean variable and handle redirect outside transaction function or if your need to retrieve why transaction failed you can get it from $e->getMessage()
inside catch(Exception $e){...}
$('#myDiv').hide();
hide function is used to edit content and show function is used to show again.
For more please click on this link.
Just type
gcc --version
in any terminal near you.. ;-)
In PHP.js, $_COOKIE is a function ;-)
function $_COOKIE(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return decodeURIComponent(c.substring(nameEQ.length,c.length).replace(/\+/g, '%20'));
}
return null;
}
You could use code like this:
if (n is IConvertible)
return ((IConvertible) n).ToDouble(CultureInfo.CurrentCulture);
else
// Cannot be converted.
If your object is an Int32
, Single
, Double
etc. it will perform the conversion. Also, a string implements IConvertible
but if the string isn't convertible to a double then a FormatException
will be thrown.
For Detecting hit on Polygon we need to test two things:
Right click on the folder where you put your main class then click on Build Path
--> Use as Source Folder
.
Finally run your main file as java application. Hope this problem will be solved.
There is also the approach of organizing the folders not by the structure of the framework, but by the structure of the application's function. There is a github starter Angular/Express application that illustrates this called angular-app.
This error can also happen if the server only sends its leaf certificate and does not send all the chain certificates needed to build the trust chain to the root CA. Unfortunately this is a common misconfiguration of servers.
Most browsers work around this problem if they already know the missing chain certificate from earlier visits or maybe download the missing certificate if the leaf certificate contains a URL for CA issuers in Authority Information Access (AIA). But this behavior is usually restricted to desktop browsers and other tools simply fail because they cannot build the trust chain.
You can make the JRE to automatically download the intermediate certificate by setting com.sun.security.enableAIAcaIssuers
to true
To verify if the server is sending all the chain certificates you can enter the host in the following SSL certificate validation tool https://www.digicert.com/help/
This has worked well for me to provide an escaped version of a text string:
public class XMLHelper {
/**
* Returns the string where all non-ascii and <, &, > are encoded as numeric entities. I.e. "<A & B >"
* .... (insert result here). The result is safe to include anywhere in a text field in an XML-string. If there was
* no characters to protect, the original string is returned.
*
* @param originalUnprotectedString
* original string which may contain characters either reserved in XML or with different representation
* in different encodings (like 8859-1 and UFT-8)
* @return
*/
public static String protectSpecialCharacters(String originalUnprotectedString) {
if (originalUnprotectedString == null) {
return null;
}
boolean anyCharactersProtected = false;
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < originalUnprotectedString.length(); i++) {
char ch = originalUnprotectedString.charAt(i);
boolean controlCharacter = ch < 32;
boolean unicodeButNotAscii = ch > 126;
boolean characterWithSpecialMeaningInXML = ch == '<' || ch == '&' || ch == '>';
if (characterWithSpecialMeaningInXML || unicodeButNotAscii || controlCharacter) {
stringBuffer.append("&#" + (int) ch + ";");
anyCharactersProtected = true;
} else {
stringBuffer.append(ch);
}
}
if (anyCharactersProtected == false) {
return originalUnprotectedString;
}
return stringBuffer.toString();
}
}
Use pprint: https://docs.python.org/3.6/library/pprint.html
import pprint
pprint.pprint(json)
print()
compared to pprint.pprint()
print(json)
{'feed': {'title': 'W3Schools Home Page', 'title_detail': {'type': 'text/plain', 'language': None, 'base': '', 'value': 'W3Schools Home Page'}, 'links': [{'rel': 'alternate', 'type': 'text/html', 'href': 'https://www.w3schools.com'}], 'link': 'https://www.w3schools.com', 'subtitle': 'Free web building tutorials', 'subtitle_detail': {'type': 'text/html', 'language': None, 'base': '', 'value': 'Free web building tutorials'}}, 'entries': [], 'bozo': 0, 'encoding': 'utf-8', 'version': 'rss20', 'namespaces': {}}
pprint.pprint(json)
{'bozo': 0,
'encoding': 'utf-8',
'entries': [],
'feed': {'link': 'https://www.w3schools.com',
'links': [{'href': 'https://www.w3schools.com',
'rel': 'alternate',
'type': 'text/html'}],
'subtitle': 'Free web building tutorials',
'subtitle_detail': {'base': '',
'language': None,
'type': 'text/html',
'value': 'Free web building tutorials'},
'title': 'W3Schools Home Page',
'title_detail': {'base': '',
'language': None,
'type': 'text/plain',
'value': 'W3Schools Home Page'}},
'namespaces': {},
'version': 'rss20'}
preg_split
if you need to split by regular expressions. str_split
if you need to split by characters. explode
if you need to split by something simple.Also for the future, if you ever want to know what PHP wants you to use if something is deprecated you can always check out the function in the manual and it will tell you alternatives.
Disclaimer: I'm a developer of Cytoscape.js
Cytoscape.js is a HTML5 graph visualisation library. The API is sophisticated and follows jQuery conventions, including
cy.elements("node[weight >= 50].someClass")
does much as you would expect),cy.nodes().unselect().trigger("mycustomevent")
),If you're thinking about building a serious webapp with graphs, you should at least consider Cytoscape.js. It's free and open-source:
use the android:background
attribute in your xml. Easiest way if you want to apply it to a whole activity is to put it in the root of your layout. So if you have a RelativeLayout as the start of your xml, put it in here:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rootRL"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/background">
</RelativeLayout>
str.split()
without any arguments splits on runs of whitespace characters:
>>> s = 'I am having a very nice day.'
>>>
>>> len(s.split())
7
From the linked documentation:
If sep is not specified or is
None
, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.
I'm assuming this is for a game or for a fast-responding type of application hence the use of KEYDOWN than KEYPRESS.
Edit: Dang! I stand corrected (thank you Crescent Fresh and David): JQuery (or even rather the underlying DOM hosts) do not expose the detail of the WM_KEYDOWN and of other events. Rather they pre-digest this data and, in the case of keyDown even in JQuery, we get:
Note that these properties are the UniCode values.
Note, I wasn't able to find an authorititative reference to that in JQuery docs, but many reputable examples on the net refer to these two properties.
The following code, adapted from some java (not javascript) of mine, is therefore totally wrong...
The following will give you the "interesting" parts of the keycode:
value = e.KeyCode;
repeatCount = value & 0xFF;
scanCode = (value >> 16) & 0xFF; // note we take the "extended bit" deal w/ it later.
wasDown = ((value & 0x4000) != 0); // indicate key was readily down (auto-repeat)
if (scanCode > 127)
// deal with extended
else
// "regular" character
Html code
<div id="coloredBy">
Colored By Santa
</div>
javascript code
document.getElementById("coloredBy").style.color = colorCode; // red or #ffffff
I think this is very easy to use
$('#mySelect')
.empty()
.append('<option selected="selected" value="whatever">text</option>')
;
Using MySql, the SqlFunctions.StringConvert
didn't work for me. Since I use SelectListItem
in 20+ places in my project, I wanted a solution that work without contorting the 20+ LINQ statements. My solution was to sub-class SelectedListItem
in order to provide an integer setter, which moves type conversion away from LINQ. Obviously, this solution is difficult to generalize, but was quite helpful for my specific project.
To use, create the following type and use in your LINQ query in place of SelectedListItem
and use IntValue in place of Value.
public class BtoSelectedListItem : SelectListItem
{
public int IntValue
{
get { return string.IsNullOrEmpty(Value) ? 0 : int.Parse(Value); }
set { Value = value.ToString(); }
}
}
Either one would work. It depends on your needs:
If your bean identifier contains special character(s) for example (/viewSummary.html
), it wont be allowed as the bean id
, because it's not a valid XML ID. In such cases you could skip defining the bean id
and supply the bean name
instead.
The name
attribute also helps in defining alias
es for your bean, since it allows specifying multiple identifiers for a given bean.
another option is to define Scanner input = new Scanner(System.in); inside the try block, this will create a new object each time you need to re-enter the values.
Run this command line on your preferred shell session:
db2 "select tabname from syscat.tables where owner = 'DB2INST1'"
Maybe you'd like to modify the owner name, and need to check the list of current owners?
db2 "select distinct owner from syscat.tables"
Another Regex based JSON parser (decode only)
Private Enum JsonStep
jsonString
jsonNumber
jsonTrue
jsonFalse
jsonNull
jsonOpeningBrace
jsonClosingBrace
jsonOpeningBracket
jsonClosingBracket
jsonComma
jsonColon
End Enum
Private regexp As Object
Private Function JsonStepName(ByVal json_step As JsonStep) As String
Select Case json_step
Case jsonString: JsonStepName = "'STRING'"
Case jsonNumber: JsonStepName = "'NUMBER'"
Case jsonTrue: JsonStepName = "true"
Case jsonFalse: JsonStepName = "false"
Case jsonNull: JsonStepName = "null"
Case jsonOpeningBrace: JsonStepName = "'{'"
Case jsonClosingBrace: JsonStepName = "'}'"
Case jsonOpeningBracket: JsonStepName = "'['"
Case jsonClosingBracket: JsonStepName = "']'"
Case jsonComma: JsonStepName = "','"
Case jsonColon: JsonStepName = "':'"
End Select
End Function
Private Function Unescape(ByVal str As String) As String
Dim match As Object
str = Replace$(str, "\""", """")
str = Replace$(str, "\\", "\")
str = Replace$(str, "\/", "/")
str = Replace$(str, "\b", vbBack)
str = Replace$(str, "\f", vbFormFeed)
str = Replace$(str, "\n", vbCrLf)
str = Replace$(str, "\r", vbCr)
str = Replace$(str, "\t", vbTab)
With regexp
.Global = True
.IgnoreCase = False
.MultiLine = False
.Pattern = "\\u([0-9a-fA-F]{4})"
For Each match In .Execute(str)
str = Replace$(str, match.value, ChrW$(Val("&H" + match.SubMatches(0))), match.FirstIndex + 1, 1)
Next match
End With
Unescape = str
End Function
Private Function ParseStep(ByVal str As String, _
ByRef index As Long, _
ByRef value As Variant, _
ByVal json_step As JsonStep, _
ByVal expected As Boolean) As Boolean
Dim match As Object
With regexp
.Global = False
.IgnoreCase = False
.MultiLine = False
Select Case json_step
'Case jsonString: .Pattern = "^\s*""(([^\\""]+|\\[""\\/bfnrt]|\\u[0-9a-fA-F]{4})*)""\s*"
Case jsonString: .Pattern = "^\s*""([^\\""]+|([^\\""]+|\\[""\\/bfnrt]|\\u[0-9a-fA-F]{4})*)""\s*"
Case jsonNumber: .Pattern = "^\s*(-?(0|[1-9]\d*)(\.\d+)?([eE][-+]?\d+)?)\s*"
Case jsonTrue: .Pattern = "^\s*(true)\s*"
Case jsonFalse: .Pattern = "^\s*(false)\s*"
Case jsonNull: .Pattern = "^\s*(null)\s*"
Case jsonOpeningBrace: .Pattern = "^\s*(\{)\s*"
Case jsonClosingBrace: .Pattern = "^\s*(\})\s*"
Case jsonOpeningBracket: .Pattern = "^\s*(\[)\s*"
Case jsonClosingBracket: .Pattern = "^\s*(\])\s*"
Case jsonComma: .Pattern = "^\s*(\,)\s*"
Case jsonColon: .Pattern = "^\s*(:)\s*"
End Select
Set match = .Execute(Mid$(str, index))
End With
If match.Count > 0 Then
index = index + match(0).Length
Select Case json_step
Case jsonString
If match(0).SubMatches(1) = Empty Then
value = match(0).SubMatches(0)
Else
value = Unescape(match(0).SubMatches(0))
End If
Case jsonNumber: value = Val(match(0).SubMatches(0))
Case jsonTrue: value = True
Case jsonFalse: value = False
Case jsonNull: value = Null
Case Else: value = Empty
End Select
ParseStep = True
ElseIf expected Then
Err.Raise 10001, "ParseJson", "Expecting " & JsonStepName(json_step) & " at char " & index & "."
End If
End Function
Private Function ParseValue(ByRef str As String, _
ByRef index As Long, _
ByRef value As Variant, _
ByVal expected As Boolean) As Boolean
ParseValue = True
If ParseStep(str, index, value, jsonString, False) Then Exit Function
If ParseStep(str, index, value, jsonNumber, False) Then Exit Function
If ParseObject(str, index, value, False) Then Exit Function
If ParseArray(str, index, value, False) Then Exit Function
If ParseStep(str, index, value, jsonTrue, False) Then Exit Function
If ParseStep(str, index, value, jsonFalse, False) Then Exit Function
If ParseStep(str, index, value, jsonNull, False) Then Exit Function
ParseValue = False
If expected Then
Err.Raise 10001, "ParseJson", "Expecting " & JsonStepName(jsonString) & ", " & JsonStepName(jsonNumber) & ", " & JsonStepName(jsonTrue) & ", " & JsonStepName(jsonFalse) & ", " & JsonStepName(jsonNull) & ", " & JsonStepName(jsonOpeningBrace) & ", or " & JsonStepName(jsonOpeningBracket) & " at char " & index & "."
End If
End Function
Private Function ParseObject(ByRef str As String, _
ByRef index As Long, _
ByRef obj As Variant, _
ByVal expected As Boolean) As Boolean
Dim key As Variant
Dim value As Variant
ParseObject = ParseStep(str, index, Empty, jsonOpeningBrace, expected)
If ParseObject Then
Set obj = CreateObject("Scripting.Dictionary")
If ParseStep(str, index, Empty, jsonClosingBrace, False) Then Exit Function
Do
If ParseStep(str, index, key, jsonString, True) Then
If ParseStep(str, index, Empty, jsonColon, True) Then
If ParseValue(str, index, value, True) Then
If IsObject(value) Then
Set obj.Item(key) = value
Else
obj.Item(key) = value
End If
End If
End If
End If
Loop While ParseStep(str, index, Empty, jsonComma, False)
ParseObject = ParseStep(str, index, Empty, jsonClosingBrace, True)
End If
End Function
Private Function ParseArray(ByRef str As String, _
ByRef index As Long, _
ByRef arr As Variant, _
ByVal expected As Boolean) As Boolean
Dim key As Variant
Dim value As Variant
ParseArray = ParseStep(str, index, Empty, jsonOpeningBracket, expected)
If ParseArray Then
Set arr = New Collection
If ParseStep(str, index, Empty, jsonClosingBracket, False) Then Exit Function
Do
If ParseValue(str, index, value, True) Then
arr.Add value
End If
Loop While ParseStep(str, index, Empty, jsonComma, False)
ParseArray = ParseStep(str, index, Empty, jsonClosingBracket, True)
End If
End Function
Public Function ParseJson(ByVal str As String) As Object
If regexp Is Nothing Then
Set regexp = CreateObject("VBScript.RegExp")
End If
If ParseObject(str, 1, ParseJson, False) Then Exit Function
If ParseArray(str, 1, ParseJson, False) Then Exit Function
Err.Raise 10001, "ParseJson", "Expecting " & JsonStepName(jsonOpeningBrace) & " or " & JsonStepName(jsonOpeningBracket) & "."
End Function
If your project does not use stdafx.h, you can put the following lines as the first lines in your .cpp file and the compiler warning should go away -- at least it did for me in Visual Studio C++ 2008.
#ifdef _CRT_SECURE_NO_WARNINGS
#undef _CRT_SECURE_NO_WARNINGS
#endif
#define _CRT_SECURE_NO_WARNINGS 1
It's ok to have comment and blank lines before them.
You can use
$window.scrollTo(x, y);
where x
is the pixel along the horizontal axis and y
is the pixel along the vertical axis.
Scroll to top
$window.scrollTo(0, 0);
Focus on element
$window.scrollTo(0, angular.element('put here your element').offsetTop);
Update:
Also you can use $anchorScroll
Sure can, sort of, thanks to the wonderful world of multiple classes, can do this:
.red {color:red}
.blackBack {background-color: black}
but I often end up combining them anyway like this:
.highlight {color:red, background-color: black}
I know the semantic police will be all over you, but it works.
They are completely equivalent when used with printf()
. Personally, I prefer %d
, it's used more often (should I say "it's the idiomatic conversion specifier for int
"?).
(One difference between %i
and %d
is that when used with scanf()
, then %d
always expects a decimal integer, whereas %i
recognizes the 0
and 0x
prefixes as octal and hexadecimal, but no sane programmer uses scanf()
anyway so this should not be a concern.)
For those having problems with AOT, you need to do it a little differently with a useFactory:
export function getCulture() {
return 'fr-CA';
}
@NgModule({
providers: [
{ provide: LOCALE_ID, useFactory: getCulture },
//otherProviders...
]
})
You can do this by casting the dict keys and values to list. It can also be be done for items.
Example:
f = {'one': 'police', 'two': 'oranges', 'three': 'car'}
list(f.keys())[0] = 'one'
list(f.keys())[1] = 'two'
list(f.values())[0] = 'police'
list(f.values())[1] = 'oranges'
The execution process is really confusing with recursive CTE, I found the best answer at https://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx and the abstract of the CTE execution process is as below.
The semantics of the recursive execution is as follows:
Microsoft SQL Server for instance, Schemas refer to a single user and is another level of a container in the order of indicating the server, database, schema, tables, and objects.
For example, when you are intending to update dbo.table_a and the syntax isn't full qualified such as UPDATE table.a the DBMS can't decide to use the intended table. Essentially by default the DBMS will utilize myuser.table_a
netstat -ano|grep 443|grep LISTEN
will tell you whether a process is listening on port 443 (you might have to replace LISTEN with a string in your language, though, depending on your system settings).
Increasing the timeout will not likely solve your issue since, as you say, the actual target web server is responding just fine.
I had this same issue and I found it had to do with not using a keep-alive on the connection. I can't actually answer why this is but, in clearing the connection header I solved this issue and the request was proxied just fine:
server {
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_pass http://localhost:5000;
}
}
Have a look at this posts which explains it in more detail: nginx close upstream connection after request Keep-alive header clarification http://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive
In order to calculate the difference you have to put the +
operator,
that way typescript
converts the dates to numbers.
+new Date()- +new Date("2013-02-20T12:01:04.753Z")
From there you can make a formula to convert the difference to minutes
or hours
.
I think this is actually what you're looking for:
.my_container ul
{
list-style: initial;
margin: initial;
padding: 0 0 0 40px;
}
.my_container li
{
display: list-item;
}
I like Calibri.
Even simpler:
=indirect(address(row(), column() - 1))
OFFSET returns a reference relative to the current reference, so if indirect returns the correct reference, you don't need it.
You can use any one of the below methods
If you are using java.text.DecimalFormat
DecimalFormat decimalFormat = NumberFormat.getCurrencyInstance();
decimalFormat.setMinimumFractionDigits(2);
System.out.println(decimalFormat.format(4.0));
OR
DecimalFormat decimalFormat = new DecimalFormat("#0.00");
System.out.println(decimalFormat.format(4.0));
If you want to convert it into simple string format
System.out.println(String.format("%.2f", 4.0));
All the above code will print 4.00
Math.random is bad for this kind of thing
Option 1
If you're able to do this server-side, just use the crypto module -
var crypto = require("crypto");
var id = crypto.randomBytes(20).toString('hex');
// "bb5dc8842ca31d4603d6aa11448d1654"
The resulting string will be twice as long as the random bytes you generate; each byte encoded to hex is 2 characters. 20 bytes will be 40 characters of hex.
Option 2
If you have to do this client-side, perhaps try the uuid module -
var uuid = require("uuid");
var id = uuid.v4();
// "110ec58a-a0f2-4ac4-8393-c866d813b8d1"
Option 3
If you have to do this client-side and you don't have to support old browsers, you can do it without dependencies -
// dec2hex :: Integer -> String
// i.e. 0-255 -> '00'-'ff'
function dec2hex (dec) {
return dec.toString(16).padStart(2, "0")
}
// generateId :: Integer -> String
function generateId (len) {
var arr = new Uint8Array((len || 40) / 2)
window.crypto.getRandomValues(arr)
return Array.from(arr, dec2hex).join('')
}
console.log(generateId())
// "82defcf324571e70b0521d79cce2bf3fffccd69"
console.log(generateId(20))
// "c1a050a4cd1556948d41"
_x000D_
For more information on crypto.getRandomValues
-
The
crypto.getRandomValues()
method lets you get cryptographically strong random values. The array given as the parameter is filled with random numbers (random in its cryptographic meaning).
Here's a little console example -
> var arr = new Uint8Array(4) # make array of 4 bytes (values 0-255)
> arr
Uint8Array(4) [ 0, 0, 0, 0 ]
> window.crypto
Crypto { subtle: SubtleCrypto }
> window.crypto.getRandomValues()
TypeError: Crypto.getRandomValues requires at least 1 argument, but only 0 were passed
> window.crypto.getRandomValues(arr)
Uint8Array(4) [ 235, 229, 94, 228 ]
For IE11 support you can use -
(window.crypto || window.msCrypto).getRandomValues(arr)
For browser coverage see https://caniuse.com/#feat=getrandomvalues
You have to allocate the buffer with mallock, and give the read write the pointer to it.
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(){
ssize_t nrd;
int fd;
int fd1;
char* buffer = malloc(100*sizeof(char));
fd = open("bli.txt", O_RDONLY);
fd1 = open("bla.txt", O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
while (nrd = read(fd,buffer,sizeof(buffer))) {
write(fd1,buffer,nrd);
}
close(fd);
close(fd1);
free(buffer);
return 0;
}
Make sure that the rad file exists and contains something. It's not perfect but it works.
Try:
select
id,
StartDate,
CASE WHEN StartDate IS NULL
THEN 'Awaiting'
ELSE 'Approved' END AS StartDateStatus
FROM myTable
You code would have been doing a When StartDate = NULL, I think.
NULL
is never equal to NULL
(as NULL is the absence of a value). NULL
is also never not equal to NULL
. The syntax noted above is ANSI SQL standard and the converse would be StartDate IS NOT NULL
.
You can run the following:
SELECT CASE WHEN (NULL = NULL) THEN 1 ELSE 0 END AS EqualityCheck,
CASE WHEN (NULL <> NULL) THEN 1 ELSE 0 END AS InEqualityCheck,
CASE WHEN (NULL IS NULL) THEN 1 ELSE 0 END AS NullComparison
And this returns:
EqualityCheck = 0
InEqualityCheck = 0
NullComparison = 1
For completeness, in SQL Server you can:
SET ANSI_NULLS OFF;
Which would result in your equals comparisons working differently:
SET ANSI_NULLS OFF
SELECT CASE WHEN (NULL = NULL) THEN 1 ELSE 0 END AS EqualityCheck,
CASE WHEN (NULL <> NULL) THEN 1 ELSE 0 END AS InEqualityCheck,
CASE WHEN (NULL IS NULL) THEN 1 ELSE 0 END AS NullComparison
Which returns:
EqualityCheck = 1
InEqualityCheck = 0
NullComparison = 1
But I would highly recommend against doing this. People subsequently maintaining your code might be compelled to hunt you down and hurt you...
Also, it will no longer work in upcoming versions of SQL server:
you can add infinite borders using box-shadow using css3 suppose you want to apply multiple borders on one div then code is like:
div {
border-radius: 4px;
/* #1 */
border: 5px solid hsl(0, 0%, 40%);
/* #2 */
padding: 5px;
background: hsl(0, 0%, 20%);
/* #3 */
outline: 5px solid hsl(0, 0%, 60%);
/* #4 AND INFINITY!!! (CSS3 only) */
box-shadow:
0 0 0 10px red,
0 0 0 15px orange,
0 0 0 20px yellow,
0 0 0 25px green,
0 0 0 30px blue;
}
Either of these 2:
NSString *subString = [dateString subStringWithRange:NSMakeRange(0,2)];
NSString *subString = [[dateString componentsSeparatedByString:@"/"] objectAtIndex:0];
Though keep in mind that sometimes a date string is not formatted properly and a day ( or a month for that matter ) is shown as 8, rather than 08 so the first one might be the worst of the 2 solutions.
The latter should be put into a separate array so you can actually check for the length of the thing returned, so you do not get any exceptions thrown in the case of a corrupt or invalid date string from whatever source you have.
This is what DocumentFragment
was meant for.
var frag = document.createDocumentFragment();
var span = document.createElement("span");
span.innerHTML = htmldata;
for (var i = 0, ii = span.childNodes.length; i < ii; i++) {
frag.appendChild(span.childNodes[i]);
}
element.appendChild(frag);
There are graph databases like:
A graph database stores data as nodes and relationships/edges.This is a good fit for semi-structured data, interconnected information and domains with deep relationships/traversal, for example social networks and knowledge representation. The data model is highly flexible and "whiteboard friendly". The underlying data model of the semantic web, RDF, is also a (labeled, directed multi-)graph.
Other stackoverflow threads with information on graph databases:
Difference between Abstraction and Encapsulation :-
Abstraction
Encapsulation
On VS2017 I installed the NuGet package: Microsoft.AspNet.WebPages
That did the trick.
you can also use: s.lower() in str.lower()
Normalizing your operational tables as suggested by Transact Charlie, is a good idea, and will save many headaches and problems over time - but there are such things as interface tables, which support integration with external systems, and reporting tables, which support things like analytical processing; and those types of tables should not necessarily be normalized - in fact, very often it is much, much more convenient and performant for them to not be.
In this case, I think Transact Charlie's proposal for your operational tables is a good one.
But I would add an index (not necessarily unique) to CompetitorName in the Competitors table to support efficient joins on CompetitorName for the purposes of integration (loading of data from external sources), and I would put an interface table into the mix: CompetitionResults.
CompetitionResults should contain whatever data your competition results have in it. The point of an interface table like this one is to make it as quick and easy as possible to truncate and reload it from an Excel sheet or a CSV file, or whatever form you have that data in.
That interface table should not be considered part of the normalized set of operational tables. Then you can join with CompetitionResults as suggested by Richard, to insert records into Competitors that don't already exist, and update the ones that do (for example if you actually have more information about competitors, like their phone number or email address).
One thing I would note - in reality, Competitor Name, it seems to me, is very unlikely to be unique in your data. In 200,000 competitors, you may very well have 2 or more David Smiths, for example. So I would recommend that you collect more information from competitors, such as their phone number or an email address, or something which is more likely to be unique.
Your operational table, Competitors, should just have one column for each data item that contributes to a composite natural key; for example it should have one column for a primary email address. But the interface table should have a slot for old and new values for a primary email address, so that the old value can be use to look up the record in Competitors and update that part of it to the new value.
So CompetitionResults should have some "old" and "new" fields - oldEmail, newEmail, oldPhone, newPhone, etc. That way you can form a composite key, in Competitors, from CompetitorName, Email, and Phone.
Then when you have some competition results, you can truncate and reload your CompetitionResults table from your excel sheet or whatever you have, and run a single, efficient insert to insert all the new competitors into the Competitors table, and single, efficient update to update all the information about the existing competitors from the CompetitionResults. And you can do a single insert to insert new rows into the CompetitionCompetitors table. These things can be done in a ProcessCompetitionResults stored procedure, which could be executed after loading the CompetitionResults table.
That's a sort of rudimentary description of what I've seen done over and over in the real world with Oracle Applications, SAP, PeopleSoft, and a laundry list of other enterprise software suites.
One last comment I'd make is one I've made before on SO: If you create a foreign key that insures that a Competitor exists in the Competitors table before you can add a row with that Competitor in it to CompetitionCompetitors, make sure that foreign key is set to cascade updates and deletes. That way if you need to delete a competitor, you can do it and all the rows associated with that competitor will get automatically deleted. Otherwise, by default, the foreign key will require you to delete all the related rows out of CompetitionCompetitors before it will let you delete a Competitor.
(Some people think non-cascading foreign keys are a good safety precaution, but my experience is that they're just a freaking pain in the butt that are more often than not simply a result of an oversight and they create a bunch of make work for DBA's. Dealing with people accidentally deleting stuff is why you have things like "are you sure" dialogs and various types of regular backups and redundant data sources. It's far, far more common to actually want to delete a competitor, whose data is all messed up for example, than it is to accidentally delete one and then go "Oh no! I didn't mean to do that! And now I don't have their competition results! Aaaahh!" The latter is certainly common enough, so, you do need to be prepared for it, but the former is far more common, so the easiest and best way to prepare for the former, imo, is to just make foreign keys cascade updates and deletes.)
I used this code and it works just fine
const int margin = 5;
Rectangle rect = new Rectangle(
Screen.PrimaryScreen.WorkingArea.X + margin,
Screen.PrimaryScreen.WorkingArea.Y + margin,
Screen.PrimaryScreen.WorkingArea.Width - 2 * margin,
Screen.PrimaryScreen.WorkingArea.Height - 2 * (margin - 7));
this.Bounds = rect;
I think that Steven is actually right. To answer the original question, then, in order to set up a class method, simply assume that the first argument is not going to be a calling instance, and then make sure that you only call the method from the class.
(Note that this answer refers to Python 3.x. In Python 2.x you'll get a TypeError
for calling the method on the class itself.)
For example:
class Dog:
count = 0 # this is a class variable
dogs = [] # this is a class variable
def __init__(self, name):
self.name = name #self.name is an instance variable
Dog.count += 1
Dog.dogs.append(name)
def bark(self, n): # this is an instance method
print("{} says: {}".format(self.name, "woof! " * n))
def rollCall(n): #this is implicitly a class method (see comments below)
print("There are {} dogs.".format(Dog.count))
if n >= len(Dog.dogs) or n < 0:
print("They are:")
for dog in Dog.dogs:
print(" {}".format(dog))
else:
print("The dog indexed at {} is {}.".format(n, Dog.dogs[n]))
fido = Dog("Fido")
fido.bark(3)
Dog.rollCall(-1)
rex = Dog("Rex")
Dog.rollCall(0)
In this code, the "rollCall" method assumes that the first argument is not an instance (as it would be if it were called by an instance instead of a class). As long as "rollCall" is called from the class rather than an instance, the code will work fine. If we try to call "rollCall" from an instance, e.g.:
rex.rollCall(-1)
however, it would cause an exception to be raised because it would send two arguments: itself and -1, and "rollCall" is only defined to accept one argument.
Incidentally, rex.rollCall() would send the correct number of arguments, but would also cause an exception to be raised because now n would be representing a Dog instance (i.e., rex) when the function expects n to be numerical.
This is where the decoration comes in: If we precede the "rollCall" method with
@staticmethod
then, by explicitly stating that the method is static, we can even call it from an instance. Now,
rex.rollCall(-1)
would work. The insertion of @staticmethod before a method definition, then, stops an instance from sending itself as an argument.
You can verify this by trying the following code with and without the @staticmethod line commented out.
class Dog:
count = 0 # this is a class variable
dogs = [] # this is a class variable
def __init__(self, name):
self.name = name #self.name is an instance variable
Dog.count += 1
Dog.dogs.append(name)
def bark(self, n): # this is an instance method
print("{} says: {}".format(self.name, "woof! " * n))
@staticmethod
def rollCall(n):
print("There are {} dogs.".format(Dog.count))
if n >= len(Dog.dogs) or n < 0:
print("They are:")
for dog in Dog.dogs:
print(" {}".format(dog))
else:
print("The dog indexed at {} is {}.".format(n, Dog.dogs[n]))
fido = Dog("Fido")
fido.bark(3)
Dog.rollCall(-1)
rex = Dog("Rex")
Dog.rollCall(0)
rex.rollCall(-1)
You can re-activate the actions by adding
this.delegateEvents(); // Re-activates the events for all the buttons
If you add it to the render function of a backbone js view, then you can use event.preventDefault() as required.
MEMORY USAGE key
command gives you the number of bytes that a key and its value require to be stored in RAM.
The reported usage is the total of memory allocations for data and administrative overheads that a key its value require (source redis documentation)
You need to open the file first. This doesn't work:
json_file = json.load('test.json')
But this works:
f = open('test.json')
json_file = json.load(f)
Another solution could be using jquery button selector inside the if else statement $("#buttonId").text("your text");
function showFilterItem() {
if (filterstatus == 0) {
filterstatus = 1;
$find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().showFilterItem();
$("#ShowButton").text("Hide Filter");
}
else {
filterstatus = 0;
$find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().hideFilterItem();
$("#ShowButton").text("Show Filter");
}}
For Java SE 5: According to Garbage Collector Ergonomics [Oracle]:
initial heap size:
Larger of 1/64th of the machine's physical memory on the machine or some reasonable minimum. Before J2SE 5.0, the default initial heap size was a reasonable minimum, which varies by platform. You can override this default using the -Xms command-line option.
maximum heap size:
Smaller of 1/4th of the physical memory or 1GB. Before J2SE 5.0, the default maximum heap size was 64MB. You can override this default using the -Xmx command-line option.
UPDATE:
As pointed out by Tom Anderson in his comment, the above is for server-class machines. From Ergonomics in the 5.0 JavaTM Virtual Machine:
In the J2SE platform version 5.0 a class of machine referred to as a server-class machine has been defined as a machine with
- 2 or more physical processors
- 2 or more Gbytes of physical memory
with the exception of 32 bit platforms running a version of the Windows operating system. On all other platforms the default values are the same as the default values for version 1.4.2.
In the J2SE platform version 1.4.2 by default the following selections were made
- initial heap size of 4 Mbyte
- maximum heap size of 64 Mbyte
Little more about XPath axes
Lets say we have below HTML
structure:
<div class="third_level_ancestor">
<nav class="second_level_ancestor">
<div class="parent">
<span>Child</span>
</div>
</nav>
</div>
//span/parent::*
- returns any element which is direct parent. In this case output is <div class="parent">
//span/parent::div[@class="parent"]
- returns parent element only of exact node type and only if specified predicate is True. Output: <div class="parent">
//span/ancestor::*
- returns all ancestors (including parent). Output: <div class="parent">
, <nav class="second_level_ancestor">
, <div class="third_level_ancestor">
...
//span/ancestor-or-self::*
- returns all ancestors and current element itself.Output: <span>Child</span>
, <div class="parent">
, <nav class="second_level_ancestor">
, <div class="third_level_ancestor">
...
//span/ancestor::div[2]
- returns second ancestor (starting from parent) of type div
. Output: <div class="third_level_ancestor">
Another approach(Inside of $function
to asure that the each
is executed on document ready
):
var ids = [1,2];
$(function(){
$('.checkbox-wrapper>input[type="checkbox"]').each(function(i,item){
if(ids.indexOf($(item).data('id')) > -1){
$(item).prop("checked", "checked");
}
});
});
What is the n.fn.init[0], and why it is returned? Why are my two seemingly identical JQuery functions returning different things?
Answer: It seems that your elements are not in the DOM yet, when you are trying to find them. As @Rory McCrossan pointed out, the
length:0
means that it doesn't find any element based on your search criteria.
n.fn.init[0]
, lets look at the core of the Jquery Library:var jQuery = function( selector, context ) {
return new jQuery.fn.init( selector, context );
};
Looks familiar, right?, now in a minified version of jquery, this should looks like:
var n = function( selector, context ) {
return new n.fn.init( selector, context );
};
So when you use a selector you are creating an instance of the jquery function; when found an element based on the selector criteria it returns the matched elements; when the criteria does not match anything it returns the prototype object of the function.
I think this will help you:
<?php
$date = new DateTime();
$match_date = new DateTime($timestamp);
$interval = $date->diff($match_date);
if($interval->days == 0) {
//Today
} elseif($interval->days == 1) {
if($interval->invert == 0) {
//Yesterday
} else {
//Tomorrow
}
} else {
//Sometime
}
MVVMC, or perhaps MVC+, seems to be a viable approach for enterprise as well as rapid application development. While it is nice to separate the UI from business and interaction logic, the 'pure' MVVM pattern and most available examples work best on singular views.
Not sure about your designs, but most of my applications, however, contain pages and several (reusable) views and thus the ViewModels do need to interact to some degree. Using the page as controller would defeat the purpose of the MVVM altogether, so not using a "VM-C" approach for the underlying logic might result in .. well .. challenging constructs as the application matures. Even in VB-6 most of us probably stopped coding business logic into the Button event and started 'relaying' commands to a controller, right? I recently looked at many emerging framworks on that topic; my favorite clearly is the Magellan (at codeplex) approach. Happy coding!
http://en.wikipedia.org/wiki/Model_View_ViewModel#References
Use start /w programname to wait for the end of programname
START /W notepad
ECHO Back from notepad
START /W wordpad
ECHO Back from wordpad
START /W notepad
The previous answers are all correct. I go one step further and make C# work for me by defining an extension method on String:
public static class Extensions
{
public static string[] Split(this string toSplit, string splitOn) {
return toSplit.Split(new string[] { splitOn }, StringSplitOptions.None);
}
}
That way I can call it on any string in the simple way I naively expected the first time I tried to accomplish this:
"a big long string with stuff to split on".Split("g str");
You can always do the following:
const SomeCall = request.get(res => {
const Store = [];
Store.push(res.data);
Store.forEach(item => { DoSomethingNeat
});
});
If you want to add a single view multiple time then you have to use
layoutInflaterForButton = getActivity().getLayoutInflater();
for (int noOfButton = 0; noOfButton < 5; noOfButton++) {
FrameLayout btnView = (FrameLayout) layoutInflaterForButton.inflate(R.layout.poll_button, null);
btnContainer.addView(btnView);
}
If you do like
layoutInflaterForButton = getActivity().getLayoutInflater();
FrameLayout btnView = (FrameLayout) layoutInflaterForButton.inflate(R.layout.poll_button, null);
and
for (int noOfButton = 0; noOfButton < 5; noOfButton++) {
btnContainer.addView(btnView);
}
then it will throw exception of all ready added view.
Have a go with these code:
>>> import pyexcel as pe
>>> sheet = pe.Sheet(data)
>>> data=[[1, 2], [2, 3], [4, 5]]
>>> sheet
Sheet Name: pyexcel
+---+---+
| 1 | 2 |
+---+---+
| 2 | 3 |
+---+---+
| 4 | 5 |
+---+---+
>>> sheet.save_as("one.csv")
>>> b = [[126, 125, 123, 122, 123, 125, 128, 127, 128, 129, 130, 130, 128, 126, 124, 126, 126, 128, 129, 130, 130, 130, 130, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 134, 134, 134, 134, 134, 134, 134, 134, 133, 134, 135, 134, 133, 133, 134, 135, 136], [135, 135, 136, 137, 137, 136, 134, 135, 135, 135, 134, 134, 133, 133, 133, 134, 134, 134, 133, 133, 132, 132, 132, 135, 135, 133, 133, 133, 133, 135, 135, 131, 135, 136, 134, 133, 136, 137, 136, 133, 134, 135, 136, 136, 135, 134, 133, 133, 134, 135, 136, 136, 136, 135, 134, 135, 138, 138, 135, 135, 138, 138, 135, 139], [137, 135, 136, 138, 139, 137, 135, 142, 139, 137, 139, 138, 136, 137, 141, 138, 138, 139, 139, 139, 139, 138, 138, 138, 138, 137, 137, 137, 137, 138, 138, 136, 137, 137, 137, 137, 137, 137, 138, 148, 144, 140, 138, 137, 138, 138, 138, 137, 137, 137, 137, 137, 138, 139, 140, 141, 141, 141, 141, 141, 141, 141, 141, 141], [141, 141, 141, 141, 141, 141, 141, 139, 139, 139, 140, 140, 141, 141, 141, 140, 140, 140, 140, 140, 141, 142, 143, 138, 138, 138, 139, 139, 140, 140, 140, 141, 140, 139, 139, 141, 141, 140, 139, 145, 137, 137, 145, 145, 137, 137, 144, 141, 139, 146, 134, 145, 140, 149, 144, 145, 142, 140, 141, 144, 145, 142, 139, 140]]
>>> s2 = pe.Sheet(b)
>>> s2
Sheet Name: pyexcel
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 126 | 125 | 123 | 122 | 123 | 125 | 128 | 127 | 128 | 129 | 130 | 130 | 128 | 126 | 124 | 126 | 126 | 128 | 129 | 130 | 130 | 130 | 130 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 134 | 134 | 134 | 134 | 134 | 134 | 134 | 134 | 133 | 134 | 135 | 134 | 133 | 133 | 134 | 135 | 136 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 135 | 135 | 136 | 137 | 137 | 136 | 134 | 135 | 135 | 135 | 134 | 134 | 133 | 133 | 133 | 134 | 134 | 134 | 133 | 133 | 132 | 132 | 132 | 135 | 135 | 133 | 133 | 133 | 133 | 135 | 135 | 131 | 135 | 136 | 134 | 133 | 136 | 137 | 136 | 133 | 134 | 135 | 136 | 136 | 135 | 134 | 133 | 133 | 134 | 135 | 136 | 136 | 136 | 135 | 134 | 135 | 138 | 138 | 135 | 135 | 138 | 138 | 135 | 139 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 137 | 135 | 136 | 138 | 139 | 137 | 135 | 142 | 139 | 137 | 139 | 138 | 136 | 137 | 141 | 138 | 138 | 139 | 139 | 139 | 139 | 138 | 138 | 138 | 138 | 137 | 137 | 137 | 137 | 138 | 138 | 136 | 137 | 137 | 137 | 137 | 137 | 137 | 138 | 148 | 144 | 140 | 138 | 137 | 138 | 138 | 138 | 137 | 137 | 137 | 137 | 137 | 138 | 139 | 140 | 141 | 141 | 141 | 141 | 141 | 141 | 141 | 141 | 141 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 141 | 141 | 141 | 141 | 141 | 141 | 141 | 139 | 139 | 139 | 140 | 140 | 141 | 141 | 141 | 140 | 140 | 140 | 140 | 140 | 141 | 142 | 143 | 138 | 138 | 138 | 139 | 139 | 140 | 140 | 140 | 141 | 140 | 139 | 139 | 141 | 141 | 140 | 139 | 145 | 137 | 137 | 145 | 145 | 137 | 137 | 144 | 141 | 139 | 146 | 134 | 145 | 140 | 149 | 144 | 145 | 142 | 140 | 141 | 144 | 145 | 142 | 139 | 140 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
>>> s2[0,0]
126
>>> s2.save_as("two.csv")
You should initialize yours recordings. You are passing to adapter null
ArrayList<String> recordings = null; //You are passing this null
According to official documentation, you can set or remove the "executable" flag on any tracked file using update-index
sub-command.
To set the flag, use following command:
git update-index --chmod=+x path/to/file
To remove it, use:
git update-index --chmod=-x path/to/file
Under the hood
While this looks like the regular unix files permission system, actually it is not. Git maintains a special "mode" for each file in its internal storage:
100644
for regular files100755
for executable onesYou can visualize it using ls-file
subcommand, with --stage
option:
$ git ls-files --stage
100644 aee89ef43dc3b0ec6a7c6228f742377692b50484 0 .gitignore
100755 0ac339497485f7cc80d988561807906b2fd56172 0 my_executable_script.sh
By default, when you add a file to a repository, Git will try to honor its filesystem attributes and set the correct filemode accordingly. You can disable this by setting core.fileMode
option to false:
git config core.fileMode false
Troubleshooting
If at some point the Git filemode is not set but the file has correct filesystem flag, try to remove mode and set it again:
git update-index --chmod=-x path/to/file
git update-index --chmod=+x path/to/file
Bonus
Starting with Git 2.9, you can stage a file AND set the flag in one command:
git add --chmod=+x path/to/file
As I understand it, the selected answer still loads all of the related tests. According to this msdn blog, there is a better way.
Specifically
using (var context = new UnicornsContext())
var princess = context.Princesses.Find(1);
// Count how many unicorns the princess owns
var unicornHaul = context.Entry(princess)
.Collection(p => p.Unicorns)
.Query()
.Count();
}
catch
is called except
in Python. other than that it's fine for such simple cases. There's the AttributeError
that can be used to check if an object has an attribute.
Use this statement for getting month name:
DECLARE @date datetime
SET @date='2015/1/4 00:00:00'
SELECT CAST(DATENAME(month,@date ) AS CHAR(3))AS 'Month Name'
This will give you short month name. Like this: Jan, Feb, Mar, etc.
Also, you can use Formo:
Configuration:
<appSettings>
<add key="RetryAttempts" value="5" />
<add key="ApplicationBuildDate" value="11/4/1999 6:23 AM" />
</appSettings>
Code:
dynamic config = new Configuration();
var retryAttempts1 = config.RetryAttempts; // Returns 5 as a string
var retryAttempts2 = config.RetryAttempts(10); // Returns 5 if found in config, else 10
var retryAttempts3 = config.RetryAttempts(userInput, 10); // Returns 5 if it exists in config, else userInput if not null, else 10
var appBuildDate = config.ApplicationBuildDate<DateTime>();
At least up to and including CSS 3 you cannot select like that. But it can be done pretty easily nowadays in JavaScript, you just need to add a bit of vanilla JavaScript, notice that the code is pretty short.
cells = document.querySelectorAll('div');_x000D_
[].forEach.call(cells, function (el) {_x000D_
//console.log(el.nodeName)_x000D_
if (el.hasChildNodes() && el.firstChild.nodeName=="A") {_x000D_
console.log(el)_x000D_
};_x000D_
});
_x000D_
<div>Peter</div>_x000D_
<div><a href="#">Jackson link</a></div>_x000D_
<div>Philip</div>_x000D_
<div><a href="#">Pullman link</a></div>
_x000D_
Reading a CSV file in very simple and common in Java. You actually don't require to load any extra third party library to do this for you. CSV (comma separated value) file is just a normal plain-text file, store data in column by column, and split it by a separator (e.g comma ",").
In order to read specific columns from the CSV file, there are several ways. Simplest of all is as below:
Code to read CSV without any 3rd party library
BufferedReader br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] cols = line.split(cvsSplitBy);
System.out.println("Coulmn 4= " + cols[4] + " , Column 5=" + cols[5]);
}
If you notice, nothing special is performed here. It is just reading a text file, and spitting it by a separator – ",".
Consider an extract from legacy country CSV data at GeoLite Free Downloadable Databases
"1.0.0.0","1.0.0.255","16777216","16777471","AU","Australia"
"1.0.1.0","1.0.3.255","16777472","16778239","CN","China"
"1.0.4.0","1.0.7.255","16778240","16779263","AU","Australia"
"1.0.8.0","1.0.15.255","16779264","16781311","CN","China"
"1.0.16.0","1.0.31.255","16781312","16785407","JP","Japan"
"1.0.32.0","1.0.63.255","16785408","16793599","CN","China"
"1.0.64.0","1.0.127.255","16793600","16809983","JP","Japan"
"1.0.128.0","1.0.255.255","16809984","16842751","TH","Thailand"
Above code will output as below:
Column 4= "AU" , Column 5="Australia"
Column 4= "CN" , Column 5="China"
Column 4= "AU" , Column 5="Australia"
Column 4= "CN" , Column 5="China"
Column 4= "JP" , Column 5="Japan"
Column 4= "CN" , Column 5="China"
Column 4= "JP" , Column 5="Japan"
Column 4= "TH" , Column 5="Thailand"
You can, in fact, put
the columns in a Map
and then get the values simply by using the key
.
Shishir
Disable selection everywhere
input, textarea ,*[contenteditable=true] {
-webkit-touch-callout:default;
-webkit-user-select:text;
-moz-user-select:text;
-ms-user-select:text;
user-select:text;
}
IE7
<BODY oncontextmenu="return false" onselectstart="return false" ondragstart="return false">
If the value
returned is null, use:
if(value.isEmpty());
Sometime to check null, if(value == null)
in java, it might not give true even the String is null.
The Answer by Bhesh Gurung is correct… unless your NetBeans project is Maven based.
Under Maven, you add a "dependency". A dependency is a description of a library (its name & version number) you want to use from your code.
Or a dependency could be a description of a library which another library needs ("depends on"). Maven automatically handles this chain, libraries that need other libraries that then need other libraries and so on. For the mathematical-minded, perhaps the phrase "Maven resolves the transitive dependencies" makes sense.
Maven gets this related-ness information, and the libraries themselves from a Maven repository. A repository is basically an online database and collection of download files (the dependency library).
Adding a dependency to a Maven-based project is really quite easy. That is the whole point to Maven, to make managing dependent libraries easy and to make building them into your project easy. To get started with adding a dependency, see this Question, Adding dependencies in Maven Netbeans and my Answer with screenshot.
This should do the trick:
$('#thisElement').find('.classToSelect')
This is available on linux: pidof keyword
The problem is you either haven't closed your if
or you need an elseif
:
create procedure checando(
in nombrecillo varchar(30),
in contrilla varchar(30),
out resultado int)
begin
if exists (select * from compas where nombre = nombrecillo and contrasenia = contrilla) then
set resultado = 0;
elseif exists (select * from compas where nombre = nombrecillo) then
set resultado = -1;
else
set resultado = -2;
end if;
end;
All of these answers ignore the easiest and quickest way to do this (as long as you have Bash 4):
if [ "${var1,,}" = "${var2,,}" ]; then
echo ":)"
fi
All you're doing there is converting both strings to lowercase and comparing the results.
Aside from the excellent and complete answer from ridgerunner, I thought of a very simple workaround for when your backend runs PHP.
Add this PHP file to your domain's backend (say: csv.php
)
<?php
session_start(); // Optional
header("content-type: text/xml");
header("charset=UTF-8");
// Set the delimiter and the End of Line character of your CSV content:
echo json_encode(array_map('str_getcsv', str_getcsv($_POST["csv"], "\n")));
?>
Now add this function to your JavaScript toolkit (should be revised a bit to make crossbrowser I believe).
function csvToArray(csv) {
var oXhr = new XMLHttpRequest;
oXhr.addEventListener("readystatechange",
function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
console.log(JSON.parse(this.responseText));
}
}
);
oXhr.open("POST","path/to/csv.php",true);
oXhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
oXhr.send("csv=" + encodeURIComponent(csv));
}
It will cost you one Ajax call, but at least you won't duplicate code nor include any external library.
jQuery's attr
method returns the value of the attribute:
The
.attr()
method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping construct such as jQuery's.each()
or.map()
method.
All you need is:
$('html').attr('lang') == 'fr-FR'
However, you might want to do a case-insensitive match:
$('html').attr('lang').toLowerCase() === 'fr-fr'
jQuery's val
method returns the value of a form element.
The
.val()
method is primarily used to get the values of form elements such asinput
,select
andtextarea
. In the case of<select multiple="multiple">
elements, the.val()
method returns an array containing each selected option; if no option is selected, it returnsnull
.
You could also use POSIX regular expressions, like
SELECT id FROM groups where name ~* 'administrator'
SELECT 'asd' ~* 'AsD'
returns t
try this
http://www.ehow.com/how_6613143_convert-xml-code-sql.html
for downloading the tool http://www.xml-converter.com/
This code splits lines from text, and add everyone into a vector.
vector<string> split(char *phrase, string delimiter){
vector<string> list;
string s = string(phrase);
size_t pos = 0;
string token;
while ((pos = s.find(delimiter)) != string::npos) {
token = s.substr(0, pos);
list.push_back(token);
s.erase(0, pos + delimiter.length());
}
list.push_back(s);
return list;
}
Called by:
vector<string> listFilesMax = split(buffer, "\n");
The solution for me on a CentOS 8 system was checking the System Cryptography Policy by verifying the /etc/crypto-policies/config reads the default value of DEFAULT rather than any other value.
Once changing this value to DEFAULT, run the following command:
/usr/bin/update-crypto-policies --set DEFAULT
Rerun the curl command and it should work.
If the question is how to convert an integer itself (not its string equivalent) into bytes, I think the robust answer is:
>>> i = 5
>>> i.to_bytes(2, 'big')
b'\x00\x05'
>>> int.from_bytes(i.to_bytes(2, 'big'), byteorder='big')
5
More information on these methods here:
If you have a container and two sub containers, you can do like this
jQuery
$("#previousbutton").click(function() {
$("#form_sub_container1").show();
$("#form_sub_container2").hide(); })
$("#nextbutton").click(function() {
$("#form_container").find(":hidden").show().next();
$("#form_sub_container1").hide();
})
HTML
<div id="form_container">
<div id="form_sub_container1" style="display: block;">
</div>
<div id="form_sub_container2" style="display: none;">
</div>
</div>
From the documentation page
To set the page type pass the value in constructor
jsPDF(orientation, unit, format)
Creates new jsPDF document objectinstance Parameters:
orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")
unit Measurement unit to be used when coordinates are specified. One of "pt" (points), "mm" (Default), "cm", "in"
format One of 'a3', 'a4' (Default),'a5' ,'letter' ,'legal'
To set font size
setFontSize(size)
Sets font size for upcoming text elements.
Parameters:
{Number} size Font size in points.
Modern answer since keyCode is now deprecated in favor of key:
document.onkeydown = function (e) {
switch (e.key) {
case 'ArrowUp':
// up arrow
break;
case 'ArrowDown':
// down arrow
break;
case 'ArrowLeft':
// left arrow
break;
case 'ArrowRight':
// right arrow
}
};
.unbind()
is deprecated and you should use the .off()
method instead. Simply call .off()
right before you call .on()
.
This will remove all event handlers:
$(element).off().on('click', function() {
// function body
});
To only remove registered 'click' event handlers:
$(element).off('click').on('click', function() {
// function body
});
The following tools works great for me:
Provide a convenience UI to with feature like source, style, DOM, Script, HTML check. It also show the actual error in your JS file (which line, which file).
2) http://www.my-debugbar.com/wiki/CompanionJS/Installing
Provide a console for IE6 or IE7 ( which originally does not support)
update as you loading contents dynamically so you use.
$(document).on('click', 'span', function () {
alert(this.id);
});
old code
$('span').click(function(){
alert(this.id);
});
or you can use .on
$('span').on('click', function () {
alert(this.id);
});
this
refers to current span element clicked
this.id
will give the id
of the current span clicked
I think I've made a simple way to notify of data set changes:
First, change a bit the way the instantiateItem function works:
@Override
public Object instantiateItem(final ViewGroup container, final int position) {
final View rootView = mInflater.inflate(...,container, false);
rootView.setTag(position);
updateView(rootView, position);
container.addView(rootView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
mViewPager.setObjectForPosition(rootView, position);
return rootView;
}
for "updateView" , fill the view with all the data you wish to fill (setText,setBitmapImage,...) .
verify that destroyView works like this:
@Override
public void destroyItem(final ViewGroup container, final int position, final Object obj) {
final View viewToRemove = (View) obj;
mViewPager.removeView(viewToRemove);
}
Now, suppose you need to change the data, do it, and then call the next function on the PagerAdapter :
public void notifyDataSetChanged(final ViewPager viewPager, final NotifyLocation fromPos,
final NotifyLocation toPos) {
final int offscreenPageLimit = viewPager.getOffscreenPageLimit();
final int fromPosInt = fromPos == NotifyLocation.CENTER ? mSelectedPhotoIndex
: fromPos == NotifyLocation.MOST_LEFT ? mSelectedPhotoIndex - offscreenPageLimit
: mSelectedPhotoIndex + offscreenPageLimit;
final int toPosInt = toPos == NotifyLocation.CENTER ? mSelectedPhotoIndex
: toPos == NotifyLocation.MOST_LEFT ? mSelectedPhotoIndex - offscreenPageLimit
: mSelectedPhotoIndex + offscreenPageLimit;
if (fromPosInt <= toPosInt) {
notifyDataSetChanged();
for (int i = fromPosInt; i <= toPosInt; ++i) {
final View pageView = viewPager.findViewWithTag(i);
mPagerAdapter.updateView(pageView, i);
}
}
}
public enum NotifyLocation {
MOST_LEFT, CENTER, MOST_RIGHT
}
For example if you wish to notify all of the views that are being shown by the viewPager that something has changed, you can call:
notifyDataSetChanged(mViewPager,NotifyLocation.MOST_LEFT,NotifyLocation.MOST_RIGHT);
That's it.
SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('FUNCTION','PROCEDURE','PACKAGE')
The column STATUS tells you whether the object is VALID or INVALID. If it is invalid, you have to try a recompile, ORACLE can't tell you if it will work before.
OP: "I would love if there were a way to do it where I didn't have to know the host address..."
response.writeHead(301, {
Location: "http" + (request.socket.encrypted ? "s" : "") + "://" +
request.headers.host + newRoom
});
response.end();
In this example, you are extending the React.Component
class, and per the ES2015 spec, a child class constructor cannot make use of this
until super()
has been called; also, ES2015 class constructors have to call super()
if they are subclasses.
class MyComponent extends React.Component {
constructor() {
console.log(this); // Reference Error
}
render() {
return <div>Hello {this.props.name}</div>;
}
}
By contrast:
class MyComponent extends React.Component {
constructor() {
super();
console.log(this); // this logged to console
}
render() {
return <div>Hello {this.props.name}</div>;
}
}
More detail as per this excellent stack overflow answer
You may see examples of components created by extending the React.Component
class that do not call super()
but you'll notice these don't have a constructor
, hence why it is not necessary.
class MyOtherComponent extends React.Component {
render() {
return <div>Hi {this.props.name}</div>;
}
}
One point of confusion I've seen from some developers I've spoken to is that the components that have no constructor
and therefore do not call super()
anywhere, still have this.props
available in the render()
method. Remember that this rule and this need to create a this
binding for the constructor
only applies to the constructor
.
Method 1: Put maps in a List and then join
public class Test15 {
public static void main(String[] args) {
Map<String, List<String>> map1 = new HashMap<>();
map1.put("London", Arrays.asList("A", "B", "C"));
map1.put("Wales", Arrays.asList("P1", "P2", "P3"));
Map<String, List<String>> map2 = new HashMap<>();
map2.put("Calcutta", Arrays.asList("Protijayi", "Gina", "Gini"));
map2.put("London", Arrays.asList( "P4", "P5", "P6"));
map2.put("Wales", Arrays.asList( "P111", "P5555", "P677666"));
System.out.println(map1);System.out.println(map2);
// put the maps in an ArrayList
List<Map<String, List<String>>> maplist = new ArrayList<Map<String,List<String>>>();
maplist.add(map1);
maplist.add(map2);
/*
<T,K,U> Collector<T,?,Map<K,U>> toMap(
Function<? super T,? extends K> keyMapper,
Function<? super T,? extends U> valueMapper,
BinaryOperator<U> mergeFunction)
*/
Map<String, List<String>> collect = maplist.stream()
.flatMap(ch -> ch.entrySet().stream())
.collect(
Collectors.toMap(
//keyMapper,
Entry::getKey,
//valueMapper
Entry::getValue,
// mergeFunction
(list_a,list_b) -> Stream.concat(list_a.stream(), list_b.stream()).collect(Collectors.toList())
));
System.out.println("Final Result(Map after join) => " + collect);
/*
{Wales=[P1, P2, P3], London=[A, B, C]}
{Calcutta=[Protijayi, Gina, Gini], Wales=[P111, P5555, P677666], London=[P4, P5, P6]}
Final Result(Map after join) => {Calcutta=[Protijayi, Gina, Gini], Wales=[P1, P2, P3, P111, P5555, P677666], London=[A, B, C, P4, P5, P6]}
*/
}//main
}
Method 2 : Normal Map merge
public class Test15 {
public static void main(String[] args) {
Map<String, List<String>> map1 = new HashMap<>();
map1.put("London", Arrays.asList("A", "B", "C"));
map1.put("Wales", Arrays.asList("P1", "P2", "P3"));
Map<String, List<String>> map2 = new HashMap<>();
map2.put("Calcutta", Arrays.asList("Protijayi", "Gina", "Gini"));
map2.put("London", Arrays.asList( "P4", "P5", "P6"));
map2.put("Wales", Arrays.asList( "P111", "P5555", "P677666"));
System.out.println(map1);System.out.println(map2);
/*
<T,K,U> Collector<T,?,Map<K,U>> toMap(
Function<? super T,? extends K> keyMapper,
Function<? super T,? extends U> valueMapper,
BinaryOperator<U> mergeFunction)
*/
Map<String, List<String>> collect = Stream.of(map1,map2)
.flatMap(ch -> ch.entrySet().stream())
.collect(
Collectors.toMap(
//keyMapper,
Entry::getKey,
//valueMapper
Entry::getValue,
// mergeFunction
(list_a,list_b) -> Stream.concat(list_a.stream(), list_b.stream()).collect(Collectors.toList())
));
System.out.println("Final Result(Map after join) => " + collect);
/*
{Wales=[P1, P2, P3], London=[A, B, C]}
{Calcutta=[Protijayi, Gina, Gini], Wales=[P111, P5555, P677666], London=[P4, P5, P6]}
Final Result(Map after join) => {Calcutta=[Protijayi, Gina, Gini], Wales=[P1, P2, P3, P111, P5555, P677666], London=[A, B, C, P4, P5, P6]}
*/
}//main
}
In Python, HashMap is called Dictionary and we can merge them very easily.
x = {'Roopa': 1, 'Tabu': 2}
y = {'Roopi': 3, 'Soudipta': 4}
z = {**x,**y}
print(z)
{'Roopa': 1, 'Tabu': 2, 'Roopi': 3, 'Soudipta': 4}
python -m pip install Pillow
Will use pip of current Python activated with
source activate shrink_venv
Encode or decode byte arrays:
byte[] encoded = Base64.getEncoder().encode("Hello".getBytes());
println(new String(encoded)); // Outputs "SGVsbG8="
byte[] decoded = Base64.getDecoder().decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
String encoded = Base64.getEncoder().encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(Base64.getDecoder().decode(encoded.getBytes()));
println(decoded) // Outputs "Hello"
For more info, see Base64.
Base64 is not bundled with Java versions less than 8. I recommend using Apache Commons Codec.
For direct byte arrays:
Base64 codec = new Base64();
byte[] encoded = codec.encode("Hello".getBytes());
println(new String(encoded)); // Outputs "SGVsbG8="
byte[] decoded = codec.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
Base64 codec = new Base64();
String encoded = codec.encodeBase64String("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(codec.decodeBase64(encoded));
println(decoded) // Outputs "Hello"
If you're working in a Spring project already, you may find their org.springframework.util.Base64Utils
class more ergonomic:
For direct byte arrays:
byte[] encoded = Base64Utils.encode("Hello".getBytes());
println(new String(encoded)) // Outputs "SGVsbG8="
byte[] decoded = Base64Utils.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
String encoded = Base64Utils.encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = Base64Utils.decodeFromString(encoded);
println(new String(decoded)) // Outputs "Hello"
If you are using the Android SDK before Java 8 then your best option is to use the bundled android.util.Base64
.
For direct byte arrays:
byte[] encoded = Base64.encode("Hello".getBytes());
println(new String(encoded)) // Outputs "SGVsbG8="
byte [] decoded = Base64.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
String encoded = Base64.encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(Base64.decode(encoded));
println(decoded) // Outputs "Hello"
It does not work because sequence does not work in following scenarios:
Source: http://www.orafaq.com/wiki/ORA-02287
However this does work:
insert into table_name
(col1, col2)
select my_seq.nextval, inner_view.*
from (select 'some value' someval
from dual
union all
select 'another value' someval
from dual) inner_view;
Try it out:
create table table_name(col1 varchar2(100), col2 varchar2(100));
create sequence vcert.my_seq
start with 1
increment by 1
minvalue 0;
select * from table_name;
(OK, I know you are asking for shrink-wrap, but maybe those home-grown solutions just weren't succinct enough for your liking. :-)
pdf = [(1, 0.1), (2, 0.05), (3, 0.05), (4, 0.2), (5, 0.4), (6, 0.2)]
cdf = [(i, sum(p for j,p in pdf if j < i)) for i,_ in pdf]
R = max(i for r in [random.random()] for i,c in cdf if c <= r)
I pseudo-confirmed that this works by eyeballing the output of this expression:
sorted(max(i for r in [random.random()] for i,c in cdf if c <= r)
for _ in range(1000))
This may be interesting for ppl using Primefaces (which uses CLEditor):
document.getElementById('form:somecontainer:editor')
.getElementsByTagName('iframe')[0].contentWindow
.document.onclick = function(){//do something}
I basically just took the answer from Travelling Tech Guy and changed the selection a bit .. ;)
Concatenate the string separating the slash and the word script in this way.
Response.Write("<script language='javascript'>alert('Especifique Usuario y Contraseña');</" + "script>");
Some times you may make silly mistakes like writing insert query on the same .sql file (in the same workspace/tab) so once you execute the insert query where your create query was written just above and already executed, it will again start executing along with the insert query.
This is the reason why we are getting the object name (table name) exists already, since it's getting executed for the second time.
So go to a separate tab to write the insert or drop or whatever queries you are about to execute.
Or else use comment lines preceding all queries in the same workspace like
CREATE -- …
-- Insert query
INSERT INTO -- …
"
is on the official list of valid HTML 4 entities, but '
is not.
From C.16. The Named Character Reference ':
The named character reference
'
(the apostrophe, U+0027) was introduced in XML 1.0 but does not appear in HTML. Authors should therefore use'
instead of'
to work as expected in HTML 4 user agents.
Works for every binary, not only java:
file - < $(which java) # heavyly bashic
cat `which java` | file - # universal
You need to add in the seconds, too:
unsigned long time_in_micros = 1000000 * tv.tv_sec + tv.tv_usec;
Note that this will only last for about 232/106 =~ 4295 seconds, or roughly 71 minutes though (on a typical 32-bit system).
To produce patch for several commits, you should use format-patch
git command, e.g.
git format-patch -k --stdout R1..R2
This will export your commits into patch file in mailbox format.
To generate patch for the last commit, run:
git format-patch -k --stdout HEAD^
Then in another repository apply the patch by am
git command, e.g.
git am -3 -k file.patch
See: man git-format-patch
and git-am
.
I will just repeat what @Ivo Bosticky said which can be overlooked. Put these lines at the VERY start of the py file.
import matplotlib
matplotlib.use('Agg')
Or one would get error
*/usr/lib/pymodules/python2.7/matplotlib/__init__.py:923: UserWarning: This call to matplotlib.use() has no effect because the the backend has already been chosen; matplotlib.use() must be called *before* pylab, matplotlib.pyplot,*
This will resolve all Display issue
If you want to keep the heredoc indented for readability:
$ perl -pe 's/^\s*//' << EOF
line 1
line 2
EOF
The built-in method for supporting indented heredoc in Bash only supports leading tabs, not spaces.
Perl can be replaced with awk to save a few characters, but the Perl one is probably easier to remember if you know basic regular expressions.
Thanks HansUp for your answer, it is very helpful and it works!
I found three patterns working in Access, yours is the best, because it works in all cases.
INNER JOIN, your variant. I will call it "closed set pattern". It is possible to join more than two tables to the same table with good performance only with this pattern.
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM
((class
INNER JOIN person AS cr
ON class.C_P_ClassRep=cr.P_Nr
)
INNER JOIN person AS cr2
ON class.C_P_ClassRep2nd=cr2.P_Nr
)
;
INNER JOIN "chained-set pattern"
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM person AS cr
INNER JOIN ( class
INNER JOIN ( person AS cr2
) ON class.C_P_ClassRep2nd=cr2.P_Nr
) ON class.C_P_ClassRep=cr.P_Nr
;
CROSS JOIN with WHERE
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM class, person AS cr, person AS cr2
WHERE class.C_P_ClassRep=cr.P_Nr AND class.C_P_ClassRep2nd=cr2.P_Nr
;
Mac OS X doesn't store the path in .bash_profile, but .profile, since Mac OS X is a branch of *BSD family. You should be able to see the export blah blah blah in .profile once you do cat .profile on your terminal.
Tomcat usually does not add classes in src/test/java
to the classpath. They are missing if you run tomcat in scope test. To order tomcat to respect classes in test, use -Dmaven.tomcat.useTestClasspath=true
or add
<properties>
<maven.tomcat.useTestClasspath>true</maven.tomcat.useTestClasspath>
</properties>
To your pom.xml
.
Try the following:
INSERT INTO table1
SELECT 'A string', 5, idTable2 idTable2 FROM table2 WHERE ...
Do you mean like this?
>>> mystring = "This isn't the right place to have \"'\" (single quotes)"
>>> mystring
'This isn\'t the right place to have "\'" (single quotes)'
>>> newstring = mystring.replace("'", "")
>>> newstring
'This isnt the right place to have "" (single quotes)'
For the sake of others who are wondering on how to get to this window. Here's how:
You can access this by clicking on Select Run/Debug Configurations
(to the left of ) and going to the Edit Configurations
. A
gif provided for clarity.
int result_num;
bool flag;
cout << "Number Divisors\n";
for (int number = 1; number <= 35; number++)
{
flag = false;
cout << setw(3) << number << setw(14);
for (int i = 1; i <= number; i++)
{
result_num = number % i;
if (result_num == 0 && flag == true)
{
cout << "," << i;
}
if (result_num == 0 && flag == false)
{
cout << i;
}
flag = true;
}
cout << endl;
}
cout << "Press enter to continue.....";
cin.ignore();
return 0;
}
Before going offline you have to make sure that everything is in your local repo, which is required while working offline. Running "mvn dependency:go-offline" for the project(s)/pom(s), you intend to work on, will reduce the efforts to achieve this.
But it´s usually not the whole story, because dependency:go-offline will only download the "bare build" plugins (go-offline / resolve-plugins does not resolve all plugin dependencies). So you have to find a way to download deploy / test / site plugins (and maybe others) and their dependencies into your repo.
Furthermore dependency:go-offline does not download the pom´s artifact itself, so you have to dependency:copy it if required.
Sometimes - as MaDa wrote - you do not know, what you will need, while being offline, which makes it pretty impossible to have a "sufficient" repo.
Anyway having a properly filled repo you only have to add "<offline>true</offline>" to Maven´s settings.xml to go offline.
Do not change the Maven profile (id) you used to fill your repo, while being offline. Maven recognizes the downloaded artifacts in its metadata with an "identity", which is bound to the profile id.
A slight more difficult answer that uses ControlTemplate and has an animation effect (adapted from https://docs.microsoft.com/en-us/dotnet/framework/wpf/controls/customizing-the-appearance-of-an-existing-control)
In your resource dictionary define a control template for your button like this one:
<ControlTemplate TargetType="Button" x:Key="testButtonTemplate2">
<Border Name="RootElement">
<Border.Background>
<SolidColorBrush x:Name="BorderBrush" Color="Black"/>
</Border.Background>
<Grid Margin="4" >
<Grid.Background>
<SolidColorBrush x:Name="ButtonBackground" Color="Aquamarine"/>
</Grid.Background>
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Margin="4,5,4,4"/>
</Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="MouseOver">
<Storyboard>
<ColorAnimation Storyboard.TargetName="ButtonBackground" Storyboard.TargetProperty="Color" To="Red"/>
</Storyboard>
</VisualState>
<VisualState x:Name="Pressed">
<Storyboard>
<ColorAnimation Storyboard.TargetName="ButtonBackground" Storyboard.TargetProperty="Color" To="Red"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Border>
</ControlTemplate>
in your XAML you can use the template above for your button as below:
Define your button
<Button Template="{StaticResource testButtonTemplate2}"
HorizontalAlignment="Center" VerticalAlignment="Center"
Foreground="White">My button</Button>
Hope it helps
you just need to give focus to the next input field (by invoking focus()method on that input element), for example if you're using jQuery this code will simulate the tab key when enter is pressed:
var inputs = $(':input').keypress(function(e){
if (e.which == 13) {
e.preventDefault();
var nextInput = inputs.get(inputs.index(this) + 1);
if (nextInput) {
nextInput.focus();
}
}
});
You'll want to include action="javascript:void(0);"
to your form to prevent page reloads and maintain HTML standard.
The splat and spread operators are part of ES6, the planned next version of Javascript. So far only Firefox supports them. This code works in FF16+:
var arr = ['quick', 'brown', 'lazy'];
var sprintf = function(str, ...args)
{
for (arg of args) {
str = str.replace(/%s/, arg);
}
return str;
}
sprintf.apply(null, ['The %s %s fox jumps over the %s dog.', ...arr]);
sprintf('The %s %s fox jumps over the %s dog.', 'slow', 'red', 'sleeping');
Note the awkard syntax for spread. The usual syntax of sprintf('The %s %s fox jumps over the %s dog.', ...arr);
is not yet supported. You can find an ES6 compatibility table here.
Note also the use of for...of
, another ES6 addition. Using for...in
for arrays is a bad idea.
it can also be achieved with below code
import re
text = 'how are u? umberella u! u. U. U@ U# u '
print (re.sub (r'[uU] ( [^a-z] )', r' you\1 ', text))
or
print (re.sub (r'[uU] ( [\s!,.?@#] )', r' you\1 ', text))
Swift 4, if all you really need is a 24 hour shift (60*60*24 seconds) and not "1 calendar day"
Future:
let dayAhead = Date(timeIntervalSinceNow: TimeInterval(86400.0))
Past:
let dayAgo = Date(timeIntervalSinceNow: TimeInterval(-86400.0))
For compare hashed password with the plain text password string you can use the PHP password_verify
if(password_verify('1234567', $crypt_password_string)) {
// in case if "$crypt_password_string" actually hides "1234567"
}
New in Chrome 50+ and Firefox 39+ (resp. 44+):
formdata.entries()
(combine with Array.from()
for debugability)formdata.get(key)
Original answer:
What I usually do to 'debug' a FormData
object, is just send it (anywhere!) and check the browser logs (eg. Chrome devtools' Network tab).
You don't need a/the same Ajax framework. You don't need any details. Just send it:
var xhr = new XMLHttpRequest;
xhr.open('POST', '/', true);
xhr.send(data);
Easy.
You can try this:
Calendar sDate = Calendar.getInstance();
Calendar eDate = Calendar.getInstance();
sDate.setTime(startDate.getTime());
eDate.setTime(endDate.getTime());
int difInMonths = sDate.get(Calendar.MONTH) - eDate.get(Calendar.MONTH);
I think this should work. I used something similar for my project and it worked for what I needed (year diff). You get a Calendar
from a Date
and just get the month's diff.
Anything in the href tag will display at the bottom-left of the browser window when you mouse over it.
I personally think having something like javascript:void(0) displayed to the user is hideous.
Instead, leave href off, do your magic with with jQuery/whatever else and add a style rule (if you still need it to look like a link):
a {
cursor:pointer;
}
You need to publish the app before it becomes available for testing.
if you publish the app and the apk is only in "alpha testing" section then it is NOT available to general public, only for activated testers in the alpha section.
EDIT: One additional note: "normal" users will not find your app on Google Play, but also the activated tester can not find the application by using the search box.
Only the direct link to the application package will work. (only for the activated testers).
for me it was installed in /usr/local/opt
The command I used for installation is brew install [email protected]
You can also use:
mMap.animateCamera( CameraUpdateFactory.zoomTo( 17.0f ) );
To just change the zoom value to any desired value between minimum value=2.0 and maximum value=21.0.
The API warns that not all locations have tiles at values at or near maximum zoom.
See this for more information about zoom methods available in the CameraUpdateFactory
.
If you have an java.awt.Image
, rezising it doesn't require any additional libraries. Just do:
Image newImage = yourImage.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT);
Ovbiously, replace newWidth
and newHeight
with the dimensions of the specified image.
Notice the last parameter: it tells to the runtime the algorithm you want to use for resizing.
There are algorithms that produce a very precise result, however these take a large time to complete.
You can use any of the following algorithms:
Image.SCALE_DEFAULT
: Use the default image-scaling algorithm.Image.SCALE_FAST
: Choose an image-scaling algorithm that gives higher priority to scaling speed than smoothness of the scaled image.Image.SCALE_SMOOTH
: Choose an image-scaling algorithm that gives higher priority to image smoothness than scaling speed.Image.SCALE_AREA_AVERAGING
: Use the Area Averaging image scaling algorithm.Image.SCALE_REPLICATE
: Use the image scaling algorithm embodied in the ReplicateScaleFilter
class.See the Javadoc for more info.
Try to cast it as a DATE
SELECT CAST(orders.date_purchased AS DATE) AS DATE_PURCHASED
Add
tools:ignore="ContentDescription"
to your image. Make sure you have xmlns:tools="http://schemas.android.com/tools"
.
in your root layout.
Use:
var config = {};
jQuery(form).serializeArray().map(function(item) {
if ( config[item.name] ) {
if ( typeof(config[item.name]) === "string" ) {
config[item.name] = [config[item.name]];
}
config[item.name].push(item.value);
} else {
config[item.name] = item.value;
}
});
Using Bash you may insert a TAB character programmatically like so:
TAB=$'\t'
echo 'line' | sed "s/.*/${TAB}&/g"
echo 'line' | sed 's/.*/'"${TAB}"'&/g' # use of Bash string concatenation
Be aware that HtmlUnitDriver webclient is single-threaded and Ghostdriver is only at 40% of the functionalities to be a WebDriver.
Nonetheless, Ghostdriver run properly for tests and I have problems to connect it to the WebDriver hub.
Check out yowsup
https://github.com/tgalal/yowsup
Yowsup is a python library that allows you to do all the previous in your own app. Yowsup allows you to login and use the Whatsapp service and provides you with all capabilities of an official Whatsapp client, allowing you to create a full-fledged custom Whatsapp client.
A solid example of Yowsup's usage is Wazapp. Wazapp is full featured Whatsapp client that is being used by hundreds of thousands of people around the world. Yowsup is born out of the Wazapp project. Before becoming a separate project, it was only the engine powering Wazapp. Now that it matured enough, it was separated into a separate project, allowing anyone to build their own Whatsapp client on top of it. Having such a popular client as Wazapp, built on Yowsup, helped bring the project into a much advanced, stable and mature level, and ensures its continuous development and maintaince.
Yowsup also comes with a cross platform command-line frontend called yowsup-cli. yowsup-cli allows you to jump into connecting and using Whatsapp service directly from command line.
If try to print the f object, then you will see that there is f.object that can be probed for getting the selected item (applicable for all rails version > 2.3)
logger.warn("f #{f.object.inspect}")
so, use the following script to get the proper selected option:
:selected => f.object.your_field
You can do this in two ways:
ElementMatch - $elemMatch
(as explained in above answers)
db.users.find({ awards: { $elemMatch: {award:'Turing Award', year:1977} } })
Use $and
with find
db.getCollection('users').find({"$and":[{"awards.award":"Turing Award"},{"awards.year":1977}]})
This can happen if disableContentCompression()
is set on a pooling manager assigned to your HttpClient, and the target server is trying to use gzip compression.
I'd check your php.ini file and verify the mysql.default_socket is set correctly and also verify that your mysqld is correctly configured with a socket file it can access. Typical default is "/tmp/mysql.sock".
Using Scanner
s, you will end up spawning a lot of objects for every line. You will generate a decent amount of garbage for the GC with large files. Also, it is nearly three times slower than using split().
On the other hand, If you split by space (line.split(" ")
), the code will fail if you try to read a file with a different whitespace delimiter. If split()
expects you to write a regular expression, and it does matching anyway, use split("\\s")
instead, that matches a "bit" more whitespace than just a space character.
P.S.: Sorry, I don't have right to comment on already given answers.
Quick tweak to @alex-rodrigues answer... deals with shape including the number of channels.
import cv2
import numpy as np
def rotateImage(image, angle):
center=tuple(np.array(image.shape[0:2])/2)
rot_mat = cv2.getRotationMatrix2D(center,angle,1.0)
return cv2.warpAffine(image, rot_mat, image.shape[0:2],flags=cv2.INTER_LINEAR)
Going to keep this pithier, this is already asked and answered above .
I'd step back however and answer it slightly differently, the docker engine itself adds orchestration as one of its extras and this is the disruptive part. Once you start running an app as a combination of containers running 'somewhere' across multiple container engines it gets really exciting. Robustness, Horizontal Scaling, complete abstraction from the underlying hardware, i could go on and on...
Its not just Docker that gives you this, in fact the de facto Container Orchestration standard is Kubernetes which comes in a lot of flavours, a Docker one, but also OpenShift, SuSe, Azure, AWS...
Then beneath K8S there are alternative container engines; the interesting ones are Docker and CRIO - recently built, daemonless, intended as a container engine specifically for Kubernetes but immature. Its the competition between these that I think will be the real long term choice for a container engine.
From Object-Oriented Programming Concept:
If you have a function that is accessing/muttating the fields of your class, it becomes method. Otherwise, it is a function.
It will not be a crime if you keep calling all the functions in Java/C++ classes as methods. The reason is that you are directly/indirectly accessing/mutating class properties. So why not all the functions in Java/C++ classes are methods?
Have you looked in firebug if POST or GET?.
check the console display.
Put in the test script:
console.log(data);
You can see the response from the server, if it shows something.
This isn't added out of the box because the Angular team wants Angular 2 to run minified. OrderBy runs off of reflection which breaks with minification. Check out Miško Heverey's response on the matter.
I've taken the time to create an OrderBy pipe that supports both single and multi-dimensional arrays. It also supports being able to sort on multiple columns of the multi-dimensional array.
<li *ngFor="let person of people | orderBy : ['-lastName', 'age']">{{person.firstName}} {{person.lastName}}, {{person.age}}</li>
This pipe does allow for adding more items to the array after rendering the page, and still sort the arrays with the new items correctly.
I have a write up on the process here.
And here's a working demo: http://fuelinteractive.github.io/fuel-ui/#/pipe/orderby and https://plnkr.co/edit/DHLVc0?p=info
EDIT: Added new demo to http://fuelinteractive.github.io/fuel-ui/#/pipe/orderby
EDIT 2: Updated ngFor to new syntax
You will have to use some sort of network sniffer if you want to get at this sort of data and you're likely to run into the same problem (pulling out the relevant data from the overall network traffic) with those that you do now with Wireshark.
Is there a way to apply a Class' style to only ONE level of td tags?
Yes*:
.MyClass>tbody>tr>td { border: solid 1px red; }
But! The ‘>
’ direct-child selector does not work in IE6. If you need to support that browser (which you probably do, alas), all you can do is select the inner element separately and un-set the style:
.MyClass td { border: solid 1px red; }
.MyClass td td { border: none; }
*Note that the first example references a tbody
element not found in your HTML. It should have been in your HTML, but browsers are generally ok with leaving it out... they just add it in behind the scenes.
I've found a much easier way. Using Powershell, we can hook Excel as a COM object.
$user = $env:UserName
$msoExcel = New-Object -ComObject Excel.Application
$msoExcel | Select-Object -Property OperatingSystem | Out-File "\\SERVER\Path\To\Dump\msoVersion-$user.txt"
exit
When requesting the OperatingSystem this way, we get strange results, have a look here. PC3 is mine.
I hope this works for you guys. Sorry for the lack of code; my scripts are mostly functional.
Edit:
Don't forget to add the code to close Excel after you're done retrieving the data.
After testing this code yesterday I had tons of Excel opening and crashing all of a sudden..
This will make sure you'll keep users and admins happy (:
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($msoExcel)
Remove-Variable msoExcel
I am running CentOS 5.6 as my development environment and the following worked for me.
su -
pecl install ssh2
echo "extension=ssh2.so" > /etc/php.d/ssh2.ini
/etc/init.d/httpd restart
Goto config/initializers/setup_mail.rb
Check whether the configuration there matches the configuration written in the development.rb
file.It should look like the following in both files:
config.action_mailer.smtp_settings = {
:address =>"[email protected]",
:port => 587,
:domain => "gmail.com",
:user_name => "[email protected]",
:password => "********",
:authentication => 'plain',
:enable_starttls_auto => true,
:openssl_verify_mode => 'none'
}
This will most certainly solve your problem.