Figured it out by testing all the stuff by myself. Couldn't find any topics about it tho, so I'll just leave the solution here. This might not be the only or even the best solution, but it works for my purposes (within getch's limits) and is better than nothing.
Note: proper keyDown()
which would recognize all the keys and actual key presses, is still valued.
Solution: using ord()
-function to first turn the getch()
into an integer (I guess they're virtual key codes, but not too sure) works fine, and then comparing the result to the actual number representing the wanted key. Also, if I needed to, I could add an extra chr()
around the number returned so that it would convert it to a character. However, I'm using mostly down arrow, esc, etc. so converting those to a character would be stupid. Here's the final code:
from msvcrt import getch
while True:
key = ord(getch())
if key == 27: #ESC
break
elif key == 13: #Enter
select()
elif key == 224: #Special keys (arrows, f keys, ins, del, etc.)
key = ord(getch())
if key == 80: #Down arrow
moveDown()
elif key == 72: #Up arrow
moveUp()
Also if someone else needs to, you can easily find out the keycodes from google, or by using python and just pressing the key:
from msvcrt import getch
while True:
print(ord(getch()))
As said above getch()
is in the ncurses
library. ncurses has to be initialized, see i.e. getchar() returns the same value (27) for up and down arrow keys for this
The keypad
will allow the keyboard of the user's terminal to allow for function keys to be interpreted as a single value (i.e. no escape sequence).
As stated in the man page:
The keypad option enables the keypad of the user's terminal. If enabled (bf is TRUE), the user can press a function key (such as an arrow key) and wgetch returns a single value representing the function key, as in KEY_LEFT. If disabled (bf is FALSE), curses does not treat function keys specially and the program has to interpret the escape sequences itself. If the keypad in the terminal can be turned on (made to transmit) and off (made to work locally), turning on this option causes the terminal keypad to be turned on when wgetch is called. The default value for keypad is false.
Do it the hard way. Use the awesome MODEL
clause:
SELECT V
FROM DUAL
MODEL DIMENSION BY (0 R)
MEASURES (0 V)
RULES ITERATE (100) (
V[ITERATION_NUMBER] = ITERATION_NUMBER + 1
)
ORDER BY 1
Very old thread, I know, but here's my contribution, as the thread is not solved yet.
It takes leap years into consideration and does not asume any fixed number of days per month or year.
It might be flawed in border cases as I haven't tested it thoroughly, but it works for all the dates provided in the original question, thus I'm confident.
function calculate() {_x000D_
var fromDate = document.getElementById('fromDate').value;_x000D_
var toDate = document.getElementById('toDate').value;_x000D_
_x000D_
try {_x000D_
document.getElementById('result').innerHTML = '';_x000D_
_x000D_
var result = getDateDifference(new Date(fromDate), new Date(toDate));_x000D_
_x000D_
if (result && !isNaN(result.years)) {_x000D_
document.getElementById('result').innerHTML =_x000D_
result.years + ' year' + (result.years == 1 ? ' ' : 's ') +_x000D_
result.months + ' month' + (result.months == 1 ? ' ' : 's ') + 'and ' +_x000D_
result.days + ' day' + (result.days == 1 ? '' : 's');_x000D_
}_x000D_
} catch (e) {_x000D_
console.error(e);_x000D_
}_x000D_
}_x000D_
_x000D_
function getDateDifference(startDate, endDate) {_x000D_
if (startDate > endDate) {_x000D_
console.error('Start date must be before end date');_x000D_
return null;_x000D_
}_x000D_
var startYear = startDate.getFullYear();_x000D_
var startMonth = startDate.getMonth();_x000D_
var startDay = startDate.getDate();_x000D_
_x000D_
var endYear = endDate.getFullYear();_x000D_
var endMonth = endDate.getMonth();_x000D_
var endDay = endDate.getDate();_x000D_
_x000D_
// We calculate February based on end year as it might be a leep year which might influence the number of days._x000D_
var february = (endYear % 4 == 0 && endYear % 100 != 0) || endYear % 400 == 0 ? 29 : 28;_x000D_
var daysOfMonth = [31, february, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];_x000D_
_x000D_
var startDateNotPassedInEndYear = (endMonth < startMonth) || endMonth == startMonth && endDay < startDay;_x000D_
var years = endYear - startYear - (startDateNotPassedInEndYear ? 1 : 0);_x000D_
_x000D_
var months = (12 + endMonth - startMonth - (endDay < startDay ? 1 : 0)) % 12;_x000D_
_x000D_
// (12 + ...) % 12 makes sure index is always between 0 and 11_x000D_
var days = startDay <= endDay ? endDay - startDay : daysOfMonth[(12 + endMonth - 1) % 12] - startDay + endDay;_x000D_
_x000D_
return {_x000D_
years: years,_x000D_
months: months,_x000D_
days: days_x000D_
};_x000D_
}
_x000D_
<p><input type="text" name="fromDate" id="fromDate" placeholder="yyyy-mm-dd" value="1999-02-28" /></p>_x000D_
<p><input type="text" name="toDate" id="toDate" placeholder="yyyy-mm-dd" value="2000-03-01" /></p>_x000D_
<p><input type="button" name="calculate" value="Calculate" onclick="javascript:calculate();" /></p>_x000D_
<p />_x000D_
<p id="result"></p>
_x000D_
Tick 'Full Index Enabled' and then 'Rebuild Index' of the central repository in 'Global Repositories' under Window > Show View > Other > Maven > Maven Repositories
, and it should work.
The rebuilding may take a long time depending on the speed of your internet connection, but eventually it works.
Well, I came across another sweet solution.
window['functioName'](params);
It is possible to upack without node installed using the following 7-Zip plugin:
http://www.tc4shell.com/en/7zip/asar/
Thanks @MayaPosch for mentioning that in this comment.
After reading the other answers (First by @duncan-finney and then by @Marrs) I set out to find the change log that explains the idiomatic react-router 2.x way of solving this. The documentation on using location (which you need for queries) in components is actually contradicted by the actual code. So if you follow their advice, you get big angry warnings like this:
Warning: [react-router] `context.location` is deprecated, please use a route component's `props.location` instead.
It turns out that you cannot have a context property called location that uses the location type. But you can use a context property called loc that uses the location type. So the solution is a small modification on their source as follows:
const RouteComponent = React.createClass({
childContextTypes: {
loc: PropTypes.location
},
getChildContext() {
return { location: this.props.location }
}
});
const ChildComponent = React.createClass({
contextTypes: {
loc: PropTypes.location
},
render() {
console.log(this.context.loc);
return(<div>this.context.loc.query</div>);
}
});
You could also pass down only the parts of the location object you want in your children get the same benefit. It didn't change the warning to change to the object type. Hope that helps.
Improvement to kaiser's answer:
var myEl = $document.find('#some-id');
Don't forget to inject $document
into your directive
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
CGPoint targetPoint = *targetContentOffset;
CGPoint currentPoint = scrollView.contentOffset;
if (targetPoint.y > currentPoint.y) {
NSLog(@"up");
}
else {
NSLog(@"down");
}
}
I am new to programming. I wanted to convert from yyyy-mm-dd
to dd/mm/yyyy
to print out a date in the format that people in my part of the world use and recognise.
The accepted answer above got me on the right track.
The answer I ended up with to my problem is:
import datetime
today_date = datetime.date.today()
print(today_date)
new_today_date = today_date.strftime("%d/%m/%Y")
print (new_today_date)
The first two lines after the import statement gives today's date in the USA format (2017-01-26). The last two lines convert this to the format recognised in the UK and other countries (26/01/2017).
You can shorten this code, but I left it as is because it is helpful to me as a beginner. I hope this helps other beginner programmers starting out!
import numpy as np
a=np.array([[21,20,19,18,17],[16,15,14,13,12],[11,10,9,8,7],[6,5,4,3,2]])
y=np.argsort(a[:,2],kind='mergesort')# a[:,2]=[19,14,9,4]
a=a[y]
print(a)
Desired output is [[6,5,4,3,2],[11,10,9,8,7],[16,15,14,13,12],[21,20,19,18,17]]
note that argsort(numArray)
returns the indices of an numArray
as it was supposed to be arranged in a sorted manner.
example
x=np.array([8,1,5])
z=np.argsort(x) #[1,3,0] are the **indices of the predicted sorted array**
print(x[z]) #boolean indexing which sorts the array on basis of indices saved in z
answer would be [1,5,8]
Similar to C# casting to (int)
with just using standard lib:
Math.trunc(1.6) // 1
Math.trunc(-1.6) // -1
if input == 'a':
for char in 'abc':
if char in some_list:
some_list.remove(char)
You could do:
Color c = Color.FromArgb(red, green, blue); //red, green and blue are integer variables containing red, green and blue components
Try
pip install --trusted-host pypi.python.org packagename
It worked for me.
Use "
That should work.
Change the start
field in package.json from
"start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" "
to
"start": "concurrently \"npm run tsc:w\" \"npm run lite\" "
Numeric precision refers to the maximum number of digits that are present in the number.
ie 1234567.89 has a precision of 9
Numeric scale refers to the maximum number of decimal places
ie 123456.789 has a scale of 3
Thus the maximum allowed value for decimal(5,2) is 999.99
I've found that this error is also generated if the document is empty. In this case it's also because there is no root element - but the error message "Extra content and the end of the document" is misleading in this situation.
I was messing/musing on one-liners involving querySelector() & ended up here, & have a possible answer to the OP question using tag names & querySelector(), with credits to @JaredMcAteer for answering MY question, aka have RegEx-like matches with querySelector() in vanilla Javascript
Hoping the following will be useful & fit the OP's needs or everyone else's:
// basically, of before:
var youtubeDiv = document.querySelector('iframe[src="http://www.youtube.com/embed/Jk5lTqQzoKA"]')
// after
var youtubeDiv = document.querySelector('iframe[src^="http://www.youtube.com"]');
// or even, for my needs
var youtubeDiv = document.querySelector('iframe[src*="youtube"]');
Then, we can, for example, get the src stuff, etc ...
console.log(youtubeDiv.src);
//> "http://www.youtube.com/embed/Jk5lTqQzoKA"
console.debug(youtubeDiv);
//> (...)
If you are using nodejs try:
require('net').isIP('10.0.0.1')
doc net.isIP()
We had the same issue while trying to launch Selenium tests from Jenkins. I had selected the 'Start Xvfb before the build, and shut it down after' box and passed in the necessary screen options, but I was still getting this error.
It finally worked when we passed in the following commands in the Execute Shell box.
Xvfb :99 -ac -screen 0 1280x1024x24 &
nice -n 10 x11vnc 2>&1 &
...
killall Xvfb
If you don't want to convert.Just use;
bool _status = status == "1" ? true : false;
Perhaps you will return the values as you want.
If you are planning to get the image from its path, it's better to use Assets instead of trying to figure out the path of the drawable folder.
InputStream stream = getAssets().open("image.png");
Drawable d = Drawable.createFromStream(stream, null);
Another way is to use /sys/class/android_usb/android0/iSerial in an App with no permissions whatsoever.
user@creep:~$ adb shell ls -l /sys/class/android_usb/android0/iSerial
-rw-r--r-- root root 4096 2013-01-10 21:08 iSerial
user@creep:~$ adb shell cat /sys/class/android_usb/android0/iSerial
0A3CXXXXXXXXXX5
To do this in java one would just use a FileInputStream to open the iSerial file and read out the characters. Just be sure you wrap it in an exception handler because not all devices have this file.
At least the following devices are known to have this file world-readable:
You can also see my blog post here: http://insitusec.blogspot.com/2013/01/leaking-android-hardware-serial-number.html where I discuss what other files are available for info.
Check out perlfaq4: How do I merge two hashes. There is a lot of good information already in the Perl documentation and you can have it right away rather than waiting for someone else to answer it. :)
Before you decide to merge two hashes, you have to decide what to do if both hashes contain keys that are the same and if you want to leave the original hashes as they were.
If you want to preserve the original hashes, copy one hash (%hash1) to a new hash (%new_hash), then add the keys from the other hash (%hash2 to the new hash. Checking that the key already exists in %new_hash gives you a chance to decide what to do with the duplicates:
my %new_hash = %hash1; # make a copy; leave %hash1 alone
foreach my $key2 ( keys %hash2 )
{
if( exists $new_hash{$key2} )
{
warn "Key [$key2] is in both hashes!";
# handle the duplicate (perhaps only warning)
...
next;
}
else
{
$new_hash{$key2} = $hash2{$key2};
}
}
If you don't want to create a new hash, you can still use this looping technique; just change the %new_hash to %hash1.
foreach my $key2 ( keys %hash2 )
{
if( exists $hash1{$key2} )
{
warn "Key [$key2] is in both hashes!";
# handle the duplicate (perhaps only warning)
...
next;
}
else
{
$hash1{$key2} = $hash2{$key2};
}
}
If you don't care that one hash overwrites keys and values from the other, you could just use a hash slice to add one hash to another. In this case, values from %hash2 replace values from %hash1 when they have keys in common:
@hash1{ keys %hash2 } = values %hash2;
To avoid the called process to be blocked if it outputs a lot of data on the standard output and/or error, you have to use the solution provided by Craigo. Note also that ProcessBuilder is better than Runtime.getRuntime().exec(). This is for a couple of reasons: it tokenizes better the arguments, and it also takes care of the error standard output (check also here).
ProcessBuilder builder = new ProcessBuilder("cmd", "arg1", ...);
builder.redirectErrorStream(true);
final Process process = builder.start();
// Watch the process
watch(process);
I use a new function "watch" to gather this data in a new thread. This thread will finish in the calling process when the called process ends.
private static void watch(final Process process) {
new Thread() {
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
try {
while ((line = input.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
I did it this way:
<update id="updateSettings" parameterType="PushSettings">
<foreach collection="settings" item="setting">
UPDATE push_setting SET status = #{setting.status}
WHERE type = #{setting.type} AND user_id = #{userId};
</foreach>
</update>
where PushSettings is
public class PushSettings {
private List<PushSetting> settings;
private String userId;
}
it works fine
My bible for JPA work is the Java Persistence wikibook. It has a section on unidirectional OneToMany
which explains how to do this with a @JoinColumn
annotation. In your case, i think you would want:
@OneToMany
@JoinColumn(name="TXTHEAD_CODE")
private Set<Text> text;
I've used a Set
rather than a List
, because the data itself is not ordered.
The above is using a defaulted referencedColumnName
, unlike the example in the wikibook. If that doesn't work, try an explicit one:
@OneToMany
@JoinColumn(name="TXTHEAD_CODE", referencedColumnName="DATREG_META_CODE")
private Set<Text> text;
I faced the same 415
http error when sending objects, serialized into JSON, via PUT/PUSH requests to my JAX-rs services, in other words my server was not able to de-serialize the objects from JSON.
In my case, the server was able to serialize successfully the same objects in JSON when sending them into its responses.
As mentioned in the other responses I have correctly set the Accept
and Content-Type
headers to application/json
, but it doesn't suffice.
Solution
I simply forgot a default constructor with no parameters for my DTO objects. Yes this is the same reasoning behind @Entity objects, you need a constructor with no parameters for the ORM to instantiate objects and populate the fields later.
Adding the constructor with no parameters to my DTO objects solved my issue. Here follows an example that resembles my code:
Wrong
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {
public NumberDTO(Number number) {
this.number = number;
}
private Number number;
public Number getNumber() {
return number;
}
public void setNumber(Number string) {
this.number = string;
}
}
Right
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {
public NumberDTO() {
}
public NumberDTO(Number number) {
this.number = number;
}
private Number number;
public Number getNumber() {
return number;
}
public void setNumber(Number string) {
this.number = string;
}
}
I lost hours, I hope this'll save yours ;-)
If you are using an earlier version of Python or you have a very good reason to roll your own word counter (I'd like to hear it!), you could try the following approach using a dict
.
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> word_list = ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats', 'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and', 'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.', 'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cats', 'have', 'bright', 'black', 'eyes;', 'They', 'like', 'to', 'practise', 'their', 'airs', 'and', 'graces', 'And', 'wait', 'for', 'the', 'Jellicle', 'Moon', 'to', 'rise.', '']
>>> word_counter = {}
>>> for word in word_list:
... if word in word_counter:
... word_counter[word] += 1
... else:
... word_counter[word] = 1
...
>>> popular_words = sorted(word_counter, key = word_counter.get, reverse = True)
>>>
>>> top_3 = popular_words[:3]
>>>
>>> top_3
['Jellicle', 'Cats', 'and']
Top Tip: The interactive Python interpretor is your friend whenever you want to play with an algorithm like this. Just type it in and watch it go, inspecting elements along the way.
You could do something like this:
$("#txtArea").on("keypress",function(e) {_x000D_
var key = e.keyCode;_x000D_
_x000D_
// If the user has pressed enter_x000D_
if (key == 13) {_x000D_
document.getElementById("txtArea").value =document.getElementById("txtArea").value + "\n";_x000D_
return false;_x000D_
}_x000D_
else {_x000D_
return true;_x000D_
}_x000D_
});
_x000D_
<textarea id="txtArea"></textarea>
_x000D_
There is a nice little url
utility for this with some cool sugaring:
http://www.example.com/path/index.html?silly=willy#chucky=cheese
url(); // http://www.example.com/path/index.html?silly=willy#chucky=cheese
url('domain'); // example.com
url('1'); // path
url('-1'); // index.html
url('?'); // silly=willy
url('?silly'); // willy
url('?poo'); // (an empty string)
url('#'); // chucky=cheese
url('#chucky'); // cheese
url('#poo'); // (an empty string)
Check out more examples and download here: https://github.com/websanova/js-url#url
I think request.domain would work, but what if you're in a sub directory like blah.blah.com? Something like this could work:
<%= request.env["HTTP_HOST"] + page = "/" + request.path_parameters['controller'] + "/" + request.path_parameters['action'] %>
Change the parameters based on your path structure.
Hope that helps!
int val_to_check = 5
bool in_range = Enumerable.Range(0, 13).Contains(val_to_check);
The second parameter is the "count" not the end or high number.
I.E.
int low_num = 0
int high_num = 12
int val_to_check = 5
bool in_range = Enumerable.Range(low_num , high_num - low_num + 1).Contains(val_to_check);
Checks if the val_to_check is between 0 and 12
The official way to handle this is using the PECL HTTP library. Unlike some answers here, this correctly handles the language priorities (q-values), partial language matches and will return the closest match, or when there are no matches it falls back to the first language in your array.
PECL HTTP:
http://pecl.php.net/package/pecl_http
How to use:
http://php.net/manual/fa/function.http-negotiate-language.php
$supportedLanguages = [
'en-US', // first one is the default/fallback
'fr',
'fr-FR',
'de',
'de-DE',
'de-AT',
'de-CH',
];
// Returns the negotiated language
// or the default language (i.e. first array entry) if none match.
$language = http_negotiate_language($supportedLanguages, $result);
Much simpler: use sudo
to run a shell and use a heredoc to feed it commands.
#!/usr/bin/env bash
whoami
sudo -i -u someuser bash << EOF
echo "In"
whoami
EOF
echo "Out"
whoami
(answer originally on SuperUser)
I'm not aware of any particular convention for javascript files as they aren't really unique on the web versus css files or html files or any other type of file like that. There are some "safe" things you can do that make it less likely you will accidentally run into a cross platform issue:
various-scripts.js
, a hyphen is a safe and useful and commonly used separator.When using JSON dictionaries:
#define isNull(value) value == nil || [value isKindOfClass:[NSNull class]]
if( isNull( dict[@"my_key"] ) )
{
// do stuff
}
The result is undefined
since $.ajax
runs an asynchronous operation. Meaning that return status
gets executed before the $.ajax
operation finishes with the request.
You may use Promise to have a syntax which feels synchronous.
function doSomething() {
return new Promise((resolve, reject) => {
$.ajax({
url:'action.php',
type: "POST",
data: dataString,
success: function (txtBack) {
if(txtBack==1) {
resolve(1);
} else {
resolve(0);
}
},
error: function (jqXHR, textStatus, errorThrown) {
reject(textStatus);
}
});
});
}
You can call the promise like this
doSomething.then(function (result) {
console.log(result);
}).catch(function (error) {
console.error(error);
});
or this
(async () => {
try {
let result = await doSomething();
console.log(result);
} catch (error) {
console.error(error);
}
})();
The browser is still submitting the form after your code runs.
Add return false;
to the handler to prevent that.
When you call delete on a pointer allocated by new, the destructor of the object pointed to will be called.
A * p = new A;
delete p; // A:~A() called for you on obkect pointed to by p
You can also use this convoluted command, which does not trigger a warning about terminating its own process:
osascript -e "do shell script \"osascript -e \\\"tell application \\\\\\\"Terminal\\\\\\\" to quit\\\" &> /dev/null &\""; exit
This command is quite long, so you could define an alias (such as quit
) in your bash profile:
alias quit='osascript -e "do shell script \"osascript -e \\\"tell application \\\\\\\"Terminal\\\\\\\" to quit\\\" &> /dev/null &\""; exit'
This would allow you to simply type quit
into terminal without having to fiddle with any other settings.
Put this into your .bashrc
# fix CURL certificates path
export CURL_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt
(see comment from Robert)
For Swift 3, many Foundation
types have dropped the 'NS' prefix, so you'd access it by UUID().uuidString
.
Without using external tools, if you are connecting to the server view SSH, this is a relatively easy command:
From a Windows 7+ command prompt:
ssh user@server cat /etc/passwd | clip
This will put the content of the remote file to your local clipboard.
(The command requires running Pageant for the key, or it will ask you for a password.)
Consider the array a:
var a ={'name1':1, 'name2':2}
If you want to check if 'name1' exists in a, simply test it with in
:
if('name1' in a){
console.log('name1 exists in a')
}else
console.log('name1 is not in a')
use this code in teminal :
python -m pip install --upgrade PAKAGE_NAME #instead of PAKAGE_NAME
for example i want update pip pakage :
python -m pip install --upgrade pip
more example :
python -m pip install --upgrade selenium
python -m pip install --upgrade requests
...
The go style:
func Contains(n int, match func(i int) bool) bool {
for i := 0; i < n; i++ {
if match(i) {
return true
}
}
return false
}
s := []string{"a", "b", "c", "o"}
// test if s contains "o"
ok := Contains(len(s), func(i int) bool {
return s[i] == "o"
})
Another problem solved by the rubber duck:
The css is right but you still have to remember that the HTML elements order matters: the div has to come before the header. http://jsfiddle.net/Fq2Na/1/
Change your HTML code to have the div before the header:
<section>
<div><button>button</button></div>
<h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>
</section>
And keep your CSS to the simple div { float: right; }
.
You need to convert your script to a shell function:
#!/bin/bash
#
# this script should not be run directly,
# instead you need to source it from your .bashrc,
# by adding this line:
# . ~/bin/myprog.sh
#
function myprog() {
A=$1
B=$2
echo "aaa ${A} bbb ${B} ccc"
cd /proc
}
The reason is that each process has its own current directory, and when you execute a program from the shell it is run in a new process. The standard "cd", "pushd" and "popd" are builtin to the shell interpreter so that they affect the shell process.
By making your program a shell function, you are adding your own in-process command and then any directory change gets reflected in the shell process.
Also be careful how you execute the js on the page. For example if you do something like this:
(function(window, document, undefined){
var foo = document.getElementById("foo");
console.log(foo);
})(window, document, undefined);
This will return null because you'd be calling the document before it was loaded.
Better option..
(function(window, document, undefined){
// code that should be taken care of right away
window.onload = init;
function init(){
// the code to be called when the dom has loaded
// #document has its nodes
}
})(window, document, undefined);
Bash does not supports multidimensional array, but we can implement using Associate array. Here the indexes are the key to retrieve the value. Associate array is available in bash
version 4.
#!/bin/bash
declare -A arr2d
rows=3
columns=2
for ((i=0;i<rows;i++)) do
for ((j=0;j<columns;j++)) do
arr2d[$i,$j]=$i
done
done
for ((i=0;i<rows;i++)) do
for ((j=0;j<columns;j++)) do
echo ${arr2d[$i,$j]}
done
done
There are two approaches that I know of. The first is to tell the browser not to cache the page. Setting the Response to no cache takes care of that, however as you suspect the browser will often ignore this directive. The other approach is to set the date time of your response to a point in the future. I believe all browsers will correct this to the current time when they add the page to the cache, but it will show the page as newer when the comparison is made. I believe there may be some cases where a comparison is not made. I am not sure of the details and they change with each new browser release. Final note I have had better luck with pages that "refresh" themselves (another response directive). The refresh seems less likely to come from the cache.
Hope that helps.
Without getting into the code first, the logic/algorithm goes below:
Go to the transaction
table with multiple records for the same client
.
Select records of clientID
and the latestDate
of client's activity using group by clientID
and max(transactionDate)
select clientID, max(transactionDate) as latestDate
from transaction
group by clientID
inner join
the transaction
table with the outcome from Step 2, then you will have the full records of the transaction
table with only each client's latest record.
select * from
transaction t
inner join (
select clientID, max(transactionDate) as latestDate
from transaction
group by clientID) d
on t.clientID = d.clientID and t.transactionDate = d.latestDate)
You can use the result from step 3 to join any table you want to get different results.
Instead of adding variables and strings, you can use the ES6 template strings! Here is an example:
<img className="image" src={`images/${this.props.image}`} />
As for all other JavaScript components inside JSX, use template strings inside of curly braces. To "inject" a variable use a dollar sign followed by curly braces containing the variable you would like to inject. For example:
{`string ${variable} another string`}
For Ubuntu 18.04 installnasm
. Open the terminal and type:
sudo apt install as31 nasm
nasm docs
For compiling and running:
nasm -f elf64 example.asm # assemble the program
ld -s -o example example.o # link the object file nasm produced into an executable file
./example # example is an executable file
Just include this script
http://code.jquery.com/jquery-migrate-1.0.0.js
after you include your jquery javascript file.
for(var property in data) {
alert(property);
}
Set up a virtualenv:
% curl -kLso /tmp/get-pip.py https://bootstrap.pypa.io/get-pip.py
% sudo python /tmp/get-pip.py
These commands install pip into the global site-packages directory.
% sudo pip install virtualenv
and ditto for virtualenv:
% mkdir -p ~/.virtualenvs
I like my virtualenvs under one tree in my home directory called .virtualenvs
% virtualenv ~/.virtualenvs/lxmltest
Creates a virtualenv.
% . ~/.virtualenvs/lxmltest/bin/activate
Removes the need to specify the full path to pip/python in this virtualenv.
% pip install lxml
Alternatively execute ~/.virtualenvs/lxmltest/bin/pip install lxml
if you chose not to follow the previous step. Note, I'm not sure how far along you are, so some of these steps can be safely skipped. Of course, if you mess something up, you can always rm -Rf ~/.virtualenvs/lxmltest
and start again from a new virtualenv.
UPDATED
I've updated your demo: http://jsfiddle.net/terryyounghk/QS56z/18/
Also, I've changed two ^=
to *=
. See http://api.jquery.com/category/selectors/
And note the :checked
selector. See http://api.jquery.com/checked-selector/
function createcodes() {
//run through each row
$('.authors-list tr').each(function (i, row) {
// reference all the stuff you need first
var $row = $(row),
$family = $row.find('input[name*="family"]'),
$grade = $row.find('input[name*="grade"]'),
$checkedBoxes = $row.find('input:checked');
$checkedBoxes.each(function (i, checkbox) {
// assuming you layout the elements this way,
// we'll take advantage of .next()
var $checkbox = $(checkbox),
$line = $checkbox.next(),
$size = $line.next();
$line.val(
$family.val() + ' ' + $size.val() + ', ' + $grade.val()
);
});
});
}
Depending on what arguments you need to pass, especially for custom event handlers, you can do something like this:
<div @customEvent='(arg1) => myCallback(arg1, arg2)'>Hello!</div>
In my case it was not working because of the return.
Instead of using:
return RedirectToAction("Rescue", "CarteiraEtapaInvestimento", new { id = investimento.Id, idCarteiraEtapaResgate = etapaDoResgate.Id });
I used:
return View("ViewRescueCarteiraEtapaInvestimento", new CarteiraEtapaInvestimentoRescueViewModel { Investimento = investimento, ValorResgate = investimentoViewModel.ValorResgate });
It´s a Model, so it is obvius that ModelState.AddModelError("keyName","Message");
must work with a model.
This answer show why. Adding validation with DataAnnotations
Complete java converter code for all primitive types to/from arrays http://www.daniweb.com/code/snippet216874.html
You have to put all your assets in app/public
folder, and to access them from your views you can use asset()
helper method.
Ex. you can retrieve assets/images/image.png
in your view as following:
<img src="{{asset('assets/images/image.png')}}">
Make sure that the value of the column is really NULL and not an empty string or 0.
Make it dataType
instead of datatype
.
And add below code in php as your ajax request is expecting json and will not accept anything, but json.
header('Content-Type: application/json');
Correct Content type for JSON and JSONP
The response visible in firebug is text data. Check Content-Type
of the response header to verify, if the response is json. It should be application/json
for dataType:'json'
and text/html
for dataType:'html'
.
It would be great if Convert.ToString() had a proper overload for this.
There's been a Convert.ToString(Object value)
since .Net 2.0 (approx. 5 years before this Q was asked), which appears to do exactly what you want:
http://msdn.microsoft.com/en-us/library/astxcyeh(v=vs.80).aspx
Am I missing/misinterpreting something really obvious here?
Use the INTERVAL
type to it. E.g:
--yesterday
SELECT NOW() - INTERVAL '1 DAY';
--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;
Then you can do the following on your query:
SELECT
org_id,
count(accounts) AS COUNT,
((date_at) - INTERVAL '1 DAY') AS dateat
FROM
sourcetable
WHERE
date_at <= now() - INTERVAL '130 DAYS'
GROUP BY
org_id,
dateat;
You can append multiple operands. E.g.: how to get last day of current month?
SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';
You can also create an interval using make_interval
function, useful when you need to create it at runtime (not using literals):
SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);
You can use database from here -
http://myip.ms/info/cities_sql_database/
CREATE TABLE `cities` (
`cityID` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`cityName` varchar(50) NOT NULL,
`stateID` smallint(5) unsigned NOT NULL DEFAULT '0',
`countryID` varchar(3) NOT NULL DEFAULT '',
`language` varchar(10) NOT NULL DEFAULT '',
`latitude` double NOT NULL DEFAULT '0',
`longitude` double NOT NULL DEFAULT '0',
PRIMARY KEY (`cityID`),
UNIQUE KEY `unq` (`countryID`,`stateID`,`cityID`),
KEY `cityName` (`cityName`),
KEY `stateID` (`stateID`),
KEY `countryID` (`countryID`),
KEY `latitude` (`latitude`),
KEY `longitude` (`longitude`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
You could use rebase interactive to modify the last two commits before they've been pushed to a remote
git rebase HEAD^^ -i
If anyone is still wondering what the value in CV_CAP_PROP_EXPOSURE
might be:
Depends. For my cheap webcam I have to enter the desired value directly, e.g. 0.1 for 1/10s. For my expensive industrial camera I have to enter -5 to get an exposure time of 2^-5s = 1/32s.
You could add easy key binding:
Preference > Key binding - user :
[
{ "keys": ["super+l"], "command": "reindent"},
]
Now select the line or file and hit: command + l
Try to insert these rows into the CSS and call the "disHighlight" at class property:
.disHighlight {
user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
-webkit-touch-callout: none;
-o-user-select: none;
-moz-user-select: none;
}
Many Markdown "extra" processors support attributes. So you can include a class name like so (PHP Markdown Extra):
![Flowers](/flowers.jpeg){.callout}
or, alternatively (Maruku, Kramdown, Python Markdown):
![Flowers](/flowers.jpeg){: .callout}
Then, of course, you can use a stylesheet the proper way:
.callout {
float: right;
}
If yours supports this syntax, it gives you the best of both worlds: no embedded markup, and a stylesheet abstract enough to not need to be modified by your content editor.
In windows first check under services if world wide web publishing services is running. If not start it.
If you cannot find it switch on IIS features of windows: In 7,8,10 it is under control panel , "turn windows features on or off". Internet Information Services World Wide web services and Internet information Services Hostable Core are required. Not sure if there is another way to get it going on windows, but this worked for me for all browsers. You might need to add localhost or http:/127.0.0.1 to the trusted websites also under IE settings.
You can remove public keyword from your functions, because, you have to define a class in order to declare public, private or protected function
I guess it will be a string. But the input parameters will be sent to the database & appropriate cast/conversions will be applied prior to creating an actual SQL statement.
To give you an example, it might try and see if the CAST/Conversion works.
If it works, it could create a final statement out of it.
SELECT * From MyTable WHERE param = CAST('10; DROP TABLE Other' AS varchar(30))
Try an example with a SQL statement accepting a numeric parameter.
Now, try passing a string variable (with numeric content that is acceptable as numeric parameter). Does it raise any error?
Now, try passing a string variable (with content that is not acceptable as numeric parameter). See what happens?
Here is a simple function I created for cleaning any spaces before or after, and multiple spaces within a string. It gracefully handles up to about 108 spaces in a single stretch and as many blocks as there are in the string. You can increase that by factors of 8 by adding additional lines with larger chunks of spaces if you need to. It seems to perform quickly and has not caused any problems in spite of it's generalized use in a large application.
CREATE FUNCTION [dbo].[fnReplaceMultipleSpaces] (@StrVal AS VARCHAR(4000))
RETURNS VARCHAR(4000)
AS
BEGIN
SET @StrVal = Ltrim(@StrVal)
SET @StrVal = Rtrim(@StrVal)
SET @StrVal = REPLACE(@StrVal, ' ', ' ') -- 16 spaces
SET @StrVal = REPLACE(@StrVal, ' ', ' ') -- 8 spaces
SET @StrVal = REPLACE(@StrVal, ' ', ' ') -- 4 spaces
SET @StrVal = REPLACE(@StrVal, ' ', ' ') -- 2 spaces
SET @StrVal = REPLACE(@StrVal, ' ', ' ') -- 2 spaces (for odd leftovers)
RETURN @StrVal
END
Its just a 2 line of code.
import org.springframework.web.client.RestTemplate;
RestTemplate restTemplate = new RestTemplate();
YourBean obj = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", YourBean.class);
I found the solution of this problem and i should work i'm sure about this because i also face the same problem
here is my solution----->
var request = require('request');
//set url
var url = 'http://localhost:8088/example';
//set header
var headers = {
'Authorization': 'Your authorization'
};
//set form data
var form = {first_name: first_name, last_name: last_name};
//set request parameter
request.post({headers: headers, url: url, form: form, method: 'POST'}, function (e, r, body) {
var bodyValues = JSON.parse(body);
res.send(bodyValues);
});
Simple! Create a dummy database (say abc)
Copy all these .myd, .myi, .frm files to mysql\data\abc wherein mysql\data\ is the place where .myd, .myi, .frm for all databases are stored.
Then go to phpMyadmin, go to db abc and you find your database.
Petar Ivanov's answer to replace a character at a specific index in a string question
String are immutable in Java. You can't change them.
You need to create a new string with the character replaced.
String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);
Or you can use a StringBuilder:
StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');
System.out.println(myName);
You could use an immutable struct
public struct Data
{
public Data(int intValue, string strValue)
{
IntegerData = intValue;
StringData = strValue;
}
public int IntegerData { get; private set; }
public string StringData { get; private set; }
}
var list = new List<Data>();
Or a KeyValuePair<int, string>
using Data = System.Collections.Generic.KeyValuePair<int, string>
...
var list = new List<Data>();
list.Add(new Data(12345, "56789"));
If the file that this script lives in is executable, the hash-bang (#!
) tells the operating system what interpreter to use to run the script. In this case it's /bin/sh
, for example.
There's a Wikipedia article about it for more information.
The <context:annotation-config>
tag tells Spring to scan the codebase for automatically resolving dependency requirements of the classes containing @Autowired annotation.
Spring 2.5 also adds support for JSR-250 annotations such as @Resource, @PostConstruct, and @PreDestroy.Use of these annotations also requires that certain BeanPostProcessors be registered within the Spring container. As always, these can be registered as individual bean definitions, but they can also be implicitly registered by including <context:annotation-config>
tag in spring configuration.
Taken from Spring documentation of Annotation Based Configuration
Spring provides the capability of automatically detecting 'stereotyped' classes and registering corresponding BeanDefinitions with the ApplicationContext.
According to javadoc of org.springframework.stereotype:
Stereotypes are Annotations denoting the roles of types or methods in the overall architecture (at a conceptual, rather than implementation, level). Example: @Controller @Service @Repository etc. These are intended for use by tools and aspects (making an ideal target for pointcuts).
To autodetect such 'stereotype' classes, <context:component-scan>
tag is required.
The <context:component-scan>
tag also tells Spring to scan the code for injectable beans under the package (and all its subpackages) specified.
Enqueue means to add an element, dequeue to remove an element.
var stackInput= []; // First stack
var stackOutput= []; // Second stack
// For enqueue, just push the item into the first stack
function enqueue(stackInput, item) {
return stackInput.push(item);
}
function dequeue(stackInput, stackOutput) {
// Reverse the stack such that the first element of the output stack is the
// last element of the input stack. After that, pop the top of the output to
// get the first element that was ever pushed into the input stack
if (stackOutput.length <= 0) {
while(stackInput.length > 0) {
var elementToOutput = stackInput.pop();
stackOutput.push(elementToOutput);
}
}
return stackOutput.pop();
}
Just have your view controller register for the UIApplicationWillEnterForegroundNotification
notification and react accordingly.
The behaviour is not really that strange. Looking into the implementation of the classes, it is caused by:
Charset.defaultCharset()
is not caching the determined character set in Java 5.Charset.defaultCharset()
again causes a second evaluation of the system property, no character set with the name "Latin-1" is found, so Charset.defaultCharset()
defaults to "UTF-8".OutputStreamWriter
is however caching the default character set and is probably used already during VM initialization, so that its default character set diverts from Charset.defaultCharset()
if the system property "file.encoding" has been changed at runtime.As already pointed out, it is not documented how the VM must behave in such a situation. The Charset.defaultCharset()
API documentation is not very precise on how the default character set is determined, only mentioning that it is usually done on VM startup, based on factors like the OS default character set or default locale.
Late, but:
In addition to the DEFAULT_FROM_EMAIL
fix others have mentioned, and allowing less-secure apps to access the account, I had to navigate to https://accounts.google.com/DisplayUnlockCaptcha while signed in as the account in question to get Django to finally authenticate.
I went to that URL through a SSH tunnel to the web server to make sure the IP address was the same; I'm not totally sure if that's necessary but it can't hurt. You can do that like so: ssh -D 8080 -fN <username>@<host>
, then set your web browser to use localhost:8080
as a SOCKS proxy.
It the case of HashSet, it does NOT replace it.
From the docs:
http://docs.oracle.com/javase/6/docs/api/java/util/HashSet.html#add(E)
"Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false."
<input type="file">
with a <label>
tag;<span>
or <a>
;input[type="file"]
invisible via display: none
.In typical usage (responses<2GB) it is not necessary to Dispose the HttpResponseMessages.
The return types of the HttpClient methods should be Disposed if their Stream Content is not fully Read. Otherwise there is no way for the CLR to know those Streams can be closed until they are garbage collected.
If you set the HttpCompletionOption to ResponseHeadersRead or the response is larger than 2GB, you should clean up. This can be done by calling Dispose on the HttpResponseMessage or by calling Dispose/Close on the Stream obtained from the HttpResonseMessage Content or by reading the content completely.
Whether you call Dispose on the HttpClient depends on whether you want to cancel pending requests or not.
EmailData clsEmailData = new EmailData();
List<EmailData> lstemail = new List<EmailData>();
clsEmailData.FirstName="JOhn";
clsEmailData.LastName ="Smith";
clsEmailData.Location ="Los Angeles"
lstemail.add(clsEmailData);
I have found the same thing as suggested above by a few folks. If you focus()
first, then push the val()
into the input, the cursor will get positioned to the end of the input value in Firefox,Chrome and IE. If you push the val()
into the input field first, Firefox and Chrome position the cursor at the end, but IE positions it to the front when you focus()
.
$('element_identifier').focus().val('some_value')
should do the trick (it always has for me anyway).
Use the formaction
HTML attribute (5th line):
<form action="/action_page.php" method="get">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<button type="submit">Submit</button><br>
<button type="submit" formaction="/action_page2.php">Submit to another page</button>
</form>
In some cases this also occurs if you have table hints and you have spaces between WITH clause and your hint, so best to type it like:
SELECT Column1 FROM Table1 t1 WITH(NOLOCK)
INNER JOIN Table2 t2 WITH(NOLOCK) ON t1.Column1 = t2.Column1
And not:
SELECT Column1 FROM Table1 t1 WITH (NOLOCK)
INNER JOIN Table2 t2 WITH (NOLOCK) ON t1.Column1 = t2.Column1
CSS rules are inherited by default - hence the "cascading" name. To get what you want you need to use !important:
form div
{
font-size: 12px;
font-weight: bold;
}
div.content
{
// any rule you want here, followed by !important
}
I have used Newtonsoft JSON.NET (Documentation) It allows you to create a class / object, populate the fields, and serialize as JSON.
public class ReturnData
{
public int totalCount { get; set; }
public List<ExceptionReport> reports { get; set; }
}
public class ExceptionReport
{
public int reportId { get; set; }
public string message { get; set; }
}
string json = JsonConvert.SerializeObject(myReturnData);
try to change the order: right click on you project-> BuildPath->Configure...->Order and Export tab -> move jre7 UP.
Normally, it should work.
But can you try this? I don't have SQL on my home PC, I can't try myself
UPDATE table
SET EndDate = '2009-05-25 00:00:00.000'
WHERE Id = 1
ClassLoader.class.getResourceAsStream("/path/file.ext");
I've created a plunker based off of the answers here and elsewhere.
Additionally I had to add an @Input
, @ViewChild
, and ElementRef
of the <input>
and create and subscribe()
to an observable of it.
Angular2 Search Filter: PLUNKR (UPDATE: plunker no longer works)
If you are using zsh terminal do the following:
1) Open .zprofile file with the editor of your choice like "open -a xcode ~/.zprofile"
2) Add new PATH or Env Variable in .zprofile Save the file and quit the editor.
3) Execute your .zprofile to update your PATH: source ~/.zprofile
While all the answers above circulate around the same fundamental idea and you can get it to work with simple layouts using one of the examples above. However I wanted to change the color of the background while using sliding 'full screen' (tab bar aside) fragment navigation and maintain regular navigation, tab and action bars.
After reading carefully an article by Anton Hadutski I had better understanding what is going on.
I have DrawerLayout
with ConstraintLayout
(i.e. container) which has Toolbar
, include for the main fragment and BottomNavigationView
.
Setting DrawerLayout
having fitsSystemWindows
to true isn't sufficient, you need to set both DrawerLayout
and ConstraintLayout
. Assuming transparent status bar, the status bar color is now the same as the background color of ConstraintLayout
.
However, the included fragment has still the status bar inset, so animating another 'full screen' fragment on top of with doesn't change the color of the status bar.
A bit of code from the referred article into Activity
's onCreate
:
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.container)) { view, insets ->
insets.replaceSystemWindowInsets(
insets.systemWindowInsetLeft,
0,
insets.systemWindowInsetRight,
insets.systemWindowInsetBottom
)
}
And all is good, except now the Toolbar
doesn't address the status bar height. Some more referring to the article and we have a fully working solution:
val toolbar = findViewById<Toolbar>(R.id.my_toolbar)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.container)) { view, insets ->
val params = toolbar.layoutParams as ViewGroup.MarginLayoutParams
params.topMargin = insets.systemWindowInsetTop
toolbar.layoutParams = params
insets.replaceSystemWindowInsets(
insets.systemWindowInsetLeft,
0,
insets.systemWindowInsetRight,
insets.systemWindowInsetBottom
)
}
The main_activity.xml (please note that marginTop in Toolbar
is for preview purposes, it will be replaced by the code):
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/green"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="@+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_constraintTop_toTopOf="@id/container"
android:layout_marginTop="26dp"
android:background="@android:color/transparent"
...>
...
</androidx.appcompat.widget.Toolbar>
<include layout="@layout/content_main" />
...
</androidx.constraintlayout.widget.ConstraintLayout>
...
</androidx.drawerlayout.widget.DrawerLayout>
The CLSID you describe is for the Microsoft.Office.Interop.Excel.ApplicationClass. This class basically launches excel.exe through InprocServer32. If you don't have it installed then it will return the error message you received above.
join
takes an iterable thing as an argument. Usually it's a list. The problem in your case is that a string is itself iterable, giving out each character in turn. Your code breaks down to this:
"wlfgALGbXOahekxSs".join("595")
which acts the same as this:
"wlfgALGbXOahekxSs".join(["5", "9", "5"])
and so produces your string:
"5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5"
Strings as iterables is one of the most confusing beginning issues with Python.
I had the same problem once. Calling invalidate after changing visibility almost always works, but in some cases it doesn't. I had to cheat and set the background to a transparent image and set the text to "".
If you already have a test class, but missing the JUnit library dependency, please refer to Configuring Libraries for Unit Testing documentation section. Pressing Alt+Enter on the red code should give you an intention action to add the missing jar.
However, IDEA offers much more. If you don't have a test class yet and want to create one for any of the source classes, see instructions below.
You can use the Create Test intention action by pressing Alt+Enter while standing on the name of your class inside the editor or by using Ctrl+Shift+T keyboard shortcut.
A dialog appears where you select what testing framework to use and press Fix button for the first time to add the required library jars to the module dependencies. You can also select methods to create the test stubs for.
You can find more details in the Testing help section of the on-line documentation.
In your Case you can write the following jquery code:
$(document).ready(function(){
$('.staff_on_site').click(function(){
var rBtnVal = $(this).val();
if(rBtnVal == "yes"){
$("#no_of_staff").attr("readonly", false);
}
else{
$("#no_of_staff").attr("readonly", true);
}
});
});
Here is the Fiddle: http://jsfiddle.net/P4QWx/3/
Why do you want to reinvent the wheel when there are opensource that are already doing the job pretty nicely.
Both apache common-langs and spring support some very flexible builder pattern
For apache, here is how you do it reflectively
@Override
public String toString()
{
return ToStringBuilder.reflectionToString(this);
}
Here is how you do it if you only want to print fields that you care about.
@Override
public String toString()
{
return new ToStringBuilder(this)
.append("name", name)
.append("location", location)
.append("address", address)
.toString();
}
You can go as far as "styling" your print output with non-default ToStringStyle or even customizing it with your own style.
I didn't personally try spring ToStringCreator api, but it looks very similar.
For the line breaks i edited your code to get something with no line breaks.
#!/bin/bash
for i in /Users/anthonykiggundu/Sites/rku-it/*; do
t=$(stat -f "%Sm" -t "%Y-%m-%d %H:%M" "$i")
echo $t : "${i##*/}" # t only contains date last modified, then only filename 'grokked'- else $i alone is abs. path
done
What you can do is @Autowired
a setter method and have it set a new static field.
public class Boo {
@Autowired
Foo foo;
static Foo staticFoo;
@Autowired
public void setStaticFoo(Foo foo) {
Boo.staticFoo = foo;
}
public static void randomMethod() {
staticFoo.doStuff();
}
}
When the bean gets processed, Spring will inject a Foo
implementation instance into the instance field foo
. It will then also inject the same Foo
instance into the setStaticFoo()
argument list, which will be used to set the static field.
This is a terrible workaround and will fail if you try to use randomMethod()
before Spring has processed an instance of Boo
.
return false;
return false;
does 3 separate things when you call it:
event.preventDefault()
– It stops the browsers default behaviour.event.stopPropagation()
– It prevents the event from propagating (or “bubbling up”) the DOM.Note that this behaviour differs from normal (non-jQuery) event handlers, in which, notably, return false
does not stop the event from bubbling up.
preventDefault();
preventDefault();
does one thing: It stops the browsers default behaviour.
When to use them?
We know what they do but when to use them? Simply it depends on what you want to accomplish. Use preventDefault();
if you want to “just” prevent the default browser behaviour. Use return false; when you want to prevent the default browser behaviour and prevent the event from propagating the DOM. In most situations where you would use return false; what you really want is preventDefault()
.
Examples:
Let’s try to understand with examples:
We will see pure JAVASCRIPT example
Example 1:
<div onclick='executeParent()'>_x000D_
<a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
function executeChild() {_x000D_
alert('Link Clicked');_x000D_
}_x000D_
_x000D_
function executeParent() {_x000D_
alert('div Clicked');_x000D_
}_x000D_
</script>
_x000D_
Run the above code you will see the hyperlink ‘Click here to visit stackoverflow.com‘ now if you click on that link first you will get the javascript alert Link Clicked Next you will get the javascript alert div Clicked and immediately you will be redirected to stackoverflow.com.
Example 2:
<div onclick='executeParent()'>_x000D_
<a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
function executeChild() {_x000D_
event.preventDefault();_x000D_
event.currentTarget.innerHTML = 'Click event prevented'_x000D_
alert('Link Clicked');_x000D_
}_x000D_
_x000D_
function executeParent() {_x000D_
alert('div Clicked');_x000D_
}_x000D_
</script>
_x000D_
Run the above code you will see the hyperlink ‘Click here to visit stackoverflow.com‘ now if you click on that link first you will get the javascript alert Link Clicked Next you will get the javascript alert div Clicked Next you will see the hyperlink ‘Click here to visit stackoverflow.com‘ replaced by the text ‘Click event prevented‘ and you will not be redirected to stackoverflow.com. This is due > to event.preventDefault() method we used to prevent the default click action to be triggered.
Example 3:
<div onclick='executeParent()'>_x000D_
<a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
function executeChild() {_x000D_
event.stopPropagation();_x000D_
event.currentTarget.innerHTML = 'Click event prevented'_x000D_
alert('Link Clicked');_x000D_
}_x000D_
_x000D_
function executeParent() {_x000D_
alert('div Clicked');_x000D_
}_x000D_
</script>
_x000D_
This time if you click on Link the function executeParent() will not be called and you will not get the javascript alert div Clicked this time. This is due to us having prevented the propagation to the parent div using event.stopPropagation() method. Next you will see the hyperlink ‘Click here to visit stackoverflow.com‘ replaced by the text ‘Click event is going to be executed‘ and immediately you will be redirected to stackoverflow.com. This is because we haven’t prevented the default click action from triggering this time using event.preventDefault() method.
Example 4:
<div onclick='executeParent()'>_x000D_
<a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
function executeChild() {_x000D_
event.preventDefault();_x000D_
event.stopPropagation();_x000D_
event.currentTarget.innerHTML = 'Click event prevented'_x000D_
alert('Link Clicked');_x000D_
}_x000D_
_x000D_
function executeParent() {_x000D_
alert('Div Clicked');_x000D_
}_x000D_
</script>
_x000D_
If you click on the Link, the function executeParent() will not be called and you will not get the javascript alert. This is due to us having prevented the propagation to the parent div using event.stopPropagation() method. Next you will see the hyperlink ‘Click here to visit stackoverflow.com‘ replaced by the text ‘Click event prevented‘ and you will not be redirected to stackoverflow.com. This is because we have prevented the default click action from triggering this time using event.preventDefault() method.
Example 5:
For return false I have three examples and all appear to be doing the exact same thing (just returning false), but in reality the results are quite different. Here's what actually happens in each of the above.
cases:
Will see all three example.
<div onclick='executeParent()'>_x000D_
<a href='https://stackoverflow.com' onclick='return false'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
var link = document.querySelector('a');_x000D_
_x000D_
link.addEventListener('click', function() {_x000D_
event.currentTarget.innerHTML = 'Click event prevented using inline html'_x000D_
alert('Link Clicked');_x000D_
});_x000D_
_x000D_
_x000D_
function executeParent() {_x000D_
alert('Div Clicked');_x000D_
}_x000D_
</script>
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>_x000D_
<a href='https://stackoverflow.com'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
$('a').click(function(event) {_x000D_
alert('Link Clicked');_x000D_
$('a').text('Click event prevented using return FALSE');_x000D_
$('a').contents().unwrap();_x000D_
return false;_x000D_
});_x000D_
$('div').click(function(event) {_x000D_
alert('Div clicked');_x000D_
});_x000D_
</script>
_x000D_
<div onclick='executeParent()'>_x000D_
<a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
function executeChild() {_x000D_
event.currentTarget.innerHTML = 'Click event prevented'_x000D_
alert('Link Clicked');_x000D_
return false_x000D_
}_x000D_
_x000D_
function executeParent() {_x000D_
alert('Div Clicked');_x000D_
}_x000D_
</script>
_x000D_
Hope these examples are clear. Try executing all these examples in a html file to see how they work.
In my case, the argument type was different in the header file and .cpp file. In the header file the type was std::wstring
and in the .cpp file it was LPCWSTR
.
This is so called file local variables, that are understood by Emacs and set correspondingly. See corresponding section in Emacs manual - you can define them either in header or in footer of file
Ok. I had to add. One line implementation for those who already have Spring and Apache Commons dependency or are planning to add it:
DigestUtils.md5DigestAsHex(FileUtils.readFileToByteArray(file))
For and Apache commons only option (credit @duleshi):
DigestUtils.md5Hex(FileUtils.readFileToByteArray(file))
Hope this helps someone.
Maybe you are looking for something like this?
>>> class MyTest:
def __init__ (self):
self.value = 3
>>> myobj = MyTest()
>>> myobj.__dict__
{'value': 3}
I answered a similar question for log4j see how-can-i-test-with-junit-that-a-warning-was-logged-with-log4
This is newer and example with Log4j2 (tested with 2.11.2) and junit 5;
package com.whatever.log;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.core.*;
import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginElement;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
class TestLogger {
private TestAppender testAppender;
private LoggerConfig loggerConfig;
private final Logger logger = (Logger)
LogManager.getLogger(ClassUnderTest.class);
@Test
@DisplayName("Test Log Junit5 and log4j2")
void test() {
ClassUnderTest.logMessage();
final LogEvent loggingEvent = testAppender.events.get(0);
//asset equals 1 because log level is info, change it to debug and
//the test will fail
assertTrue(testAppender.events.size()==1,"Unexpected empty log");
assertEquals(Level.INFO,loggingEvent.getLevel(),"Unexpected log level");
assertEquals(loggingEvent.getMessage().toString()
,"Hello Test","Unexpected log message");
}
@BeforeEach
private void setup() {
testAppender = new TestAppender("TestAppender", null);
final LoggerContext context = logger.getContext();
final Configuration configuration = context.getConfiguration();
loggerConfig = configuration.getLoggerConfig(logger.getName());
loggerConfig.setLevel(Level.INFO);
loggerConfig.addAppender(testAppender,Level.INFO,null);
testAppender.start();
context.updateLoggers();
}
@AfterEach
void after(){
testAppender.stop();
loggerConfig.removeAppender("TestAppender");
final LoggerContext context = logger.getContext();
context.updateLoggers();
}
@Plugin( name = "TestAppender", category = Core.CATEGORY_NAME, elementType = Appender.ELEMENT_TYPE)
static class TestAppender extends AbstractAppender {
List<LogEvent> events = new ArrayList();
protected TestAppender(String name, Filter filter) {
super(name, filter, null);
}
@PluginFactory
public static TestAppender createAppender(
@PluginAttribute("name") String name,
@PluginElement("Filter") Filter filter) {
return new TestAppender(name, filter);
}
@Override
public void append(LogEvent event) {
events.add(event);
}
}
static class ClassUnderTest {
private static final Logger LOGGER = (Logger) LogManager.getLogger(ClassUnderTest.class);
public static void logMessage(){
LOGGER.info("Hello Test");
LOGGER.debug("Hello Test");
}
}
}
Using the following maven dependencies
<dependency>
<artifactId>log4j-core</artifactId>
<packaging>jar</packaging>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.5.0</version>
<scope>test</scope>
</dependency>
function GetCookieValue(name) {
var found = document.cookie.split(';').filter(c => c.trim().split("=")[0] === name);
return found.length > 0 ? found[0].split("=")[1] : null;
}
Use the Count(*) analytic function OVER PARTITION BY NULL This will count the total # of rows
After more exploration and testing, it appears that this issue was being caused by debugging the plugin and using breakpoints. SVN/Subclipse apparently didn't like having breakpoints midway through their execution and as a result this lock files were being created. As soon as I started just running the plugin, this issue disappeared.
<TextView
android:id="@+id/phoneNumber"
android:autoLink="phone"
android:linksClickable="true"
android:text="+91 22 2222 2222"
/>
This is how you can open EditText label assigned number on dialer directly.
Yes -- the X509Store.Certificates
property returns a snapshot of the X.509 certificate store.
Update only works on updating querysets. If you want to update multiple fields at the same time, say from a dict for a single object instance you can do something like:
obj.__dict__.update(your_dict)
obj.save()
Bear in mind that your dictionary will have to contain the correct mapping where the keys need to be your field names and the values the values you want to insert.
Seems PyAudio is supported by Python 2.7, 3.4, 3.5, and 3.6. Refer https://people.csail.mit.edu/hubert/pyaudio/
Please suggest if there is any alternate way to install PyAudio on Python 3.8.2
Welcome to the wonderful world of Angular !!
I am very new to angularJS. I am searching for accessing services from RESTful API but I didn't get any idea. please help me to do that. Thank you
There are two (very big) hurdles to writing your first Angular scripts, if you're currently using 'GET' services.
First, your services must implement the "Access-Control-Allow-Origin" property, otherwise the services will work a treat when called from, say, a web browser, but fail miserably when called from Angular.
So, you'll need to add a few lines to your web.config file:
<configuration>
...
<system.webServer>
<httpErrors errorMode="Detailed"/>
<validation validateIntegratedModeConfiguration="false"/>
<!-- We need the following 6 lines, to let AngularJS call our REST web services -->
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Content-Type"/>
</customHeaders>
</httpProtocol>
</system.webServer>
...
</configuration>
Next, you need to add a little bit of code to your HTML file, to force Angular to call 'GET' web services:
// Make sure AngularJS calls our WCF Service as a "GET", rather than as an "OPTION"
var myApp = angular.module('myApp', []);
myApp.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
Once you have these fixes in place, actually calling a RESTful API is really straightforward.
function YourAngularController($scope, $http)
{
$http.get('http://www.iNorthwind.com/Service1.svc/getAllCustomers')
.success(function (data) {
//
// Do something with the data !
//
});
}
You can find a really clear walkthrough of these steps on this webpage:
Good luck !
Mike
As explained by Ron, there are two variables, local and global. The local variable is always used, and is the same as global upon connection.
SET FOREIGN_KEY_CHECKS=0;
SET GLOBAL FOREIGN_KEY_CHECKS=0;
SHOW Variables WHERE Variable_name='foreign_key_checks'; # always shows local variable
When setting the GLOBAL variable, the local one isn't changed for any existing connections. You need to reconnect or set the local variable too.
Perhaps unintuitive, MYSQL does not enforce foreign keys when FOREIGN_KEY_CHECKS are re-enabled. This makes it possible to create an inconsistent database even though foreign keys and checks are on.
If you want your foreign keys to be completely consistent, you need to add the keys while checking is on.
In Netbeans you can right click on the project and run it, but in IntelliJ IDEA you have to select the index.jsp file or the welcome file to run the project.
this is because Netbeans generate the following tag in web.xml and IntelliJ do not.
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
You have to give the path to jdk ...typically C:\Program Files\Java.. Still if it is asking you for the path then Check this http://www.shellperson.net/oracle-sql-developer-enter-the-full-pathname-for-java-exe/
I had similar issue with c#, first I found that each project may have a few different types. i.e. in .csproject file locate ProjectTypeGuids, it should be a few guids, i.e.
<ProjectTypeGuids>{F85E285D-A4E0-4152-9332-AB1D724D3325};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
they will point on component you are missing. In my case it was ASP.NET MVC 2. Some guys get it worked by installing MVC 2 destribution.
My case was worse, because installation didn't work, but it turned out that it was because I had Express 2008 and 2010. I fixed it by uninstalling both 2008 & 2010 and installing only 2010 versions. For c# you need both Visual C# Express and Visual Web Developer express
Perhaps involve the activity's life-cycle methods to achieve this:
Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler.post(sendData);
}
@Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(sendData);
}
private final Runnable sendData = new Runnable(){
public void run(){
try {
//prepare and send the data here..
handler.postDelayed(this, 1000);
}
catch (Exception e) {
e.printStackTrace();
}
}
};
In this approach, if you press back-key on your activity or call finish();
, it will also stop the postDelayed callings.
Add the following css to disable the default scroll:
body {
overflow: hidden;
}
And change the #content
css to this to make the scroll only on content body:
#content {
max-height: calc(100% - 120px);
overflow-y: scroll;
padding: 0px 10%;
margin-top: 60px;
}
Edit:
Actually, I'm not sure what was the issue you were facing, since it seems that your css is working. I have only added the HTML and the header css statement:
html {_x000D_
height: 100%;_x000D_
}_x000D_
html body {_x000D_
height: 100%;_x000D_
overflow: hidden;_x000D_
}_x000D_
html body .container-fluid.body-content {_x000D_
position: absolute;_x000D_
top: 50px;_x000D_
bottom: 30px;_x000D_
right: 0;_x000D_
left: 0;_x000D_
overflow-y: auto;_x000D_
}_x000D_
header {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
right: 0;_x000D_
top: 0;_x000D_
background-color: #4C4;_x000D_
height: 50px;_x000D_
}_x000D_
footer {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
background-color: #4C4;_x000D_
height: 30px;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<header></header>_x000D_
<div class="container-fluid body-content">_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
</div>_x000D_
<footer></footer>
_x000D_
ConcurrentLinkedQueue
uses a lock-free queue (based off the newer CAS instruction).
I need to click the link who's href has substring "long" in it. How can I do this?
With the beauty of CSS selectors.
your statement would be...
driver.findElement(By.cssSelector("a[href*='long']")).click();
This means, in english,
Find me any 'a' elements, that have the
href
attribute, and that attributecontains
'long'
You can find a useful article about formulating your own selectors for automation effectively, as well as a list of all the other equality operators. contains
, starts with
, etc... You can find that at: http://ddavison.io/css/2014/02/18/effective-css-selectors.html
Also it's possible to avoid using JavaScript for drop-down effect, and use CSS3 transition, by adding this small piece of code to your style:
.dropdown .dropdown-menu {
-webkit-transition: all 0.3s;
-moz-transition: all 0.3s;
-ms-transition: all 0.3s;
-o-transition: all 0.3s;
transition: all 0.3s;
max-height: 0;
display: block;
overflow: hidden;
opacity: 0;
}
.dropdown.open .dropdown-menu { /* For Bootstrap 4, use .dropdown.show instead of .dropdown.open */
max-height: 300px;
opacity: 1;
}
The only problem with this way is that you should manually specify max-height. If you set a very big value, your animation will be very quick.
It works like a charm if you know the approximate height of your dropdowns, otherwise you still can use javascript to set a precise max-height value.
Here is small example: DEMO
! There is small bug with padding in this solution, check Jacob Stamm's comment with solution.
Greg is right-- you can use sys.stdout.write
Perhaps, though, you should consider refactoring your algorithm to accumulate a list of <whatevers> and then
lst = ['h', 'm']
print "".join(lst)
I think this will do:
Dim filename As String
filename = Application.GetOpenFilename
Replace this:
var cat = $.jqURL.get('category');
var $dd = $('#cbCategory');
var $options = $('option', $dd);
$options.each(function() {
if ($(this).text() == cat)
$(this).select(); // This is where my problem is
});
With this:
$('#cbCategory').val(cat);
Calling val()
on a select list will automatically select the option with that value, if any.
From man 1 pkill
-f The pattern is normally only matched against the process name.
When -f is set, the full command line is used.
Which means, for example, if we see these lines in ps aux
:
apache 24268 0.0 2.6 388152 27116 ? S Jun13 0:10 /usr/sbin/httpd
apache 24272 0.0 2.6 387944 27104 ? S Jun13 0:09 /usr/sbin/httpd
apache 24319 0.0 2.6 387884 27316 ? S Jun15 0:04 /usr/sbin/httpd
We can kill them all using the pkill -f
option:
pkill -f httpd
You can't. If you have a method called isBiggerThanMaxLong(long)
it should always return false
.
If you were to increment the bits of Long.MAX_VALUE
, the next value should be Long.MIN_VALUE
. Read up on twos-complement and that should tell you why.
Adding a class to Html.EditorFor
doesn't make sense as inside its template you could have many different tags. So you need to assign the class inside the editor template:
@Html.EditorFor(x => x.Created)
and in the custom template:
<div>
@Html.TextBoxForModel(x => x.Created, new { @class = "date" })
</div>
The XPath turns into this:
Get me all of the div elements that have an id equal to container.
As for getting the first etc, you have two options.
Turn it into a .findElement()
- this will just return the first one for you anyway.
or
To explicitly do this in XPath, you'd be looking at:
(//div[@id='container'])[1]
for the first one, for the second etc:
(//div[@id='container'])[2]
Then XPath has a special indexer, called last, which would (you guessed it) get you the last element found:
(//div[@id='container'])[last()]
Worth mentioning that XPath indexers will start from 1 not 0 like they do in most programming languages.
As for getting the parent 'node', well, you can use parent:
//div[@id='container']/parent::*
That would get the div's direct parent.
You could then go further and say I want the first *div* with an id of container, and I want his parent:
(//div[@id='container'])[1]/parent::*
Hope that helps!
Use the second argument on the Mockito.verify
method, as in:
Mockito.verify(dependency, Mockito.times(0)).someMethod()
Here's the answer I found:
Just to make the definition complete, in the Cartesian coordinate system:
The conversion is:
x = R * cos(lat) * cos(lon)
y = R * cos(lat) * sin(lon)
z = R *sin(lat)
Where R is the approximate radius of earth (e.g. 6371 km).
If your trigonometric functions expect radians (which they probably do), you will need to convert your longitude and latitude to radians first. You obviously need a decimal representation, not degrees\minutes\seconds (see e.g. here about conversion).
The formula for back conversion:
lat = asin(z / R)
lon = atan2(y, x)
asin is of course arc sine. read about atan2 in wikipedia. Don’t forget to convert back from radians to degrees.
This page gives c# code for this (note that it is very different from the formulas), and also some explanation and nice diagram of why this is correct,
You may want to try compiling with Facebook's HipHop.
It does a static analysis on the entire project and may be what you're looking for.
To script this:
pid=$(lsof -ti tcp:8080)
if [[ $pid ]]; then
kill -9 $pid
fi
The -t
argument makes the output of lsof "terse" which means that it only returns the PID.
Try this simple code! (it is self explanatory)
import tensorflow as tf
sess = tf.InteractiveSession() # see the answers above :)
x = [[1.,2.,1.],[1.,1.,1.]] # a 2D matrix as input to softmax
y = tf.nn.softmax(x) # this is the softmax function
# you can have anything you like here
u = y.eval()
print(u)
Use System.Windows.Forms.SystemInformation.UserName
for the actually logged in user as Environment.UserName
still returns the account being used by the current process.
I assume you are loading the XML from an external file. With $.ajax()
, it's quite simple actually:
$.ajax({
url: 'xmlfile.xml',
dataType: 'xml',
success: function(data){
// Extract relevant data from XML
var xml_node = $('Pages',data);
console.log( xml_node.find('Page[Name="test"] > controls > test').text() );
},
error: function(data){
console.log('Error loading XML data');
}
});
Also, you should be consistent about the XML node naming. You have both lowercase and capitalized node names (<Page>
versus <page>
) which can be confusing when you try to use XML tree selectors.
In order to build a more-or-less reliable list of applications that appear in the "Programs and Feautres" in the Control Panel, you have to consider that not all applications were installed using MSI. WMI only provides the ones installed with MSI.
Here is a short summary of what I've found out:
MSI applications always have a Product Code (GUID) subkey under HKLM\...\Uninstall
and/or under HKLM\...\Installer\UserData\S-1-5-18\Products
. In addition, they may have a key that looks like HKLM\...\Uninstall\NotAGuid
.
Non-MSI applications do not have a product code, and therefore have keys like HKLM\...\Uninstall\NotAGuid
or HKCU\...\Uninstall\NotAGuid
.
Use active class with label to make it auto select and use checked=""
.
<label class="btn btn-primary active" value="regular" style="width:47%">
<input type="radio" name="service" checked="" > Regular </label>
<label class="btn btn-primary " value="express" style="width:46%">
<input type="radio" name="service"> Express </label>
You create a form with hidden inputs that hold the values to be posted, set the action of the form to the destination url, and the form method to post. Then, when your link is clicked, trigger a JS function that submits the form.
See here, for an example. This example uses pure JavaScript, with no jQuery — you could choose this if you don't want to install anything more than you already have.
<form name="myform" action="handle-data.php" method="post">
<label for="query">Search:</label>
<input type="text" name="query" id="query"/>
<button>Search</button>
</form>
<script>
var button = document.querySelector('form[name="myform"] > button');
button.addEventListener(function() {
document.querySelector("form[name="myform"]").submit();
});
</script>
To me, it sounds like you want to create a new attribute? Do you want
<option value="2" value2="somethingElse">...
To do this, you can do
$(your selector).attr('value2', 'the value');
And then to retrieve it, you can use
$(your selector).attr('value2')
It's not going to be valid code, but I guess it does the job.
Just want to add these back slashes to previous answers, I am on Windows 10 CMD, and it doesn't work without back slashes before the spaces.
git config --global core.editor "C:\\Users\\your_user_name\\AppData\\Local\\Programs\\Microsoft\ VS\ Code\\Code.exe"
I'd rather use static widths and if you'd like your page to resize depending on screen size, you can have a look at media queries.
Or, you can set a min-width on elements like header, navigation, content etc.
As an even easier solution, you could just use:
$results = $objects.Name
Which should fill $results
with an array of all the 'Name' property values of the elements in $objects
.
Have you had a look at getcwd()
?
#include <unistd.h>
char *getcwd(char *buf, size_t size);
Simple example:
#include <unistd.h>
#include <stdio.h>
#include <limits.h>
int main() {
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
printf("Current working dir: %s\n", cwd);
} else {
perror("getcwd() error");
return 1;
}
return 0;
}
The .join()
method has a parameter for the separator string. If you want it to be empty instead of the default comma, use
arr.join("");
The markdown syntax for displaying images is indeed:
![image](https://{url})
BUT: How to provide the url
?
So... you can use this awesome trick to make github host your image file. TDLR:
http://solutionoptimist.com/2013/12/28/awesome-github-tricks/
Powershell one liner:
$p='HKLM:\SOFTWARE\JavaSoft\Java Development Kit'; $v=(gp $p).CurrentVersion; (gp $p/$v).JavaHome
When you create an App, a file called styles.xml will be created in your res/values folder. If you change the styles, you can change the background, text color, etc for all your layouts. That way you don’t have to go into each individual layout and change the it manually.
styles.xml:
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="Theme.AppBaseTheme" parent="@android:style/Theme.Light">
<item name="android:editTextColor">#295055</item>
<item name="android:textColorPrimary">#295055</item>
<item name="android:textColorSecondary">#295055</item>
<item name="android:textColorTertiary">#295055</item>
<item name="android:textColorPrimaryInverse">#295055</item>
<item name="android:textColorSecondaryInverse">#295055</item>
<item name="android:textColorTertiaryInverse">#295055</item>
<item name="android:windowBackground">@drawable/custom_background</item>
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>
parent="@android:style/Theme.Light"
is Google’s native colors. Here is a reference of what the native styles are:
https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/res/res/values/themes.xml
The default Android style is also called “Theme”. So you calling it Theme probably confused the program.
name="Theme.AppBaseTheme"
means that you are creating a style that inherits all the styles from parent="@android:style/Theme.Light"
.
This part you can ignore unless you want to inherit from AppBaseTheme again. = <style name="AppTheme" parent="AppBaseTheme">
@drawable/custom_background is a custom image I put in the drawable’s folder. It is a 300x300 png image.
#295055 is a dark blue color.
My code changes the background and text color. For Button text, please look through Google’s native stlyes (the link I gave u above).
Then in Android Manifest, remember to include the code:
<application
android:theme="@style/Theme.AppBaseTheme">
This is what worked for me for the associative array:
/*
* Inserts a new key/value after the key in the array.
*
* @param $key
* The key to insert after.
* @param $array
* An array to insert in to.
* @param $new_key
* The key to insert.
* @param $new_value
* An value to insert.
*
* @return
* The new array if the key exists, FALSE otherwise.
*
* @see array_insert_before()
*/
function array_insert_after($key, array &$array, $new_key, $new_value) {
if (array_key_exists($key, $array)) {
$new = array();
foreach ($array as $k => $value) {
$new[$k] = $value;
if ($k === $key) {
$new[$new_key] = $new_value;
}
}
return $new;
}
return FALSE;
}
The function source - this blog post. There's also handy function to insert BEFORE specific key.
You can try something like this
r = requests.get(ENDPOINT, params=params, headers={'Authorization': 'Basic %s' % API_KEY})
That entire block is misplaced.
class Example(object):
def main(self):
print "Hello World!"
if __name__ == '__main__':
Example().main()
But you really shouldn't be using a class just to run your main code.
I also like using qdapTools::lookup
or shorthand binary operator %l%
. It works identically to an Excel vlookup, but it accepts name arguments opposed to column numbers
## Replicate Ben's data:
hous <- structure(list(HouseType = c("Semi", "Single", "Row", "Single",
"Apartment", "Apartment", "Row"), HouseTypeNo = c(1L, 2L, 3L,
2L, 4L, 4L, 3L)), .Names = c("HouseType", "HouseTypeNo"),
class = "data.frame", row.names = c(NA, -7L))
largetable <- data.frame(HouseType = as.character(sample(unique(hous$HouseType),
1000, replace = TRUE)), stringsAsFactors = FALSE)
## It's this simple:
library(qdapTools)
largetable[, 1] %l% hous
pyspark.sql.functions.split()
is the right approach here - you simply need to flatten the nested ArrayType column into multiple top-level columns. In this case, where each array only contains 2 items, it's very easy. You simply use Column.getItem()
to retrieve each part of the array as a column itself:
split_col = pyspark.sql.functions.split(df['my_str_col'], '-')
df = df.withColumn('NAME1', split_col.getItem(0))
df = df.withColumn('NAME2', split_col.getItem(1))
The result will be:
col1 | my_str_col | NAME1 | NAME2
-----+------------+-------+------
18 | 856-yygrm | 856 | yygrm
201 | 777-psgdg | 777 | psgdg
I am not sure how I would solve this in a general case where the nested arrays were not the same size from Row to Row.
object.__del__(self)
is called when the instance is about to be destroyed.
>>> class Test:
... def __del__(self):
... print "deleted"
...
>>> test = Test()
>>> del test
deleted
Object is not deleted unless all of its references are removed(As quoted by ethan)
Also, From Python official doc reference:
del x doesn’t directly call x.del() — the former decrements the reference count for x by one, and the latter is only called when x‘s reference count reaches zero
According to Apple documentation
Example :
var myObject = NSDate()
let futureDate = myObject.dateByAddingTimeInterval(10)
let timeSinceNow = myObject.timeIntervalSinceNow
If you're using Anaconda to manage Python on your system, you can install it with:
$ conda install pyqt=4
Omit the =4
to install the most current version.
Answer from How to install PyQt4 in anaconda?
If you want to move the file in new path with keep original file name. use this:
$source_file = 'foo/image.jpg';
$destination_path = 'bar/';
rename($source_file, $destination_path . pathinfo($source_file, PATHINFO_BASENAME));
Well.. I'm not sure how portable os.chdir('..') would actually be. Under Unix those are real filenames. I would prefer the following:
import os
os.chdir(os.path.dirname(os.getcwd()))
That gets the current working directory, steps up one directory, and then changes to that directory.
1) If the object is created via a pointer and that pointer is later deleted or given a new address to point to, does the object that it was pointing to call its destructor (assuming nothing else is pointing to it)?
It depends on the type of pointers. For example, smart pointers often delete their objects when they are deleted. Ordinary pointers do not. The same is true when a pointer is made to point to a different object. Some smart pointers will destroy the old object, or will destroy it if it has no more references. Ordinary pointers have no such smarts. They just hold an address and allow you to perform operations on the objects they point to by specifically doing so.
2) Following up on question 1, what defines when an object goes out of scope (not regarding to when an object leaves a given {block}). So, in other words, when is a destructor called on an object in a linked list?
That's up to the implementation of the linked list. Typical collections destroy all their contained objects when they are destroyed.
So, a linked list of pointers would typically destroy the pointers but not the objects they point to. (Which may be correct. They may be references by other pointers.) A linked list specifically designed to contain pointers, however, might delete the objects on its own destruction.
A linked list of smart pointers could automatically delete the objects when the pointers are deleted, or do so if they had no more references. It's all up to you to pick the pieces that do what you want.
3) Would you ever want to call a destructor manually?
Sure. One example would be if you want to replace an object with another object of the same type but don't want to free memory just to allocate it again. You can destroy the old object in place and construct a new one in place. (However, generally this is a bad idea.)
// pointer is destroyed because it goes out of scope,
// but not the object it pointed to. memory leak
if (1) {
Foo *myfoo = new Foo("foo");
}
// pointer is destroyed because it goes out of scope,
// object it points to is deleted. no memory leak
if(1) {
Foo *myfoo = new Foo("foo");
delete myfoo;
}
// no memory leak, object goes out of scope
if(1) {
Foo myfoo("foo");
}
Try going to Project -> Properties -> Java Build Path -> Order & Export
And Confirm Android Private Libraries are checked for your project and for all other library projects you are using in your Application.
From what you've said so far, it sounds like a problem where the MySQL driver in PHP5.3 has trouble connecting to the older MySQL version 4.1. Have a look on http://www.bitshop.com/Blogs/tabid/95/EntryId/67/PHP-mysqlnd-cannot-connect-to-MySQL-4-1-using-old-authentication.aspx
There's a similar question here with some useful answers, Cannot connect to MySQL 4.1+ using old authentication
SELECT `User`, `Host`, Length(`Password`) FROM mysql.user
This will return 16 for accounts with old passwords and 41 for accounts with new passwords (and 0 for accounts with no password at all, you might want to take care of those as well). Either use the user managements tools of the MySQL front end (if there are any) or
SET PASSWORD FOR 'User'@'Host'=PASSWORD('yourpassword');
FLUSH Privileges
Based on your suggestion original suggestion (setting negative margins), I have tried and come up with a similar method using percentage units for dynamic browser width:
HTML
<div class="grandparent">
<div class="parent">
<div class="child">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolore neque repellat ipsum natus magni soluta explicabo architecto, molestias laboriosam rerum. Tempore eos labore temporibus alias necessitatibus illum enim, est harum perspiciatis, sit, totam earum corrupti placeat architecto aut minus dignissimos mollitia asperiores sint ea. Libero hic laudantium, ipsam nostrum earum distinctio. Cum expedita, ratione, accusamus dicta similique distinctio est dolore assumenda soluta dolorem quisquam ex possimus aliquid provident quo? Enim tempora quo cupiditate eveniet aperiam.</p>
</div>
</div>
</div>
CSS:
.child-div{
margin: 0 -100%;
padding: 0 -100%;
}
.parent {
width: 60%;
background-color: red;
margin: 0 auto;
padding: 50px;
position:relative;
}
.grandparent {
overflow-x:hidden;
background-color: blue;
width: 100%;
position:relative;
}
The negative margins will let the content flow out of the Parent DIV. Therefore I set the padding: 0 100%;
to push the content back to the original boundaries of the Chlid DIV.
The negative margins will also make the .child-div's total width expands out of the browser's viewport, resulting in a horizontal scroll. Hence we need to clip the extruding width by applying an overflow-x: hidden
to a Grandparent DIV (which is the parent of the Parent Div):
Here is the JSfiddle
I haved tried Nils Kaspersson's left: calc(-50vw + 50%)
; it worked perfectly fine in Chrome & FF (not sure about IE yet) until I found out Safari browsers doesn't do it properly. Hope they fixed this soon as I actually like this simple method.
This also may resolve your issue where the Parent DIV element has to be position:relative
The 2 drawbacks of this workaround method is:
Please let me know if there's any issue you find with this method ;). Hope it helps.
For people running Android Studio
and Eclipse
:
I know that answers are already saturated, but I'll just add that it appears that this error surfaces after installing Android Studio and returning to Eclipse to build and run your project.
Make sure you close all other instances of ADB that may be running (including Android Studio). Once you've done this if you are still having troubles try killing all ADB server processes and restarting. If you haven't setup a global variable, open terminal and navigate to the platform-tools folder of the Android SDK Eclipse is referencing, then run:
./adb kill-server
./adb start-server
I had a case where I was entering text into a field after which the text would be removed automatically. Turned out it was due to some site functionality where you had to press the enter key after entering the text into the field. So, after sending your barcode text with sendKeys method, send 'enter' directly after it. Note that you will have to import the selenium Keys class. See my code below.
import org.openqa.selenium.Keys;
String barcode="0000000047166";
WebElement element_enter = driver.findElement(By.xpath("//*[@id='div-barcode']"));
element_enter.findElement(By.xpath("your xpath")).sendKeys(barcode);
element_enter.sendKeys(Keys.RETURN); // this will result in the return key being pressed upon the text field
I hope it helps..
Nikita's point is an excellent one: don't confuse mature with bad. XML hasn't changed much.
JDOM would be another alternative to DOM4J.
This is confusing. When you say "form object", do you mean "<select>
element"? If not, your code won't work, so I'll assume your form
variable is in fact a reference to a <select>
element. Why do you want to rewrite this code? What you have has worked in all scriptable browsers since around 1996, and won't stop working any time soon. Doing it with jQuery will immediately make your code slower, more error-prone and less compatible across browsers.
Here's a function that uses your current code as a starting point and populates a <select>
element from an object:
<select id="mySelect"></select>
<script type="text/javascript>
function populateSelect(select, optionsData) {
var options = select.options, o, selected;
options.length = 0;
for (var i = 0, len = optionsData.length; i < len; ++i) {
o = optionsData[i];
selected = !!o.selected;
options[i] = new Option(o.text, o.value, selected, selected);
}
}
var optionsData = [
{
text: "Select a city / town in Sweden",
value: ""
},
{
text: "Melbourne",
value: "Melbourne",
selected: true
}
];
populateSelect(document.getElementById("mySelect"), optionsData);
</script>
Faced this exact issue. The problem resolved when i changed the Service="Namespace.ServiceName" tag in the Markup (right click xxxx.svc and select View Markup in visual studio) to match the namespace i used for my xxxx.svc.cs file
The pg documentation at NOTES say
The path will be interpreted relative to the working directory of the server process (normally the cluster's data directory), not the client's working directory.
So, gerally, using psql
or any client, even in a local server, you have problems ... And, if you're expressing COPY command for other users, eg. at a Github README, the reader will have problems ...
The only way to express relative path with client permissions is using STDIN,
When STDIN or STDOUT is specified, data is transmitted via the connection between the client and the server.
as remembered here:
psql -h remotehost -d remote_mydb -U myuser -c \
"copy mytable (column1, column2) from STDIN with delimiter as ','" \
< ./relative_path/file.csv
your question makes no sense. you are asking how to turn a hash into an array. You cant.
you can make a list of values, or make a list of keys, and neither of these have anything to do with jquery, this is pure javascript
(Previously known as node-webkit)
I would suggest NW.js if you are familiar with Node or experienced with JavaScript.
NW.js is an app runtime based on Chromium and node.js.
Features
- Apps written in modern HTML5, CSS3, JS and WebGL
- Complete support for Node.js APIs and all its third party modules.
- Good performance: Node and WebKit run in the same thread: Function calls are made straightforward; objects are in the same heap and can just reference each other
- Easy to package and distribute apps
- Available on Linux, Mac OS X and Windows
You can find the NW.js repo here, and a good introduction to NW.js here. If you fancy learning Node.js I would recommend this SO post with a lot of good links.
Using Spring for Android with RestTemplate https://spring.io/guides/gs/consuming-rest-android/
// The connection URL
String url = "https://ajax.googleapis.com/ajax/" +
"services/search/web?v=1.0&q={query}";
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();
// Add the String message converter
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
// Make the HTTP GET request, marshaling the response to a String
String result = restTemplate.getForObject(url, String.class, "Android");
where returns ActiveRecord::Relation
Now take a look at find_by implementation:
def find_by
where(*args).take
end
As you can see find_by is the same as where but it returns only one record. This method should be used for getting 1 record and where should be used for getting all records with some conditions.
you can try using this
System.Web.HttpContext.Current.Server.MapPath(path);
or use HostingEnvironment.MapPath
System.Web.Hosting.HostingEnvironment.MapPath(path);
I have the same problem now , I have foreign key and i need put it as nullable, to solve this problem you should put
modelBuilder.Entity<Country>()
.HasMany(c => c.Users)
.WithOptional(c => c.Country)
.HasForeignKey(c => c.CountryId)
.WillCascadeOnDelete(false);
in DBContext class I am sorry for answer you very late :)
private static Scanner in;
I fixed it by declaring in as a private static Scanner class variable. Not sure why that fixed it but that is what eclipse recommended I do.
I updated to use ContextCompat.getColor(context, R.color.your_color);
but sometimes (On some devices/Android versions. I'm not sure) that causes a NullPointerExcepiton.
So to make it work on all devices/versions, I fall back on the old way of doing it, in the case of a null pointer.
try {
textView.setTextColor(ContextCompat.getColor(getActivity(), R.color.text_grey_dark));
}
catch(NullPointerException e) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
textView.setTextColor(getContext().getColor(R.color.text_grey_dark));
}
else {
textView.setTextColor(getResources().getColor(R.color.text_grey_dark));
}
}
This script will help you switch Gopaths. https://github.com/buffonomics/goswitch
Just to give an update, there are minor changes for Visual Studio 2015 users.
To use or install package manually, go to Tools -> Options -> NuGet Package Manager -> Package Sources
Click the Add button, choose the Source, and don't forget to click "Update" as it will update the folder location for your packages, edit your desired Name of your package source if you want:
To choose your added package, right click your solution and select "Manage Nuget Packages"
The drop down list is on the right and choose Browse to browse your packages that you specified on your folder source. If there is no nuget package on that folder source, this will be empty:
I got pretty good results with my HTML mailing list by using the following:
p { margin-bottom: 0; }
ul { margin-top: 0; }
This does not reset all margin values but only those that create such a gap before ordered list, and still doesn't assume anything about default margin values.
At least with Xcode 6, you already have git-completion.bash
. It's inside the Xcode app bundle.
Just add this to your .bashrc:
source `xcode-select -p`/usr/share/git-core/git-completion.bash
Estimated sanjan:
The idea behind Dijkstra's Algorithm is to explore all the nodes of the graph in an ordered way. The algorithm stores a priority queue where the nodes are ordered according to the cost from the start, and in each iteration of the algorithm the following operations are performed:
It's true that the algorithm calculates the cost of the path between the start (A in your case) and all the rest of the nodes, but you can stop the exploration of the algorithm when it reaches the goal (Z in your example). At this point you know the cost between A and Z, and the path connecting them.
I recommend you to use a library which implements this algorithm instead of coding your own. In Java, you might take a look to the Hipster library, which has a very friendly way to generate the graph and start using the search algorithms.
Here you have an example of how to define the graph and start using Dijstra with Hipster.
// Create a simple weighted directed graph with Hipster where
// vertices are Strings and edge values are just doubles
HipsterDirectedGraph<String,Double> graph = GraphBuilder.create()
.connect("A").to("B").withEdge(4d)
.connect("A").to("C").withEdge(2d)
.connect("B").to("C").withEdge(5d)
.connect("B").to("D").withEdge(10d)
.connect("C").to("E").withEdge(3d)
.connect("D").to("F").withEdge(11d)
.connect("E").to("D").withEdge(4d)
.buildDirectedGraph();
// Create the search problem. For graph problems, just use
// the GraphSearchProblem util class to generate the problem with ease.
SearchProblem p = GraphSearchProblem
.startingFrom("A")
.in(graph)
.takeCostsFromEdges()
.build();
// Search the shortest path from "A" to "F"
System.out.println(Hipster.createDijkstra(p).search("F"));
You only have to substitute the definition of the graph for your own, and then instantiate the algorithm as in the example.
I hope this helps!