You can add the src
folder to build path by:
- Select Java perspective.
- Right click on
src
folder. - Select Build Path > Use a source folder.
And you are done. Hope this help.
EDIT: Refer to the Eclipse documentation
I had a similar problem and found that it was because I had a similarly named public property (that should have been private) that only differed in case.
public string PropertyName {get;set;} // actually set propertyName, get propertyName
public string propertyName {get;set;}
should have been
public string PropertyName {get;set;}
private string propertyName {get;set;}
add javax.xml.bind dependency in pom.xml
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
By latest document, you can use rdd.collect().foreach(println) on the driver to display all, but it may cause memory issues on the driver, best is to use rdd.take(desired_number)
https://spark.apache.org/docs/2.2.0/rdd-programming-guide.html
To print all elements on the driver, one can use the collect() method to first bring the RDD to the driver node thus: rdd.collect().foreach(println). This can cause the driver to run out of memory, though, because collect() fetches the entire RDD to a single machine; if you only need to print a few elements of the RDD, a safer approach is to use the take(): rdd.take(100).foreach(println).
Newer versions of datetimepicker (I'm using is use 2.3.7) use format:"Y/m/d"
not dateFormat...
so
jQuery('#timePicker').datetimepicker({
format: 'd-m-y',
value: new Date()
});
You won't be able to do it in a single replacement; you'll have to perform a few steps. Here's how I'd do it:
Find (in regular expression mode):
(.+)
Replace with:
"\1"
This adds the quotes:
"AliceBlue"
"AntiqueWhite"
"Aqua"
"Aquamarine"
"Azure"
"Beige"
"Bisque"
"Black"
"BlanchedAlmond"
Find (in extended mode):
\r\n
Replace with (with a space after the comma, not shown):
,
This converts the lines into a comma-separated list:
"AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond"
Add the var myArray =
assignment and braces manually:
var myArray = ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond"];
If you don't know its key it means it doesn't matter.
You could place the value as the key, it means it will instantly find the value. Better than using searching in all elements over and over again.
$messages=array();
$messages[312] = 312;
$messages[401] = 401;
$messages[1599] = 1599;
$messages[3] = 3;
unset($messages[3]); // no search needed
I usually use this little collection of extension methods:
public static class EnumerableExtension
{
public static T PickRandom<T>(this IEnumerable<T> source)
{
return source.PickRandom(1).Single();
}
public static IEnumerable<T> PickRandom<T>(this IEnumerable<T> source, int count)
{
return source.Shuffle().Take(count);
}
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
{
return source.OrderBy(x => Guid.NewGuid());
}
}
For a strongly typed list, this would allow you to write:
var strings = new List<string>();
var randomString = strings.PickRandom();
If all you have is an ArrayList, you can cast it:
var strings = myArrayList.Cast<string>();
For people looking at a simpler solution, I think you can just have this one line of code in
onStart()
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
It's called Immersive mode. You may look at the official documentation for other possibilities.
The two structs are different. When you initialize the first struct, about 40 bytes of memory are allocated. When you initialize the second struct, about 10 bytesof memory are allocated. (Actual amount is architecture dependent)
You can use the string literals (string constants) to initalize character arrays. This is why
person p = {"John", "Doe",30};
works in the first example.
You cannot assign (in the conventional sense) a string in C.
The string literals you have ("John") are loaded into memory when your code executes. When you initialize an array with one of these literals, then the string is copied into a new memory location. In your second example, you are merely copying the pointer to (location of) the string literal. Doing something like:
char* string = "Hello";
*string = 'C'
might cause compile or runtime errors (I am not sure.) It is a bad idea because you are modifying the literal string "Hello" which, for example on a microcontroler, could be located in read-only memory.
POJO:- POJO is a Java object not bound by any restriction other than those forced by the Java Language Specification.
Properties of POJO
Example of POJO
public class POJO {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
if you want to remove pagination and but want ordering of dataTable then add this script at the end of your page!
<script>_x000D_
$(document).ready(function() { _x000D_
$('#table_id').DataTable({_x000D_
"paging": false,_x000D_
"info": false_x000D_
} );_x000D_
_x000D_
} );_x000D_
</script>
_x000D_
Well the thing is that you probably actually don't want the test to run indefinitely. You just want to wait a longer amount of time before the library decides the element doesn't exist. In that case, the most elegant solution is to use implicit wait, which is designed for just that:
driver.manage().timeouts().implicitlyWait( ... )
For using dictionary object in typescript you can use interface as below:
interface Dictionary<T> {
[Key: string]: T;
}
and, use this for your class property type.
export class SearchParameters {
SearchFor: Dictionary<string> = {};
}
to use and initialize this class,
getUsers(): Observable<any> {
var searchParams = new SearchParameters();
searchParams.SearchFor['userId'] = '1';
searchParams.SearchFor['userName'] = 'xyz';
return this.http.post(searchParams, 'users/search')
.map(res => {
return res;
})
.catch(this.handleError.bind(this));
}
I'm not sure how far it will get you, but you can execute JavaScript one line at a time from the Developer Tool Console.
You could use timeit like this to test a script named module.py
$ python -mtimeit -s 'import module'
Do not use { display:none; }
It makes the content inaccessible. You want screen-readers to see your content, and visually style it by replacing the text with an image (like a logo). By using text-indent: -999px;
or a similar method, the text is still there — just not visually there. Use display:none
, and the text is gone.
Create a file named python2.7.reg
(registry file) and put this content into it:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7]
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\Help]
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\Help\MainPythonDocumentation]
@="C:\\Python27\\Doc\\python26.chm"
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\InstallPath]
@="C:\\Python27\\"
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\InstallPath\InstallGroup]
@="Python 2.7"
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\Modules]
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\PythonPath]
@="C:\\Python27\\Lib;C:\\Python27\\DLLs;C:\\Python27\\Lib\\lib-tk"
And make sure every path is right!
Then run (merge) it and done :)
{% for days in days_list %}
<h2># Day {{ forloop.counter }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
{% endfor %}
or if you want to start from 0
{% for days in days_list %}
<h2># Day {{ forloop.counter0 }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
{% endfor %}
I would break up
public static void main(String args[])
in parts:
public
It means that you can call this method from outside of the class you are currently in. This is necessary because this method is being called by the Java runtime system which is not located in your current class.
static
When the JVM makes call to the main method there is no object existing for the class being called therefore it has to have static method to allow invocation from class.
void
Java is platform independent language and if it will return some value then the value may mean different things to different platforms. Also there are other ways to exit the program on a multithreaded system. Detailed explaination.
main
It's just the name of method. This name is fixed and as it's called by the JVM as entry point for an application.
String args[]
These are the arguments of type String that your Java application accepts when you run it.
Because of the way jQuery selectors are evaluated right-to-left, the quite readable li:not(:first)
is slowed down by that evaluation.
An equally fast and easy to read solution is using the function version .not(":first")
:
e.g.
$("li").not(":first").hide();
JSPerf: http://jsperf.com/fastest-way-to-select-all-expect-the-first-one/6
This is only few percentage points slower than slice(1)
, but is very readable as "I want all except the first one".
I know it's not an exact answer to the OP, but as answers have already be given...
Do you really need to do this in PHP ?
What I mean is : if you need to convert a lot of images, doing it in PHP might not be the best way : you'll be confronted to memory_limit
, max_execution_time
, ...
I would also say GD might not get you the best quality/size ratio ; but not sure about that (if you do a comparison between GD and other solutions, I am very interested by the results ;-) )
Another approach, not using PHP, would be to use Image Magick via the command line (and not as a PHP extension like other people suggested)
You'd have to write a shell-script that goes through all .png
files, and gives them to either
convert
to create a new .jpg
file for each .png
filemogrify
to directly work on the original file and override it.
As a sidenote : if you are doing this directly on your production server, you could put some sleep time between bunches of conversions, to let it cool down a bit sometimes ^^
I've use the shell script + convert
/mogrify
a few times (having them run for something like 10 hours one time), and they do the job really well :-)
\d
is called a character class and will match digits. It is equal to [0-9]
.
+
matches 1 or more occurrences of the character before.
So \d+
means match 1 or more digits.
If you're more comfortable PCRE regex syntax, which
you have [g]vim compiled with perl feature, test using
:ver and inspect features; if +perl is there you're good to go)
try search/replace using
:perldo s///
Example. Swap src and alt attributes in img tag:
<p class="logo"><a href="/"><img src="/caminoglobal_en/includes/themes/camino/images/header_logo.png" alt=""></a></p>
:perldo s/(src=".*?")\s+(alt=".*?")/$2 $1/
<p class="logo"><a href="/"><img alt="" src="/caminoglobal_en/includes/themes/camino/images/header_logo.png"></a></p>
I noticed that I get this error when I'm working on a new computer if I try to build from the command line first. However, if I build from Android Studio, it retrieves the SDK and creates the directory automatically. Then when I build from the command line it works.
The
<a href="image2.gif" ><img src="image1.gif"/></a>
technique has always worked for me. I used it to good effect in my Super Bowl diary, but I see that the scripts I used are broken. Once I get them fixed I will edit in the URL.
If the javascript file is loaded from the admin dashboard, this javascript function will give you the root of your WordPress installation. I use this a lot when I'm building plugins that need to make ajax requests from the admin dashboard.
function getHomeUrl() {
var href = window.location.href;
var index = href.indexOf('/wp-admin');
var homeUrl = href.substring(0, index);
return homeUrl;
}
Example code:
class inside:
def __init__(self):
self.l = []
def insert(self, element):
self.l.append(element)
class outside:
l = [] # static variable - the same for all instances
def insert(self, element):
self.l.append(element)
def main():
x = inside()
x.insert(8)
print(x.l) # [8]
y = inside()
print(y.l) # []
# ----------------------------
x = outside()
x.insert(8)
print(x.l) # [8]
y = outside()
print(y.l) # [8] # here is the difference
if __name__ == '__main__':
main()
I used
getContext().getApplicationContext().getString(R.string.nameOfString);
It works for me.
I think it's worth pointing out that jQuery sorts this out nicely with $.each()
.
See: .each()
Example:
$('.foo').each(function() {
console.log($(this));
});
$(this)
being the single item inside the object. Swap $('.foo')
to a variable if you don't want to use jQuery's selector engine.
This worked for me, setting up Googles nameserver because no standard nameserver was specified, followed by restarting networking:
sudo echo "dns-nameservers 8.8.8.8" >> /etc/network/interfaces && sudo ifdown venet0:0 && sudo ifup venet0:0
Try the following:
<a asp-controller="Users" asp-action="Index"></a>
(Valid for ASP.NET 5 and MVC 6)
df = data.frame(matrix("", ncol = 3, nrow = 10)
This OTN-thread contains several ways to do string aggregation, including a performance comparison: http://forums.oracle.com/forums/message.jspa?messageID=1819487#1819487
The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.
The way you get your original array back is by using Convert.FromBase64String
:
byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);
I recently wanted to solve for a similar issue and constructed a small function to color only keywords i cared about which were easily identifiable by surrounding curly braces {keyword}
.
This worked like a charm:
var text = 'some text with some {special} formatting on this {keyword} and this {keyword}'
var splitText = text.split(' ');
var cssRules = [];
var styledText = '';
_.each(splitText, (split) => {
if (/^\{/.test(split)) {
cssRules.push('color:blue');
} else {
cssRules.push('color:inherit')
}
styledText += `%c${split} `
});
console.log(styledText , ...cssRules)
technically you could swap out the if statement with a switch/case statement to allow multiple stylings for different reasons
Wrap the Parallel.Foreach
into a Task.Run()
and instead of the await
keyword use [yourasyncmethod].Result
(you need to do the Task.Run thing to not block the UI thread)
Something like this:
var yourForeachTask = Task.Run(() =>
{
Parallel.ForEach(ids, i =>
{
ICustomerRepo repo = new CustomerRepo();
var cust = repo.GetCustomer(i).Result;
customers.Add(cust);
});
});
await yourForeachTask;
When you're analyzing code, you have to analyse it line by line, counting every operation/recognizing time complexity, in the end, you have to sum it to get whole picture.
For example, you can have one simple loop with linear complexity, but later in that same program you can have a triple loop that has cubic complexity, so your program will have cubic complexity. Function order of growth comes into play right here.
Let's look at what are possibilities for time complexity of an algorithm, you can see order of growth I mentioned above:
Constant time has an order of growth 1
, for example: a = b + c
.
Logarithmic time has an order of growth LogN
, it usually occurs
when you're dividing something in half (binary search, trees, even loops), or multiplying something in same way.
Linear, order of growth is N
, for example
int p = 0;
for (int i = 1; i < N; i++)
p = p + 2;
Linearithmic, order of growth is n*logN
, usually occurs in divide and conquer algorithms.
Cubic, order of growth N^3
, classic example is a triple loop where you check all triplets:
int x = 0;
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
for (int k = 0; k < N; k++)
x = x + 2
Exponential, order of growth 2^N
, usually occurs when you do exhaustive search, for example check subsets of some set.
The right way is to execute npm update
. It's a really powerful command, it updates the missing packages and also checks if a newer version of package already installed can be used.
Read Intro to NPM to understand what you can do with npm.
Use this html code it will surely help you
<input type="button" value="NEXT" onclick="document.write('<?php //call a function here ex- 'fun();' ?>');" />
one limitation is that it is taking more time to run so wait for few seconds it will work
It's a really old topic but as it still comes up top in search results:
Nowadays you can add additional class fa-fw
to set it fixed width.
Example:
<i class="fa fa-pencil fa-fw" aria-hidden="true"></i>
I think you should simply use $breed->setSpecies($species)
, for instance in my form I have:
$m = new Member();
$m->setBirthDate(new \DateTime);
$form = $this->createForm(new MemberType, $m);
and that sets my default selection to the current date. Should work the same way for external entities...
If you are looking for a more generalized way to apply to many columns, what you can do is to build a list of column names and pass it as the index of the grouped dataframe. In your case, for example:
columns = ['Y'+str(i) for year in range(1967, 2011)]
df.groupby('Country')[columns].agg('sum')
Fetch the KeyListener value of EditText
by editText.getKeyListener()
and store in the KeyListener type variable, which will contain
the Editable property value:
KeyListener variable;
variable = editText.getKeyListener();
Set the Editable property of EditText
to false as:
edittext.setKeyListener(null);
Now set Editable property of EditText
to true as:
editText.setKeyListener(variable);
Note: In XML the default Editable property of EditText
should be true.
The Arrays
class has versions of sort()
and binarySearch()
which don't require a Comparator.
For example, you can use the version of Arrays.sort()
which just takes an array of objects. These methods call the compareTo()
method of the objects in the array.
Do the following:
<html>
)This is a hacky way, but it's the easiest way to do this.
You could declare one or more of your targets to be phony.
A phony target is one that is not really the name of a file; rather it is just a name for a recipe to be executed when you make an explicit request. There are two reasons to use a phony target: to avoid a conflict with a file of the same name, and to improve performance.
...
A phony target should not be a prerequisite of a real target file; if it is, its recipe will be run every time make goes to update that file. As long as a phony target is never a prerequisite of a real target, the phony target recipe will be executed only when the phony target is a specified goal
What platform does the path come from? Windows paths are different from POSIX paths are different from Mac OS 9 paths are different from RISC OS paths are different...
If it's a web app where the filename can come from different platforms there is no one solution. However a reasonable stab is to use both '\' (Windows) and '/' (Linux/Unix/Mac and also an alternative on Windows) as path separators. Here's a non-RegExp version for extra fun:
var leafname= pathname.split('\\').pop().split('/').pop();
I have just experienced this issue in one of my MySQL db's and I looked at the phpMyAdmin answer here. However the best way I fixed it in phpMyAdmin was in the affected table, drop the id column and make a fresh/new id column (adding A-I -autoincrement-). This restored my table id correctly-simples! Hope that helps (no MySQL code needed-I hope to learn to use that but later!) anyone else with this problem.
#include <string.h>
...
char otherString[6]; // note 6, not 5, there's one there for the null terminator
...
strncpy(otherString, someString, 5);
otherString[5] = '\0'; // place the null terminator
intersect_all <- function(a,b,...){
all_data <- c(a,b,...)
require(plyr)
count_data<- length(list(a,b,...))
freq_dist <- count(all_data)
intersect_data <- freq_dist[which(freq_dist$freq==count_data),"x"]
intersect_data
}
intersect_all(a,b,c)
UPDATE EDIT A simpler code
intersect_all <- function(a,b,...){
Reduce(intersect, list(a,b,...))
}
intersect_all(a,b,c)
The two options I use are:
list1.AddRange(list2);
or
list1.Concat(list2);
However I noticed as I used that when using the AddRange
method with a recursive function, that calls itself very often I got an SystemOutOfMemoryException because the maximum number of dimensions was reached.
(Message Google Translated)
The array dimensions exceeded the supported range.
Using Concat
solved that issue.
This is because You're sorting entire result-set, You should sort, every part of union separately, or You can use ORDER BY (Something ie. subquery distance) THEN (something ie row id) clause
You can use the build in CLLocationDistance to calculate this:
CLLocation *location1 = [[CLLocation alloc] initWithLatitude:latitude1 longitude:longitude1];
CLLocation *location2 = [[CLLocation alloc] initWithLatitude:latitude2 longitude:longitude2];
[self distanceInMetersFromLocation:location1 toLocation:location2]
- (int)distanceInMetersFromLocation:(CLLocation*)location1 toLocation:(CLLocation*)location2 {
CLLocationDistance distanceInMeters = [location1 distanceFromLocation:location2];
return distanceInMeters;
}
In your case if you want kilometers just divide by 1000.
from itertools import chain, repeat
prompts = chain(["Enter a number: "], repeat("Not a number! Try again: "))
replies = map(input, prompts)
valid_response = next(filter(str.isdigit, replies))
print(valid_response)
Enter a number: a
Not a number! Try again: b
Not a number! Try again: 1
1
or if you want to have a "bad input" message separated from an input prompt as in other answers:
prompt_msg = "Enter a number: "
bad_input_msg = "Sorry, I didn't understand that."
prompts = chain([prompt_msg], repeat('\n'.join([bad_input_msg, prompt_msg])))
replies = map(input, prompts)
valid_response = next(filter(str.isdigit, replies))
print(valid_response)
Enter a number: a
Sorry, I didn't understand that.
Enter a number: b
Sorry, I didn't understand that.
Enter a number: 1
1
prompts = chain(["Enter a number: "], repeat("Not a number! Try again: "))
This combination of itertools.chain
and itertools.repeat
will create an iterator
which will yield strings "Enter a number: "
once, and "Not a number! Try again: "
an infinite number of times:
for prompt in prompts:
print(prompt)
Enter a number:
Not a number! Try again:
Not a number! Try again:
Not a number! Try again:
# ... and so on
replies = map(input, prompts)
- here map
will apply all the prompts
strings from the previous step to the input
function. E.g.:
for reply in replies:
print(reply)
Enter a number: a
a
Not a number! Try again: 1
1
Not a number! Try again: it doesn't care now
it doesn't care now
# and so on...
filter
and str.isdigit
to filter out those strings that contain only digits:
only_digits = filter(str.isdigit, replies)
for reply in only_digits:
print(reply)
Enter a number: a
Not a number! Try again: 1
1
Not a number! Try again: 2
2
Not a number! Try again: b
Not a number! Try again: # and so on...
And to get only the first digits-only string we use next
.String methods: Of course you can use other string methods like str.isalpha
to get only alphabetic strings, or str.isupper
to get only uppercase. See docs for the full list.
Membership testing:
There are several different ways to perform it. One of them is by using __contains__
method:
from itertools import chain, repeat
fruits = {'apple', 'orange', 'peach'}
prompts = chain(["Enter a fruit: "], repeat("I don't know this one! Try again: "))
replies = map(input, prompts)
valid_response = next(filter(fruits.__contains__, replies))
print(valid_response)
Enter a fruit: 1
I don't know this one! Try again: foo
I don't know this one! Try again: apple
apple
Numbers comparison:
There are useful comparison methods which we can use here. For example, for __lt__
(<
):
from itertools import chain, repeat
prompts = chain(["Enter a positive number:"], repeat("I need a positive number! Try again:"))
replies = map(input, prompts)
numeric_strings = filter(str.isnumeric, replies)
numbers = map(float, numeric_strings)
is_positive = (0.).__lt__
valid_response = next(filter(is_positive, numbers))
print(valid_response)
Enter a positive number: a
I need a positive number! Try again: -5
I need a positive number! Try again: 0
I need a positive number! Try again: 5
5.0
Or, if you don't like using dunder methods (dunder = double-underscore), you can always define your own function, or use the ones from the operator
module.
Path existance:
Here one can use pathlib
library and its Path.exists
method:
from itertools import chain, repeat
from pathlib import Path
prompts = chain(["Enter a path: "], repeat("This path doesn't exist! Try again: "))
replies = map(input, prompts)
paths = map(Path, replies)
valid_response = next(filter(Path.exists, paths))
print(valid_response)
Enter a path: a b c
This path doesn't exist! Try again: 1
This path doesn't exist! Try again: existing_file.txt
existing_file.txt
If you don't want to torture a user by asking him something an infinite number of times, you can specify a limit in a call of itertools.repeat
. This can be combined with providing a default value to the next
function:
from itertools import chain, repeat
prompts = chain(["Enter a number:"], repeat("Not a number! Try again:", 2))
replies = map(input, prompts)
valid_response = next(filter(str.isdigit, replies), None)
print("You've failed miserably!" if valid_response is None else 'Well done!')
Enter a number: a
Not a number! Try again: b
Not a number! Try again: c
You've failed miserably!
Sometimes we don't want to reject an input if the user accidentally supplied it IN CAPS or with a space in the beginning or an end of the string. To take these simple mistakes into account we can preprocess the input data by applying str.lower
and str.strip
methods. For example, for the case of membership testing the code will look like this:
from itertools import chain, repeat
fruits = {'apple', 'orange', 'peach'}
prompts = chain(["Enter a fruit: "], repeat("I don't know this one! Try again: "))
replies = map(input, prompts)
lowercased_replies = map(str.lower, replies)
stripped_replies = map(str.strip, lowercased_replies)
valid_response = next(filter(fruits.__contains__, stripped_replies))
print(valid_response)
Enter a fruit: duck
I don't know this one! Try again: Orange
orange
In the case when you have many functions to use for preprocessing, it might be easier to use a function performing a function composition. For example, using the one from here:
from itertools import chain, repeat
from lz.functional import compose
fruits = {'apple', 'orange', 'peach'}
prompts = chain(["Enter a fruit: "], repeat("I don't know this one! Try again: "))
replies = map(input, prompts)
process = compose(str.strip, str.lower) # you can add more functions here
processed_replies = map(process, replies)
valid_response = next(filter(fruits.__contains__, processed_replies))
print(valid_response)
Enter a fruit: potato
I don't know this one! Try again: PEACH
peach
For a simple case, for example, when the program asks for age between 1 and 120, one can just add another filter
:
from itertools import chain, repeat
prompt_msg = "Enter your age (1-120): "
bad_input_msg = "Wrong input."
prompts = chain([prompt_msg], repeat('\n'.join([bad_input_msg, prompt_msg])))
replies = map(input, prompts)
numeric_replies = filter(str.isdigit, replies)
ages = map(int, numeric_replies)
positive_ages = filter((0).__lt__, ages)
not_too_big_ages = filter((120).__ge__, positive_ages)
valid_response = next(not_too_big_ages)
print(valid_response)
But in the case when there are many rules, it's better to implement a function performing a logical conjunction. In the following example I will use a ready one from here:
from functools import partial
from itertools import chain, repeat
from lz.logical import conjoin
def is_one_letter(string: str) -> bool:
return len(string) == 1
rules = [str.isalpha, str.isupper, is_one_letter, 'C'.__le__, 'P'.__ge__]
prompt_msg = "Enter a letter (C-P): "
bad_input_msg = "Wrong input."
prompts = chain([prompt_msg], repeat('\n'.join([bad_input_msg, prompt_msg])))
replies = map(input, prompts)
valid_response = next(filter(conjoin(*rules), replies))
print(valid_response)
Enter a letter (C-P): 5
Wrong input.
Enter a letter (C-P): f
Wrong input.
Enter a letter (C-P): CDE
Wrong input.
Enter a letter (C-P): Q
Wrong input.
Enter a letter (C-P): N
N
Unfortunately, if someone needs a custom message for each failed case, then, I'm afraid, there is no pretty functional way. Or, at least, I couldn't find one.
One thing I found is the path of your image must be relative to wherever the notebook was originally loaded from. if you cd to a different directory, such as Pictures your Markdown path is still relative to the original loading directory.
This may be a Chrome bug. Unfortunately Chrome routinely breaks debugging. It often has some kind of memory leak and it often breaks or changes every few releases.
Debugging with formatted sources is currently extremely unreliable.
It's possible you're also trying to break on dead code.
To be certain it's not the browser you should also try to debug it in firefox.
I use system properties in log4j.xml:
...
<param name="File" value="${catalina.home}/logs/root.log"/>
...
and start tests with:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<configuration>
<systemProperties>
<property>
<name>catalina.home</name>
<value>${project.build.directory}</value>
</property>
</systemProperties>
</configuration>
</plugin>
Putting together several answers from above, this is what I ended up using:
var validationErrors = ModelState.Values.Where(E => E.Errors.Count > 0)
.SelectMany(E => E.Errors)
.Select(E => E.ErrorMessage)
.ToList();
validationErrors
ends up being a List<string>
that contains each error message. From there, it's easy to do what you want with that list.
You have to use the viewWithTag
function to find the view with the given tag
.
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let touch = touches.anyObject() as UITouch
let point = touch.locationInView(self.view)
if let viewWithTag = self.view.viewWithTag(100) {
print("Tag 100")
viewWithTag.removeFromSuperview()
} else {
print("tag not found")
}
}
Here's what you can do if you have a NavigableSet
(e.g. a TreeSet
):
public static <E> E get(NavigableSet<E> set, E key) {
return set.tailSet(key, true).floor(key);
}
The things are slightly trickier for HashSet
and its descendants like LinkedHashSet
:
import java.util.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Test {
private static final Field mapField;
private static final Method hashMethod;
private static final Method getNodeMethod;
private static final Field keyField;
static {
try {
mapField = HashSet.class.getDeclaredField("map");
mapField.setAccessible(true);
hashMethod = HashMap.class.getDeclaredMethod("hash", Object.class);
hashMethod.setAccessible(true);
getNodeMethod = HashMap.class.getDeclaredMethod("getNode",
Integer.TYPE, Object.class);
getNodeMethod.setAccessible(true);
keyField = Class.forName("java.util.HashMap$Node").getDeclaredField("key");
keyField.setAccessible(true);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
public static <E> E get(HashSet<E> set, E key) {
try {
Object map = mapField.get(set);
Object hash = hashMethod.invoke(null, key);
Object node = getNodeMethod.invoke(map, hash, key);
if (node == null)
return null;
@SuppressWarnings("unchecked")
E result = (E)keyField.get(node);
return result;
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
public static <E> E get(NavigableSet<E> set, E key) {
return set.tailSet(key, true).floor(key);
}
public static void main(String[] args) {
HashSet<Integer> s = new HashSet<>();
// HashSet<Integer> s = new LinkedHashSet<>();
// TreeSet<Integer> s = new TreeSet<>();
for (int i = 0; i < 100_000; i++)
s.add(i);
Integer key = java.awt.event.KeyEvent.VK_FIND;
Integer hidden = get(s, key);
System.out.println(key);
System.out.println(hidden);
System.out.println(key.equals(hidden));
System.out.println(key == hidden);
}
}
multipart/form-data
encoded requests are indeed not by default supported by the Servlet API prior to version 3.0. The Servlet API parses the parameters by default using application/x-www-form-urlencoded
encoding. When using a different encoding, the request.getParameter()
calls will all return null
. When you're already on Servlet 3.0 (Glassfish 3, Tomcat 7, etc), then you can use HttpServletRequest#getParts()
instead. Also see this blog for extended examples.
Prior to Servlet 3.0, a de facto standard to parse multipart/form-data
requests would be using Apache Commons FileUpload. Just carefully read its User Guide and Frequently Asked Questions sections to learn how to use it. I've posted an answer with a code example before here (it also contains an example targeting Servlet 3.0).
Instead of
<button ng-click="removeTask({{task.id}})">remove</button>
do this:
<button ng-click="removeTask(task.id)">remove</button>
Please see this fiddle:
How to find out what this MySQL Error is trying to say:
#1064 - You have an error in your SQL syntax;
This error has no clues in it. You have to double check all of these items to see where your mistake is:
!@#$%^&*()-_=+[]{}\|;:'",<>/?
select
, into
, or countless others. Take away as much as you can from the broken query until it starts working. And then use PostgreSQL next time that has a sane syntax reporting system.
exit(0)
behave like return 0
in main()
function, exit(1)
behave like return 1
. The standard is, that main
function return 0
, if program ended successfully while non-zero value means that program was terminated with some kind of error.
Ok, For installing Android on Windows phone, I think you can..(But your window phone has required configuration to run Android) (For other I don't know If I will then surely post here)
Just go through these links,
Run Android on Your Windows Mobile Phone
full tutorial on how to put android on windows mobile touch pro 2
How to install Android on most Windows Mobile phones
Update:
For Windows 7 to Android device, this also possible, (You need to do some hack for this)
Just go through these links,
Install Windows Phone 7 Mango on HTC HD2 [How-To Guide]
HTC HD2: How To Install WP7 (Windows Phone 7) & MAGLDR 1.13 To NAND
Install windows phone 7 on android and iphones | Tips and Tricks
How to install Windows Phone 7 on HTC HD2? (Video)
To Install Android on your iOS Devices (This also possible...)
You're talking about template literals.
They allow for both multiline strings and string interpolation.
Multiline strings:
console.log(`foo_x000D_
bar`);_x000D_
// foo_x000D_
// bar
_x000D_
String interpolation:
var foo = 'bar';_x000D_
console.log(`Let's meet at the ${foo}`);_x000D_
// Let's meet at the bar
_x000D_
Modified from the angular-drag-and-drop-lists examples page
<div class="row">
<div ng-repeat="(listName, list) in models.lists" class="col-md-6">
<ul dnd-list="list">
<li ng-repeat="item in list"
dnd-draggable="item"
dnd-moved="list.splice($index, 1)"
dnd-effect-allowed="move"
dnd-selected="models.selected = item"
ng-class="{'selected': models.selected === item}"
draggable="true">{{item.label}}</li>
</ul>
</div>
</div>
var app = angular.module('angular-starter', [
'ui.router',
'dndLists'
]);
app.controller('MainCtrl', function($scope){
$scope.models = {
selected: null,
lists: {"A": [], "B": []}
};
// Generate initial model
for (var i = 1; i <= 3; ++i) {
$scope.models.lists.A.push({label: "Item A" + i});
$scope.models.lists.B.push({label: "Item B" + i});
}
// Model to JSON for demo purpose
$scope.$watch('models', function(model) {
$scope.modelAsJson = angular.toJson(model, true);
}, true);
});
Library can be installed via bower or npm: angular-drag-and-drop-lists
In my case, the error message was implying that I was working in a headless console. So plt.show()
could not work. What worked was calling plt.savefig
:
import matplotlib.pyplot as plt
plt.plot([1,2,3], [5,7,4])
plt.savefig("mygraph.png")
I found the answer on a github repository.
For anyone developing with WordPress, just use
esc_url_raw($url) === $url
to validate a URL (here's WordPress' documentation on esc_url_raw
). It handles URLs much better than filter_var($url, FILTER_VALIDATE_URL)
because it is unicode and XSS-safe. (Here is a good article mentioning all the problems with filter_var
).
you have to call a function before it can return anything.
function mainFunction() {
function subFunction() {
var str = "foo";
return str;
}
return subFunction();
}
var test = mainFunction();
alert(test);
Or:
function mainFunction() {
function subFunction() {
var str = "foo";
return str;
}
return subFunction;
}
var test = mainFunction();
alert( test() );
for your actual code. The return should be outside, in the main function. The callback is called somewhere inside the getLocations
method and hence its return value is not recieved inside your main function.
function reverseGeocode(latitude,longitude){
var address = "";
var country = "";
var countrycode = "";
var locality = "";
var geocoder = new GClientGeocoder();
var latlng = new GLatLng(latitude, longitude);
geocoder.getLocations(latlng, function(addresses) {
address = addresses.Placemark[0].address;
country = addresses.Placemark[0].AddressDetails.Country.CountryName;
countrycode = addresses.Placemark[0].AddressDetails.Country.CountryNameCode;
locality = addresses.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
});
return country
}
One small point to Andy Hayden's solution – it doesn't work (anymore?) because np.nan == np.nan
yields False
, so the replace
function doesn't actually do anything.
What worked for me was this:
df['b'] = df['b'].apply(lambda x: x if not np.isnan(x) else -1)
(At least that's the behavior for Pandas 0.19.2. Sorry to add it as a different answer, I do not have enough reputation to comment.)
If you have Python 2.6 or newer, use format
:
'{0:.3g}'.format(num)
For Python 2.5 or older:
'%.3g'%(num)
Explanation:
{0}
tells format
to print the first argument -- in this case, num
.
Everything after the colon (:) specifies the format_spec
.
.3
sets the precision to 3.
g
removes insignificant zeros. See
http://en.wikipedia.org/wiki/Printf#fprintf
For example:
tests=[(1.00, '1'),
(1.2, '1.2'),
(1.23, '1.23'),
(1.234, '1.23'),
(1.2345, '1.23')]
for num, answer in tests:
result = '{0:.3g}'.format(num)
if result != answer:
print('Error: {0} --> {1} != {2}'.format(num, result, answer))
exit()
else:
print('{0} --> {1}'.format(num,result))
yields
1.0 --> 1
1.2 --> 1.2
1.23 --> 1.23
1.234 --> 1.23
1.2345 --> 1.23
Using Python 3.6 or newer, you could use f-strings
:
In [40]: num = 1.234; f'{num:.3g}'
Out[40]: '1.23'
1) you can float the image to the left:
<img style="float:left" src="http://i.imgur.com/hCrQkJi.png">
2)You can use an HTML table to place elements on one line.
Code below
<div class="navigation-bar">
<div id="navigation-container">
<table>
<tr>
<td><img src="http://i.imgur.com/hCrQkJi.png"></td>
<td><ul>
<li><a href="#">Home</a></li>
<li><a href="#">Projects</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Get in Touch</a></li>
</ul>
</td></tr></table>
</div>
For simple input, like two prompts and two corresponding fixed responses, you could also use a "here document", the syntax of which looks like this:
test.sh <<!
y
pasword
!
The << prefixes a pattern, in this case '!'. Everything up to a line beginning with that pattern is interpreted as standard input. This approach is similar to the suggestion to pipe a multi-line echo into ssh, except that it saves the fork/exec of the echo command and I find it a bit more readable. The other advantage is that it uses built-in shell functionality so it doesn't depend on expect.
LocalDate.of( 2018 , Month.JANUARY , 23 )
.format( DateTimeFormatter.ofPattern( “uuuu-MM-EEE” , Locale.US ) )
The modern approach uses the java.time classes.
LocalDate ld = LocalDate.of( 2018 , Month.JANUARY , 23 ) ;
Note how we specify a Locale
such as Locale.CANADA_FRENCH
to determine the human language used to translate the name of the day.
DateTimeFormatter f = DateTimeFormatter.ofPattern( “uuuu-MM-EEE” , Locale.US ) ;
String output = ld.format( f ) ;
By the way, you may be interested in the standard ISO 8601 week numbering scheme: yyyy-Www-d
.
2018-W01-2
Week # 1 has the first Thursday of the calendar-year. Week starts on a Monday. A year has either 52 or 53 weeks. The last/first few days of a calendar-year may land in the next/previous week-based-year.
The single digit on the end is day-of-week, 1-7 for Monday-Sunday.
Add the ThreeTen-Extra library class to your project for the YearWeek
class.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
<?php
session_start();
mysql_connect('localhost','root','');
mysql_select_db('database name goes here');
$error_msg=NULL;
//log out code
if(isset($_REQUEST['logout'])){
unset($_SESSION['user']);
unset($_SESSION['username']);
unset($_SESSION['id']);
unset($_SESSION['role']);
session_destroy();
}
//
if(!empty($_POST['submit'])){
if(empty($_POST['username']))
$error_msg='please enter username';
if(empty($_POST['password']))
$error_msg='please enter password';
if(empty($error_msg)){
$sql="SELECT*FROM users WHERE username='%s' AND password='%s'";
$sql=sprintf($sql,$_POST['username'],md5($_POST['password']));
$records=mysql_query($sql) or die(mysql_error());
if($record_new=mysql_fetch_array($records)){
$_SESSION['user']=$record_new;
$_SESSION['id']=$record_new['id'];
$_SESSION['username']=$record_new['username'];
$_SESSION['role']=$record_new['role'];
header('location:index.php');
$error_msg='welcome';
exit();
}else{
$error_msg='invalid details';
}
}
}
?>
// replace the location with whatever page u want the user to visit when he/she log in
more_itertools.locate
finds indices for all items that satisfy a condition.
from more_itertools import locate
list(locate([0, 1, 1, 0, 1, 0, 0]))
# [1, 2, 4]
list(locate(['a', 'b', 'c', 'b'], lambda x: x == 'b'))
# [1, 3]
more_itertools
is a third-party library > pip install more_itertools
.
Try this code:
For Each aSheet In Worksheets
Select Case aSheet.Name
Case "ID Sheet", "Summary"
Application.DisplayAlerts = False
aSheet.Delete
Application.DisplayAlerts = True
End Select
Next aSheet
You can run your .bat file through a .vbs file
Copy the following code into your .vbs file :
Dim WshShell
Dim obj
Set WshShell = WScript.CreateObject("WScript.Shell")
obj = WshShell.Run("C:\Users\file1.bat", 0)
obj = WshShell.Run("C:\Users\file2.bat", 0) and so on
set WshShell = Nothing
A lot of good answers have been posted, but I'd like to append one more.
Not all numbers can be represented via floats/doubles For example, the number "0.2" will be represented as "0.200000003" in single precision in IEEE754 float point standard.
Model for store real numbers under the hood represent float numbers as
Even though you can type 0.2
easily, FLT_RADIX
and DBL_RADIX
is 2; not 10 for a computer with FPU which uses "IEEE Standard for Binary Floating-Point Arithmetic (ISO/IEEE Std 754-1985)".
So it is a bit hard to represent such numbers exactly. Even if you specify this variable explicitly without any intermediate calculation.
Many answers focus on how to make your solution work, while very few suggest that your solution is a very bad approach. If you really want to "practice to learn", why not practice using good solutions? Hardcoding your password is learning the wrong approach!
If what you really want is a password-less mount
for that volume, maybe sudo
isn't needed at all! So may I suggest other approaches?
Use /etc/fstab
as mensi suggested. Use options user
and noauto
to let regular users mount that volume.
Use Polkit
for passwordless actions: Configure a .policy
file for your script with <allow_any>yes</allow_any>
and drop at /usr/share/polkit-1/actions
Edit /etc/sudoers
to allow your user to use sudo
without typing your password. As @Anders suggested, you can restrict such usage to specific commands, thus avoiding unlimited passwordless root priviledges in your account. See this answer for more details on /etc/sudoers
.
All the above allow passwordless root privilege, none require you to hardcode your password. Choose any approach and I can explain it in more detail.
As for why it is a very bad idea to hardcode passwords, here are a few good links for further reading:
You can add the src
folder to build path by:
src
folder.And you are done. Hope this help.
EDIT: Refer to the Eclipse documentation
You can use appendChild
function to insert after an element.
Reference: http://www.w3schools.com/jsref/met_node_appendchild.asp
Your svn merge
syntax is wrong.
You want to checkout a working copy of trunk
and then use the svn merge --reintegrate
option:
$ pwd
/home/user/project-trunk
$ svn update # (make sure the working copy is up to date)
At revision <N>.
$ svn merge --reintegrate ^/project/branches/branch_1
--- Merging differences between repository URLs into '.':
U foo.c
U bar.c
U .
$ # build, test, verify, ...
$ svn commit -m "Merge branch_1 back into trunk!"
Sending .
Sending foo.c
Sending bar.c
Transmitting file data ..
Committed revision <N+1>.
See the SVN book chapter on merging for more details.
Note that at the time it was written, this was the right answer (and was accepted), but things have moved on. See the answer of topek, and http://subversion.apache.org/docs/release-notes/1.8.html#auto-reintegrate
Something like:
>>> bytes.fromhex('4a4b4c').decode('utf-8')
'JKL'
Just put the actual encoding you are using.
Mike Bethany's answer above worked to set a default value when a new record was being created and still have the value the user selected show in the edit form. However, I added a model validation and it would not let me submit the form. Here's what worked for me to have a model validation on the field and to show a default value as well as the value the user selected when in edit mode.
<div class="field">
<%= f.label :project_id, 'my project id', class: "control-label" %><br>
<% if @work.new_record? %>
<%= f.select :project_id, options_for_select([['Yes', true], ['No', false]], true), {}, required: true, class: "form-control" %><br>
<% else %>
<%= f.select :project_id, options_for_select([['Yes', true], ['No', false]], @work.project_id), {}, required: true, class: "form-control" %><br>
<% end %>
</div>
model validation
validates :project_id, presence: true
I'm using Rails 4.2.4 and couldn't work out why I was getting:
Can't verify CSRF token authenticity
I have in the layout:
<%= csrf_meta_tags %>
In the controller:
protect_from_forgery with: :exception
Invoking tcpdump -A -s 999 -i lo port 3000
was showing the header being set ( despite not needing to set the headers with ajaxSetup
- it was done already):
X-CSRF-Token: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
DNT: 1
Content-Length: 125
authenticity_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
In the end it was failing because I had cookies switched off. CSRF doesn't work without cookies being enabled, so this is another possible cause if you're seeing this error.
Even if you are using IIS or apache, in my guess you are using static html page as a landing page, and by default the web server doesn't allow POST or GET verb on .html page, facebook calls your page via POST/GET verb
the solution would be to rename the page into .php or .aspx and you should be good to go :)
SPARK-22614 exposes range partitioning.
val partitionedByRange = df.repartitionByRange(42, $"k")
partitionedByRange.explain
// == Parsed Logical Plan ==
// 'RepartitionByExpression ['k ASC NULLS FIRST], 42
// +- AnalysisBarrier Project [_1#2 AS k#5, _2#3 AS v#6]
//
// == Analyzed Logical Plan ==
// k: string, v: int
// RepartitionByExpression [k#5 ASC NULLS FIRST], 42
// +- Project [_1#2 AS k#5, _2#3 AS v#6]
// +- LocalRelation [_1#2, _2#3]
//
// == Optimized Logical Plan ==
// RepartitionByExpression [k#5 ASC NULLS FIRST], 42
// +- LocalRelation [k#5, v#6]
//
// == Physical Plan ==
// Exchange rangepartitioning(k#5 ASC NULLS FIRST, 42)
// +- LocalTableScan [k#5, v#6]
SPARK-22389 exposes external format partitioning in the Data Source API v2.
In Spark >= 1.6 it is possible to use partitioning by column for query and caching. See: SPARK-11410 and SPARK-4849 using repartition
method:
val df = Seq(
("A", 1), ("B", 2), ("A", 3), ("C", 1)
).toDF("k", "v")
val partitioned = df.repartition($"k")
partitioned.explain
// scala> df.repartition($"k").explain(true)
// == Parsed Logical Plan ==
// 'RepartitionByExpression ['k], None
// +- Project [_1#5 AS k#7,_2#6 AS v#8]
// +- LogicalRDD [_1#5,_2#6], MapPartitionsRDD[3] at rddToDataFrameHolder at <console>:27
//
// == Analyzed Logical Plan ==
// k: string, v: int
// RepartitionByExpression [k#7], None
// +- Project [_1#5 AS k#7,_2#6 AS v#8]
// +- LogicalRDD [_1#5,_2#6], MapPartitionsRDD[3] at rddToDataFrameHolder at <console>:27
//
// == Optimized Logical Plan ==
// RepartitionByExpression [k#7], None
// +- Project [_1#5 AS k#7,_2#6 AS v#8]
// +- LogicalRDD [_1#5,_2#6], MapPartitionsRDD[3] at rddToDataFrameHolder at <console>:27
//
// == Physical Plan ==
// TungstenExchange hashpartitioning(k#7,200), None
// +- Project [_1#5 AS k#7,_2#6 AS v#8]
// +- Scan PhysicalRDD[_1#5,_2#6]
Unlike RDDs
Spark Dataset
(including Dataset[Row]
a.k.a DataFrame
) cannot use custom partitioner as for now. You can typically address that by creating an artificial partitioning column but it won't give you the same flexibility.
One thing you can do is to pre-partition input data before you create a DataFrame
import org.apache.spark.sql.types._
import org.apache.spark.sql.Row
import org.apache.spark.HashPartitioner
val schema = StructType(Seq(
StructField("x", StringType, false),
StructField("y", LongType, false),
StructField("z", DoubleType, false)
))
val rdd = sc.parallelize(Seq(
Row("foo", 1L, 0.5), Row("bar", 0L, 0.0), Row("??", -1L, 2.0),
Row("foo", -1L, 0.0), Row("??", 3L, 0.6), Row("bar", -3L, 0.99)
))
val partitioner = new HashPartitioner(5)
val partitioned = rdd.map(r => (r.getString(0), r))
.partitionBy(partitioner)
.values
val df = sqlContext.createDataFrame(partitioned, schema)
Since DataFrame
creation from an RDD
requires only a simple map phase existing partition layout should be preserved*:
assert(df.rdd.partitions == partitioned.partitions)
The same way you can repartition existing DataFrame
:
sqlContext.createDataFrame(
df.rdd.map(r => (r.getInt(1), r)).partitionBy(partitioner).values,
df.schema
)
So it looks like it is not impossible. The question remains if it make sense at all. I will argue that most of the time it doesn't:
Repartitioning is an expensive process. In a typical scenario most of the data has to be serialized, shuffled and deserialized. From the other hand number of operations which can benefit from a pre-partitioned data is relatively small and is further limited if internal API is not designed to leverage this property.
GROUP BY
- it is possible to reduce memory footprint of the temporary buffers**, but overall cost is much higher. More or less equivalent to groupByKey.mapValues(_.reduce)
(current behavior) vs reduceByKey
(pre-partitioning). Unlikely to be useful in practice.SqlContext.cacheTable
. Since it looks like it is using run length encoding, applying OrderedRDDFunctions.repartitionAndSortWithinPartitions
could improve compression ratio. Performance is highly dependent on a distribution of the keys. If it is skewed it will result in a suboptimal resource utilization. In the worst case scenario it will be impossible to finish the job at all.
Partitioning with JDBC sources:
JDBC data sources support predicates
argument. It can be used as follows:
sqlContext.read.jdbc(url, table, Array("foo = 1", "foo = 3"), props)
It creates a single JDBC partition per predicate. Keep in mind that if sets created using individual predicates are not disjoint you'll see duplicates in the resulting table.
partitionBy
method in DataFrameWriter
:
Spark DataFrameWriter
provides partitionBy
method which can be used to "partition" data on write. It separates data on write using provided set of columns
val df = Seq(
("foo", 1.0), ("bar", 2.0), ("foo", 1.5), ("bar", 2.6)
).toDF("k", "v")
df.write.partitionBy("k").json("/tmp/foo.json")
This enables predicate push down on read for queries based on key:
val df1 = sqlContext.read.schema(df.schema).json("/tmp/foo.json")
df1.where($"k" === "bar")
but it is not equivalent to DataFrame.repartition
. In particular aggregations like:
val cnts = df1.groupBy($"k").sum()
will still require TungstenExchange
:
cnts.explain
// == Physical Plan ==
// TungstenAggregate(key=[k#90], functions=[(sum(v#91),mode=Final,isDistinct=false)], output=[k#90,sum(v)#93])
// +- TungstenExchange hashpartitioning(k#90,200), None
// +- TungstenAggregate(key=[k#90], functions=[(sum(v#91),mode=Partial,isDistinct=false)], output=[k#90,sum#99])
// +- Scan JSONRelation[k#90,v#91] InputPaths: file:/tmp/foo.json
bucketBy
method in DataFrameWriter
(Spark >= 2.0):
bucketBy
has similar applications as partitionBy
but it is available only for tables (saveAsTable
). Bucketing information can used to optimize joins:
// Temporarily disable broadcast joins
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)
df.write.bucketBy(42, "k").saveAsTable("df1")
val df2 = Seq(("A", -1.0), ("B", 2.0)).toDF("k", "v2")
df2.write.bucketBy(42, "k").saveAsTable("df2")
// == Physical Plan ==
// *Project [k#41, v#42, v2#47]
// +- *SortMergeJoin [k#41], [k#46], Inner
// :- *Sort [k#41 ASC NULLS FIRST], false, 0
// : +- *Project [k#41, v#42]
// : +- *Filter isnotnull(k#41)
// : +- *FileScan parquet default.df1[k#41,v#42] Batched: true, Format: Parquet, Location: InMemoryFileIndex[file:/spark-warehouse/df1], PartitionFilters: [], PushedFilters: [IsNotNull(k)], ReadSchema: struct<k:string,v:int>
// +- *Sort [k#46 ASC NULLS FIRST], false, 0
// +- *Project [k#46, v2#47]
// +- *Filter isnotnull(k#46)
// +- *FileScan parquet default.df2[k#46,v2#47] Batched: true, Format: Parquet, Location: InMemoryFileIndex[file:/spark-warehouse/df2], PartitionFilters: [], PushedFilters: [IsNotNull(k)], ReadSchema: struct<k:string,v2:double>
* By partition layout I mean only a data distribution. partitioned
RDD has no longer a partitioner.
** Assuming no early projection. If aggregation covers only small subset of columns there is probably no gain whatsoever.
>>> import re
>>> re.sub("[^0-9]", "", "sdkjh987978asd098as0980a98sd")
'987978098098098'
After struggling with this and trying all the answers on this page, I finally realized I had the incorrect credentials stored by windows for the server that hosts our subversion. I cleared this stored value from windows credentials and all is well.
This worked for me:
this.form.get('first').disable({onlySelf: true});
When linger is on but the timeout is zero the TCP stack doesn't wait for pending data to be sent before closing the connection. Data could be lost due to this but by setting linger this way you're accepting this and asking that the connection be reset straight away rather than closed gracefully. This causes an RST to be sent rather than the usual FIN.
Thanks to EJP for his comment, see here for details.
Try:
openssl pkcs12 -in path.p12 -out newfile.crt.pem -clcerts -nokeys
openssl pkcs12 -in path.p12 -out newfile.key.pem -nocerts -nodes
After that you have:
To put the certificate and key in the same file without a password, use the following, as an empty password will cause the key to not be exported:
openssl pkcs12 -in path.p12 -out newfile.pem -nodes
Or, if you want to provide a password for the private key, omit -nodes
and input a password:
openssl pkcs12 -in path.p12 -out newfile.pem
If you need to input the PKCS#12 password directly from the command line (e.g. a script), just add -passin pass:${PASSWORD}
:
openssl pkcs12 -in path.p12 -out newfile.crt.pem -clcerts -nokeys -passin 'pass:P@s5w0rD'
If you are using Notepad++ editor Goto ctrl + F choose tab 3 find in files and enter:
I got it working using the following code.
var green= "Green";
var color : Color= <Color>Color[green];
TL;DR: Follow Go conventions! (lesson learned the hard way), check for old go versions and remove them. Install latest.
For me the solution was different. I worked on a shared Linux server and after verifying my GOPATH
and other environment variables several times it still didn't work. I encountered several errors including 'Cannot find package' and 'unrecognized import path'. After trying to reinstall with this solution by the instructions on golang.org (including the uninstall part) still encountered problems.
Took me some time to realize that there's still an old version that hasn't been uninstalled (running go version
then which go
again... DAHH) which got me to this question and finally solved.
Simplest of all would be.
Create xml layout file for dialog . Add whatever view you want like EditText , ListView , Spinner etc.
Inflate this view and set this to AlertDialog
Lets start with Layout file first.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical">
<EditText
android:id="@+id/etComments"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="top"
android:hint="Enter comments(Optional)"
android:inputType="textMultiLine"
android:lines="8"
android:maxLines="3"
android:minLines="6"
android:scrollbars="vertical" />
</LinearLayout>
final View view = layoutInflater.inflate(R.layout.xml_file_created_above, null);
AlertDialog alertDialog = new AlertDialog.Builder(ct).create();
alertDialog.setTitle("Your Title Here");
alertDialog.setIcon("Icon id here");
alertDialog.setCancelable(false);
Constant.alertDialog.setMessage("Your Message Here");
final EditText etComments = (EditText) view.findViewById(R.id.etComments);
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss()
}
});
alertDialog.setView(view);
alertDialog.show();
ast.literal_eval
(located in ast.py
) parses the tree with ast.parse
first, then it evaluates the code with quite an ugly recursive function, interpreting the parse tree elements and replacing them with their literal equivalents. Unfortunately the code is not at all expandable, so to add Decimal
to the code you need to copy all the code and start over.
For a slightly easier approach, you can use ast.parse
module to parse the expression, and then the ast.NodeVisitor
or ast.NodeTransformer
to ensure that there is no unwanted syntax or unwanted variable accesses. Then compile with compile
and eval
to get the result.
The code is a bit different from literal_eval
in that this code actually uses eval
, but in my opinion is simpler to understand and one does not need to dig too deep into AST trees. It specifically only allows some syntax, explicitly forbidding for example lambdas, attribute accesses (foo.__dict__
is very evil), or accesses to any names that are not deemed safe. It parses your expression fine, and as an extra I also added Num
(float and integer), list and dictionary literals.
Also, works the same on 2.7 and 3.3
import ast
import decimal
source = "(Decimal('11.66985'), Decimal('1e-8'),"\
"(1,), (1,2,3), 1.2, [1,2,3], {1:2})"
tree = ast.parse(source, mode='eval')
# using the NodeTransformer, you can also modify the nodes in the tree,
# however in this example NodeVisitor could do as we are raising exceptions
# only.
class Transformer(ast.NodeTransformer):
ALLOWED_NAMES = set(['Decimal', 'None', 'False', 'True'])
ALLOWED_NODE_TYPES = set([
'Expression', # a top node for an expression
'Tuple', # makes a tuple
'Call', # a function call (hint, Decimal())
'Name', # an identifier...
'Load', # loads a value of a variable with given identifier
'Str', # a string literal
'Num', # allow numbers too
'List', # and list literals
'Dict', # and dicts...
])
def visit_Name(self, node):
if not node.id in self.ALLOWED_NAMES:
raise RuntimeError("Name access to %s is not allowed" % node.id)
# traverse to child nodes
return self.generic_visit(node)
def generic_visit(self, node):
nodetype = type(node).__name__
if nodetype not in self.ALLOWED_NODE_TYPES:
raise RuntimeError("Invalid expression: %s not allowed" % nodetype)
return ast.NodeTransformer.generic_visit(self, node)
transformer = Transformer()
# raises RuntimeError on invalid code
transformer.visit(tree)
# compile the ast into a code object
clause = compile(tree, '<AST>', 'eval')
# make the globals contain only the Decimal class,
# and eval the compiled object
result = eval(clause, dict(Decimal=decimal.Decimal))
print(result)
First of all: you should always import mockito static, this way the code will be much more readable (and intuitive):
import static org.mockito.Mockito.*;
There are actually many ways to achieve this, however it's (arguably) cleaner to use the
verify(yourMock, times(0)).someMethod();
method all over your tests, when on other Tests you use it to assert a certain amount of executions like this:
verify(yourMock, times(5)).someMethod();
Alternatives are:
verify(yourMock, never()).someMethod();
Alternatively - when you really want to make sure a certain mocked Object is actually NOT called at all - you can use:
verifyZeroInteractions(yourMock)
Just download and install "Samsung Kies" from this link. and everything would work as required.
Before installing, uninstall the drivers you have installed for your device.
Update:
Two possible solutions:
You should be able to do something like:
ArrayList<String> list = new ArrayList<String>();
for( String s : foo )
{
list.add(s);
}
Stop using jQuery just for the sake of it! This is so simple with JavaScript only.
document.querySelector('#the-link').setAttribute('href', 'http://google.com');
From a post by Robert Martin in comp.object:
Association represents the ability of one instance to send a message to another instance. This is typically implemented with a pointer or reference instance variable, although it might also be implemented as a method argument, or the creation of a local variable.
//[Example:]
//|A|----------->|B|
class A
{
private:
B* itsB;
};
Aggregation [...] is the typical whole/part relationship. This is exactly the same as an association with the exception that instances cannot have cyclic aggregation relationships (i.e. a part cannot contain its whole).
//[Example:]
//|Node|<>-------->|Node|
class Node
{
private:
vector<Node*> itsNodes;
};
The fact that this is aggregation means that the instances of Node cannot form a cycle. Thus, this is a Tree of Nodes not a graph of Nodes.
Composition [...] is exactly like Aggregation except that the lifetime of the 'part' is controlled by the 'whole'. This control may be direct or transitive. That is, the 'whole' may take direct responsibility for creating or destroying the 'part', or it may accept an already created part, and later pass it on to some other whole that assumes responsibility for it.
//[Example:]
//|Car|<#>-------->|Carburetor|
class Car
{
public:
virtual ~Car() {delete itsCarb;}
private:
Carburetor* itsCarb
};
git mv oldname newname
so that Git recognizes this is a move, rather than deleting/adding new files).Info.plist
and Product Bundle Identifier
.Info.plist
, update it.Product Bundle Identifier
, unless it is utilizing the ${PRODUCT_NAME} variable. In that case, search for "product" in the settings and update Product Name
. If Product Name
is based on ${TARGET_NAME}, click on the actual target item in the TARGETS list on the left of the settings pane and edit it, and all related settings will update immediately.Prefix Header
's path is also updated to the new name.Start your Emulator from Android Studio Tools->Android-> AVD Manager
then select an emulator image and start it.
After emulator is started just drag and drop the APK Very simple.
ZIP is a file format used for storing an arbitrary number of files and folders together with lossless compression. It makes no strict assumptions about the compression methods used, but is most frequently used with DEFLATE.
Gzip is both a compression algorithm based on DEFLATE but less encumbered with potential patents et al, and a file format for storing a single compressed file. It supports compressing an arbitrary number of files and folders when combined with tar. The resulting file has an extension of .tgz
or .tar.gz
and is commonly called a tarball.
zlib is a library of functions encapsulating DEFLATE in its most common LZ77 incarnation.
None of these solutions works for me. Postman is not sending any request to the server because postman is not finding the host. So, if you modify your /etc/hosts to
127.0.0.1 localhost
127.0.0.1 subdomain.localhost
It works for me.
There are many options to consume a SOAP web service with Stub or Java classes created based on WSDL. But if anyone wants to do this without any Java class created, this article is very helpful. Code Snippet from the article:
public String someMethod() throws MalformedURLException, IOException {
//Code to make a webservice HTTP request
String responseString = "";
String outputString = "";
String wsURL = "<Endpoint of the webservice to be consumed>";
URL url = new URL(wsURL);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)connection;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
String xmlInput = "entire SOAP Request";
byte[] buffer = new byte[xmlInput.length()];
buffer = xmlInput.getBytes();
bout.write(buffer);
byte[] b = bout.toByteArray();
String SOAPAction = "<SOAP action of the webservice to be consumed>";
// Set the appropriate HTTP parameters.
httpConn.setRequestProperty("Content-Length",
String.valueOf(b.length));
httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
httpConn.setRequestProperty("SOAPAction", SOAPAction);
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
OutputStream out = httpConn.getOutputStream();
//Write the content of the request to the outputstream of the HTTP Connection.
out.write(b);
out.close();
//Ready with sending the request.
//Read the response.
InputStreamReader isr = null;
if (httpConn.getResponseCode() == 200) {
isr = new InputStreamReader(httpConn.getInputStream());
} else {
isr = new InputStreamReader(httpConn.getErrorStream());
}
BufferedReader in = new BufferedReader(isr);
//Write the SOAP message response to a String.
while ((responseString = in.readLine()) != null) {
outputString = outputString + responseString;
}
//Parse the String output to a org.w3c.dom.Document and be able to reach every node with the org.w3c.dom API.
Document document = parseXmlFile(outputString); // Write a separate method to parse the xml input.
NodeList nodeLst = document.getElementsByTagName("<TagName of the element to be retrieved>");
String elementValue = nodeLst.item(0).getTextContent();
System.out.println(elementValue);
//Write the SOAP message formatted to the console.
String formattedSOAPResponse = formatXML(outputString); // Write a separate method to format the XML input.
System.out.println(formattedSOAPResponse);
return elementValue;
}
For those who're looking for a similar kind of solution with file upload while consuming a SOAP API, please refer to this post: How to attach a file (pdf, jpg, etc) in a SOAP POST request?
Try this
static DataTable ConvertToDatatable(List<Item> list)
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Price");
dt.Columns.Add("URL");
foreach (var item in list)
{
var row = dt.NewRow();
row["Name"] = item.Name;
row["Price"] = Convert.ToString(item.Price);
row["URL"] = item.URL;
dt.Rows.Add(row);
}
return dt;
}
TimeUnit is an enum, so you can't create a new one.
The following will convert 1000000000000ns to seconds.
TimeUnit.NANOSECONDS.toSeconds(1000000000000L);
If the message is "n commits behind master."
You need to rebase your dev branch with master. You got the above message because after checking out dev branch from master, the master branch got new commit and has moved ahead. You need to get those new commits to your dev branch.
Steps:
git checkout master
git pull #this will update your local master
git checkout yourDevBranch
git rebase master
You can not create URI from resources inside of the jar file. You can simply write it to the temp file and then use it (java8):
Path path = File.createTempFile("some", "address").toPath();
Files.copy(ClassLoader.getSystemResourceAsStream("/path/to/resource"), path, StandardCopyOption.REPLACE_EXISTING);
Here is a vbs script that was passed down to me:
Set servicelist = GetObject("winmgmts:").InstancesOf ("Win32_Service")
for each service in servicelist
sname = lcase(service.name)
If sname = "NameOfMyService" Then
msgbox(sname)
service.delete ' the internal name of your service
end if
next
You can also use template matching to detect shapes inside an image.
This can also happen in Intellij Ultimate, which has PyCharm integrated. The issue is as diagnosed above, you have the wrong interpreter selected.
The exact method to fix this for any given project is to go to Project Settings...Project and adjust the Project SDK. You can add a New Project SDK if you don't have Python 3 added by navigating to the python3 binary. This will fix the errors listed above. A shortcut to Project Settings is the blue checkerboard-type icon.
You can also add Python 3 as the default interpreter for Python projects. On OSX this is in File..Other Settings...Default Project Structure. There you can set the Project SDK which will now apply on each new project. It can be different on other platforms, but still similar.
I can't tell from the context you supply, but if it's something you just need to do at app startup, you can still use Server.MapPath
in WebApiHttpApplication
; e.g. in Application_Start()
.
I'm just answering your direct question; the already-mentioned HostingEnvironment.MapPath()
is probably the preferred solution.
onLocationChange
may also be useful. Not sure if this is a Mozilla-only thing though, appears that it might be.
Its better to perform this over Master branch
Edit .gitignore file. Add the below line in it.
.idea
Remove .idea folder from remote repo. using below command.
git rm -r --cached .idea
For more info. reference: Removing Files from a Git Repository Without Actually Deleting Them
Stage .gitignore file. Using below command
git add .gitignore
Commit
git commit -m 'Removed .idea folder'
Push to remote
git push origin master
If you are using spring, then you can use the the following method to read file from src/main/resources:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.springframework.core.io.ClassPathResource;
public String readFileToString(String path) throws IOException {
StringBuilder resultBuilder = new StringBuilder("");
ClassPathResource resource = new ClassPathResource(path);
try (
InputStream inputStream = resource.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
resultBuilder.append(line);
}
}
return resultBuilder.toString();
}
Might this be the download you are looking for?
Introduce a new variable that you'll use as a 'loop breaker'. First assign something to it(False,0, etc.), and then, inside the outer loop, before you break from it, change the value to something else(True,1,...). Once the loop exits make the 'parent' loop check for that value. Let me demonstrate:
breaker = False #our mighty loop exiter!
while True:
while True:
if conditionMet:
#insert code here...
breaker = True
break
if breaker: # the interesting part!
break # <--- !
If you have an infinite loop, this is the only way out; for other loops execution is really a lot faster. This also works if you have many nested loops. You can exit all, or just a few. Endless possibilities! Hope this helped!
++
is not an operator. It is two +
operators. The +
operator is the identity operator, which does nothing. (Clarification: the +
and -
unary operators only work on numbers, but I presume that you wouldn't expect a hypothetical ++
operator to work on strings.)
++count
Parses as
+(+count)
Which translates to
count
You have to use the slightly longer +=
operator to do what you want to do:
count += 1
I suspect the ++
and --
operators were left out for consistency and simplicity. I don't know the exact argument Guido van Rossum gave for the decision, but I can imagine a few arguments:
++count
is ambiguous, as it could be +
, +
, count
(two unary +
operators) just as easily as it could be ++
, count
(one unary ++
operator). It's not a significant syntactic ambiguity, but it does exist.++
is nothing more than a synonym for += 1
. It was a shorthand invented because C compilers were stupid and didn't know how to optimize a += 1
into the inc
instruction most computers have. In this day of optimizing compilers and bytecode interpreted languages, adding operators to a language to allow programmers to optimize their code is usually frowned upon, especially in a language like Python that is designed to be consistent and readable.++
operators is mixing up the differences (both in precedence and in return value) between the pre- and post-increment/decrement operators, and Python likes to eliminate language "gotcha"-s. The precedence issues of pre-/post-increment in C are pretty hairy, and incredibly easy to mess up.Could you please have a look at: http://jsfiddle.net/4Zw3M/1/.
Basically, the data is stored in an Array and the options are added accordingly. I think the code says more than a thousand words.
var data = [ // The data
['ten', [
'eleven','twelve'
]],
['twenty', [
'twentyone', 'twentytwo'
]]
];
$a = $('#a'); // The dropdowns
$b = $('#b');
for(var i = 0; i < data.length; i++) {
var first = data[i][0];
$a.append($("<option>"). // Add options
attr("value",first).
data("sel", i).
text(first));
}
$a.change(function() {
var index = $(this).children('option:selected').data('sel');
var second = data[index][1]; // The second-choice data
$b.html(''); // Clear existing options in second dropdown
for(var j = 0; j < second.length; j++) {
$b.append($("<option>"). // Add options
attr("value",second[j]).
data("sel", j).
text(second[j]));
}
}).change(); // Trigger once to add options at load of first choice
You can't create pseudo elements in inline css.
However, if you can create a pseudo element in a stylesheet, then there's a way to style it inline by setting an inline style to its parent element, and then using inherit keyword to style the pseudo element, like this:
<parent style="background-image:url(path/to/file); background-size:0px;"></p>
<style>
parent:before{
content:'';
background-image:inherit;
(other)
}
</style>
sometimes this can be handy.
You can do as @rmobis has specified in his answer, [Adding something more into it]
Using order by
twice:
MyTable::orderBy('coloumn1', 'DESC')
->orderBy('coloumn2', 'ASC')
->get();
and the second way to do it is,
Using raw order by
:
MyTable::orderByRaw("coloumn1 DESC, coloumn2 ASC");
->get();
Both will produce same query as follow,
SELECT * FROM `my_tables` ORDER BY `coloumn1` DESC, `coloumn2` ASC
As @rmobis specified in comment of first answer you can pass like an array to order by column like this,
$myTable->orders = array(
array('column' => 'coloumn1', 'direction' => 'desc'),
array('column' => 'coloumn2', 'direction' => 'asc')
);
one more way to do it is iterate
in loop,
$query = DB::table('my_tables');
foreach ($request->get('order_by_columns') as $column => $direction) {
$query->orderBy($column, $direction);
}
$results = $query->get();
Hope it helps :)
I got the same issue and this solved it for me. Perhaps this might be a fix for your problem too.
Here is the fix. Follow this link http://www.anindya.com/php-5-4-3-and-php-5-3-13-x64-64-bit-for-windows/
Go to "Fixed curl extensions" and download the extension that matches your PHP version.
Extract and copy "php_curl.dll" to the extension directory of your wamp installation. (i.e. C:\wamp\bin\php\php5.3.13\ext)
Restart Apache
Done!
Refer to: http://blog.nterms.com/2012/07/php-curl-issues-with-wamp-server-on.html
Cheers!
When we use lazy-init="default" as an attribute in element, the container picks up the value specified by default-lazy-init="true|false" attribute of element and uses it as lazy-init="true|false".
If default-lazy-init attribute is not present in element than lazy-init="default" in element will behave as if lazy-init-"false".
If you used read.table()
(or one of it's ilk, e.g. read.csv()
) then the easy fix is to change the call to:
read.table(file = "foo.txt", row.names = 1, ....)
where ....
are the other arguments you needed/used. The row.names
argument takes the column number of the data file from which to take the row names. It need not be the first column. See ?read.table
for details/info.
If you already have the data in R and can't be bothered to re-read it, or it came from another route, just set the rownames
attribute and remove the first variable from the object (assuming obj
is your object)
rownames(obj) <- obj[, 1] ## set rownames
obj <- obj[, -1] ## remove the first variable
as @rampion mentioned, if you are in clang gcc, the warnings are by name, not number, and you'll need to do:
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-variable"
// ..your code..
#pragma clang diagnostic pop
this info comes from here
As has been suggested, using the string.format method is nice and simple and very readable.
In vb.net the " + " is used for addition and the " & " is used for string concatenation.
In your example:
MsgBox("Variable = " + variable)
becomes:
MsgBox("Variable = " & variable)
I may have been a bit quick answering this as it appears these operators can both be used for concatenation, but recommended use is the "&", source http://msdn.microsoft.com/en-us/library/te2585xw(v=VS.100).aspx
maybe call
variable.ToString()
update:
Use string interpolation (vs2015 onwards I believe):
MsgBox($"Variable = {variable}")
After reading all of the above, I prefer the following statement:
SELECT EXISTS(
SELECT * FROM information_schema.tables
WHERE table_schema = 'db'
AND table_name = 'table'
);
It indicates exactly what you want to do and it actually returns a 'boolean'.
Try to use:
location.reload(true);
When this method receives a true
value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.
More info:
My task was kill everything matching regexp that is placed in specific directory (after selenium tests not everything got stop). This worked for me:
for i in `ps aux | egrep "firefox|chrome|selenium|opera"|grep "/home/dir1/dir2"|awk '{print $2}'|uniq`; do kill $i; done
declare @cur cursor
declare @idx int
declare @Approval_No varchar(50)
declare @ReqNo varchar(100)
declare @M_Id varchar(100)
declare @Mail_ID varchar(100)
declare @temp table
(
val varchar(100)
)
declare @temp2 table
(
appno varchar(100),
mailid varchar(100),
userod varchar(100)
)
declare @slice varchar(8000)
declare @String varchar(100)
--set @String = '1200096,1200095,1200094,1200093,1200092,1200092'
set @String = '20131'
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(',',@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
--select @slice
insert into @temp values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
-- select distinct(val) from @temp
SET @cur = CURSOR FOR select distinct(val) from @temp
--open cursor
OPEN @cur
--fetchng id into variable
FETCH NEXT
FROM @cur into @Approval_No
--
--loop still the end
while @@FETCH_STATUS = 0
BEGIN
select distinct(Approval_Sr_No) as asd, @ReqNo=Approval_Sr_No,@M_Id=AM_ID,@Mail_ID=Mail_ID from WFMS_PRAO,WFMS_USERMASTER where WFMS_PRAO.AM_ID=WFMS_USERMASTER.User_ID
and Approval_Sr_No=@Approval_No
insert into @temp2 values(@ReqNo,@M_Id,@Mail_ID)
FETCH NEXT
FROM @cur into @Approval_No
end
--close cursor
CLOSE @cur
select * from @tem
You can use the following little trick:
set word=table
set str="jump over the chair"
call set str=%%str:chair=%word%%%
echo %str%
The call
there causes another layer of variable expansion, making it necessary to quote the original %
signs but it all works out in the end.
in c++11 you can do:
void foo(const std::list<std::string> & myArguments) {
//do whatever you want, with all the convenience of lists
}
foo({"arg1","arg2"});
list initializer FTW!
oh boy, this got resolved, I just had to name my Installed JRE appropriately. I had only the jdk installed and eclipse had taken the default jdk name, i renamed it to JavaSE-1.6 and voila it worked, though i had to redo everthing from the scratch.
class MyComponent extends Component {
constructor(props){
super(props)
this.myInput = React.createRef()
}
componentDidMount () {
console.log(this.myInput.current.offsetWidth)
}
render () {
return (
// new way - as of [email protected]
<div ref={this.myInput}>some elem</div>
// legacy way
// <div ref={(ref) => this.myInput = ref}>some elem</div>
)
}
}
Here's a simplest example from ASP.NET Community, this gave me a clear understanding on the concept....
what difference does this make?
For an example of this, here is a way to put focus on a text box on a page when the page is loaded into the browser—with Visual Basic using the RegisterStartupScript
method:
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Testing", _
"document.forms[0]['TextBox1'].focus();", True)
This works well because the textbox on the page is generated and placed on the page by the time the browser gets down to the bottom of the page and gets to this little bit of JavaScript.
But, if instead it was written like this (using the RegisterClientScriptBlock
method):
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Testing", _
"document.forms[0]['TextBox1'].focus();", True)
Focus will not get to the textbox control and a JavaScript error will be generated on the page
The reason for this is that the browser will encounter the JavaScript before the text box is on the page. Therefore, the JavaScript will not be able to find a TextBox1.
select a.id, a.object
from table_A a
inner join table_B b on a.id=b.id
where b.tag = 'chair';
Assuming HTTP authentication (WWW-Authenticate and Authorization headers) is in use, if authenticating as another user would grant access to the requested resource, then 401 Unauthorized should be returned.
403 Forbidden is used when access to the resource is forbidden to everyone or restricted to a given network or allowed only over SSL, whatever as long as it is no related to HTTP authentication.
If HTTP authentication is not in use and the service a cookie-based authentication scheme as is the norm nowadays, then a 403 or a 404 should be returned.
Regarding 401, this is from RFC 7235 (Hypertext Transfer Protocol (HTTP/1.1): Authentication):
3.1. 401 Unauthorized
The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. The origin server MUST send a WWW-Authenticate header field (Section 4.4) containing at least one challenge applicable to the target resource. If the request included authentication credentials, then the 401 response indicates that authorization has been refused for those credentials. The client MAY repeat the request with a new or replaced Authorization header field (Section 4.1). If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user agent SHOULD present the enclosed representation to the user, since it usually contains relevant diagnostic information.
The semantics of 403 (and 404) have changed over time. This is from 1999 (RFC 2616):
10.4.4 403 Forbidden
The server understood the request, but is refusing to fulfill it.
Authorization will not help and the request SHOULD NOT be repeated.
If the request method was not HEAD and the server wishes to make
public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404
(Not Found) can be used instead.
In 2014 RFC 7231 (Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content) changed the meaning of 403:
6.5.3. 403 Forbidden
The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).
If authentication credentials were provided in the request, the
server considers them insufficient to grant access. The client
SHOULD NOT automatically repeat the request with the same
credentials. The client MAY repeat the request with new or different credentials. However, a request might be forbidden for reasons
unrelated to the credentials.An origin server that wishes to "hide" the current existence of a
forbidden target resource MAY instead respond with a status code of
404 (Not Found).
Thus, a 403 (or a 404) might now mean about anything. Providing new credentials might help... or it might not.
I believe the reason why this has changed is RFC 2616 assumed HTTP authentication would be used when in practice today's Web apps build custom authentication schemes using for example forms and cookies.
You can use show tables
or show collections
.
You can use multiple ordering on multiple condition,
ORDER BY
(CASE
WHEN @AlphabetBy = 2 THEN [Drug Name]
END) ASC,
CASE
WHEN @TopBy = 1 THEN [Rx Count]
WHEN @TopBy = 2 THEN [Cost]
WHEN @TopBy = 3 THEN [Revenue]
END DESC
I found this answer works for me
<style type="text/css">
#background{
position: fixed;
top: 0;
left: 0;
width: 100% !important;
height: 100% !important;
background: url(mobile-images/limo-service.jpg) no-repeat center center fixed !important;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
z-index: -1;
}
.ui-page{
background:none;
}
</style>
also add id="background"
to the div for your content section
<div data-role="page" data-theme="a">
<div data-role="main" class="ui-content" id="background">
</div>
</div>
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
You should set both your table encoding and connection encoding to UTF-8
:
ALTER TABLE keywords CHARACTER SET UTF8; -- run once
and
SET NAMES 'UTF8';
SET CHARACTER SET 'UTF8';
Assuming that your branch is called master
both here and remotely, and that your remote is called origin
you could do:
git reset --hard <commit-hash>
git push -f origin master
However, you should avoid doing this if anyone else is working with your remote repository and has pulled your changes. In that case, it would be better to revert the commits that you don't want, then push as normal.
$no_newlines = str_replace("\r", '', str_replace("\n", '', $str_with_newlines));
When you open a transaction nothing gets locked by itself. But if you execute some queries inside that transaction, depending on the isolation level, some rows, tables or pages get locked so it will affect other queries that try to access them from other transactions.
If you have a SSHClient, you can also use open_sftp()
:
import paramiko
# lets say you have SSH client...
client = paramiko.SSHClient()
sftp = client.open_sftp()
# then you can use upload & download as shown above
...
Check out How to Install Pip article article for more information.
As of 2019,
Download get-pip.py provided by https://pip.pypa.io using the following command:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
Run get-pip.py using the following command:
sudo python get-pip.py
After you done installing, run this command to check if pip is installed.
pip --version
Remove get-pip.py file after installing pip.
rm get-pip.py
Also if you want to save some money you don't must buy a Mac. There is other ways how to do it:
1.) You can use practically any OS to run latest MacOS in virtual machine (look at YouTube). I am using this method really long time without any problems on windows with VMWare.
2.) Hackintosh. Install MacOS to your PC. You must have compatible components, but if you have, this is the best way, because you eliminate the lags in VM... I am using this in this time. Perfect. On my laptop, but please don't tell this to Apple, because practically this is illegal
3.) If you are making simple apps with minimum UI, you can use Theos. Also with Theos you can create cydia tweaks. Only one problem: codesign. If you want to publish app on App Store you still must have MacOS, but if you want to make app in home you can use CydiaImpactor to sign the apps with Apple ID.
I used all of this ways and all is working. By my VM is best solution if you don't want to spend lot of time by installing Hackintosh.
I just went into the manifest and changed android:label="...." to the name of the application. Once Id changed this, the title and the actual app name changed to that :)
I'm using varchar(15)
so far everything is working for me. Insert, Update, Select. I have just started an app that has IP Addresses, though I have not done much dev work yet.
Here is the select statement:
select * From dbo.Server
where [IP] = ('132.46.151.181')
Go
I have created a function in PHP language to get browser name, browser version, operating system (windows/linux etc.) along with device type (desktop / mobile / tablet).
function getBrowserInfo(){
$browserInfo = array('user_agent'=>'','browser'=>'','browser_version'=>'','os_platform'=>'','pattern'=>'', 'device'=>'');
$u_agent = $_SERVER['HTTP_USER_AGENT'];
$bname = 'Unknown';
$ub = 'Unknown';
$version = "";
$platform = 'Unknown';
$deviceType='Desktop';
if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$u_agent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($u_agent,0,4))){
$deviceType='Mobile';
}
if($_SERVER['HTTP_USER_AGENT'] == 'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10') {
$deviceType='Tablet';
}
if(stristr($_SERVER['HTTP_USER_AGENT'], 'Mozilla/5.0(iPad;')) {
$deviceType='Tablet';
}
//$detect = new Mobile_Detect();
//First get the platform?
if (preg_match('/linux/i', $u_agent)) {
$platform = 'linux';
} elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
$platform = 'mac';
} elseif (preg_match('/windows|win32/i', $u_agent)) {
$platform = 'windows';
}
// Next get the name of the user agent yes seperately and for good reason
if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
{
$bname = 'IE';
$ub = "MSIE";
} else if(preg_match('/Firefox/i',$u_agent))
{
$bname = 'Mozilla Firefox';
$ub = "Firefox";
} else if(preg_match('/Chrome/i',$u_agent) && (!preg_match('/Opera/i',$u_agent) && !preg_match('/OPR/i',$u_agent)))
{
$bname = 'Chrome';
$ub = "Chrome";
} else if(preg_match('/Safari/i',$u_agent) && (!preg_match('/Opera/i',$u_agent) && !preg_match('/OPR/i',$u_agent)))
{
$bname = 'Safari';
$ub = "Safari";
} else if(preg_match('/Opera/i',$u_agent) || preg_match('/OPR/i',$u_agent))
{
$bname = 'Opera';
$ub = "Opera";
} else if(preg_match('/Netscape/i',$u_agent))
{
$bname = 'Netscape';
$ub = "Netscape";
} else if((isset($u_agent) && (strpos($u_agent, 'Trident') !== false || strpos($u_agent, 'MSIE') !== false)))
{
$bname = 'Internet Explorer';
$ub = 'Internet Explorer';
}
// finally get the correct version number
$known = array('Version', $ub, 'other');
$pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
if (!preg_match_all($pattern, $u_agent, $matches)) {
// we have no matching number just continue
}
// see how many we have
$i = count($matches['browser']);
if ($i != 1) {
//we will have two since we are not using 'other' argument yet
//see if version is before or after the name
if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
$version= $matches['version'][0];
} else {
$version= @$matches['version'][1];
}
} else {
$version= $matches['version'][0];
}
// check if we have a number
if ($version==null || $version=="") {$version="?";}
return array(
'user_agent' => $u_agent,
'browser' => $bname,
'browser_version' => $version,
'os_platform' => $platform,
'pattern' => $pattern,
'device' => $deviceType
);
}
This solved my problem of browser detection, I hope, this will also help you. Thank you.
You should use nested query as:
SELECT *
FROM ANY_TABLE_X
WHERE ANY_COLUMN_X = (SELECT MAX(ANY_COLUMN_X) FROM ANY_TABLE_X)
=> In PL/SQL "ROWNUM = 1" is NOT equal to "TOP 1" of TSQL.
So you can't use a query like this: "select * from any_table_x where rownum=1 order by any_column_x;" Because oracle gets first row then applies order by clause.
The way you did is correct. It works fine with that code: x is true. probably you made a mistake somewhere else.
List<int> ints = new List<int>( new[] {1,5,7}); // 1
List<int> intlist=new List<int>() { 0,2,3,4,1}; // 2
var i = 5;
var x = ints.Contains(i); // return true or false
I have tried all the solutions and this one worked for me
let temp = base64String.components(separatedBy: ",")
let dataDecoded : Data = Data(base64Encoded: temp[1], options:
.ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)
yourImage.image = decodedimage
I wrote quick test program to demonstrate one difference:
#include <stdio.h>
enum {ENUM_DEFINED=16};
enum {ENUM_DEFINED=32};
#define DEFINED_DEFINED 16
#define DEFINED_DEFINED 32
int main(int argc, char *argv[]) {
printf("%d, %d\n", DEFINED_DEFINED, ENUM_DEFINED);
return(0);
}
This compiles with these errors and warnings:
main.c:6:7: error: redefinition of enumerator 'ENUM_DEFINED'
enum {ENUM_DEFINED=32};
^
main.c:5:7: note: previous definition is here
enum {ENUM_DEFINED=16};
^
main.c:9:9: warning: 'DEFINED_DEFINED' macro redefined [-Wmacro-redefined]
#define DEFINED_DEFINED 32
^
main.c:8:9: note: previous definition is here
#define DEFINED_DEFINED 16
^
Note that enum gives an error when define gives a warning.
To change the "..." when the mouse hovers over the calendar icon, You need to add the following in the datepicker options:
showOn: 'button',
buttonText: 'Click to show the calendar',
buttonImageOnly: true,
buttonImage: 'images/cal2.png',
wget -S -i *file*
will get you the headers from each url in a file.
Filter though grep
for the status code specifically.
Don't build directory and file names your self, use python's included libraries.
In this case the relevant one is os.path. Especially join which creates a new pathname from a directory and a file name or directory and split that gets the filename from a full path.
Your example would be
pathfile=os.path.dirname(templateFile)
p = os.path.join(pathfile, 'output')
p = os.path.join( p, 'log.txt')
rootTree.write(p)
You can use filter like this
angular.module('app').filter('trustAs', ['$sce',
function($sce) {
return function (input, type) {
if (typeof input === "string") {
return $sce.trustAs(type || 'html', input);
}
console.log("trustAs filter. Error. input isn't a string");
return "";
};
}
]);
usage
<div ng-bind-html="myData | trustAs"></div>
it can be used for other resource types, for example source link for iframes and other types declared here
Three ways you can do that:-
Approach 1:-
// using spread ...
let obj1 = {
...obj2
};
Approach2:-
// using Object.assign() method
let obj1 = Object.assign({}, obj2);
Approach3:-
// using JSON
let obj1 = JSON.parse(JSON.stringify(obj2));
You can try this:
/// <summary>
/// Remove all extra spaces and tabs between words in the specified string!
/// </summary>
/// <param name="str">The specified string.</param>
public static string RemoveExtraSpaces(string str)
{
str = str.Trim();
StringBuilder sb = new StringBuilder();
bool space = false;
foreach (char c in str)
{
if (char.IsWhiteSpace(c) || c == (char)9) { space = true; }
else { if (space) { sb.Append(' '); }; sb.Append(c); space = false; };
}
return sb.ToString();
}
I had the same issue inside an alpine docker container, my solution was to add the boost-dev apk library because libboost-dev was not available.
To decompile APK Use APKTool.
You can learn how APKTool works on http://www.decompileandroid.com/ or by reading the documentation.
You can practice Regex In Visual Studio and Visual Studio Code using find/replace.
You need to select both Match Case and Regular Expressions for regex expressions with case. Else [A-Z] won't work.enter image description here
Another option (which is useful e.g. for scientific purposes when you need to work with segmentation masks) is simply apply a threshold:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Binarize (make it black and white) an image with Python."""
from PIL import Image
from scipy.misc import imsave
import numpy
def binarize_image(img_path, target_path, threshold):
"""Binarize an image."""
image_file = Image.open(img_path)
image = image_file.convert('L') # convert image to monochrome
image = numpy.array(image)
image = binarize_array(image, threshold)
imsave(target_path, image)
def binarize_array(numpy_array, threshold=200):
"""Binarize a numpy array."""
for i in range(len(numpy_array)):
for j in range(len(numpy_array[0])):
if numpy_array[i][j] > threshold:
numpy_array[i][j] = 255
else:
numpy_array[i][j] = 0
return numpy_array
def get_parser():
"""Get parser object for script xy.py."""
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
parser = ArgumentParser(description=__doc__,
formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument("-i", "--input",
dest="input",
help="read this file",
metavar="FILE",
required=True)
parser.add_argument("-o", "--output",
dest="output",
help="write binarized file hre",
metavar="FILE",
required=True)
parser.add_argument("--threshold",
dest="threshold",
default=200,
type=int,
help="Threshold when to show white")
return parser
if __name__ == "__main__":
args = get_parser().parse_args()
binarize_image(args.input, args.output, args.threshold)
It looks like this for ./binarize.py -i convert_image.png -o result_bin.png --threshold 200
:
I found that DataGridViewTextBox
values and some JSON objects don't equal Null but instead are "{}"
values. Comparing them to Null doesn't work but using these do the trick:
if (cell.Value is System.DBNull)
if (cell.Value == System.DBNull.Value)
A good excerpt I found concerning the difference between Null and DBNull:
Do not confuse the notion of null in an object-oriented programming language with a DBNull object. In an object-oriented programming language, null means the absence of a reference to an object. DBNull represents an uninitialized variant or nonexistent database column.
You can learn more about the DBNull class here.
You can use following lines of code to insert values into an already existing table. Here the table is db_name.table_name having two columns, and I am inserting 'All','done' as a row in the table.
insert into table db_name.table_name
select 'ALL','Done';
Hope this was helpful.
The Extensible Markup Language (XML) 1.0 only includes the block comments.
Why do you do it manually? yield return
automates the entire process of handling iterators. (I also wrote about it on my blog, including a look at the compiler generated code).
If you really want to do it yourself, you have to return a generic enumerator too. You won't be able to use an ArrayList
any more since that's non-generic. Change it to a List<MyObject>
instead. That of course assumes that you only have objects of type MyObject
(or derived types) in your collection.
My solution for a Date/Time parameter:
=CDate(Today())
The trick is to convert back to a DateTime as recommend Perhentian.
you can try to use
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
instead of
androidTestCompile 'com.android.support.test:runner:0.4.1'
androidTestCompile 'com.android.support.test:rules:0.4.1'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
androidTestCompile 'com.android.support.test.espresso:espresso-contrib:2.2.1'
The following query work for me:
select TABLE_NAME tabla,COLUMN_NAME columna
from INFORMATION_SCHEMA.COLUMNS
where COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
order by TABLE_NAME
I think you need an additionally query because the charset option in the DSN is actually ignored. see link posted in the comment of the other answer.
Looking at how Drupal 7 is doing it in http://api.drupal.org/api/drupal/includes--database--mysql--database.inc/function/DatabaseConnection_mysql%3A%3A__construct/7:
// Force MySQL to use the UTF-8 character set. Also set the collation, if a
// certain one has been set; otherwise, MySQL defaults to 'utf8_general_ci'
// for UTF-8.
if (!empty($connection_options['collation'])) {
$this->exec('SET NAMES utf8 COLLATE ' . $connection_options['collation']);
}
else {
$this->exec('SET NAMES utf8');
}
I have just come back to this and I had to install scipy as matplotlib.mlab gave me the error message MatplotlibDeprecationWarning: scipy.stats.norm.pdf
when trying example above. So the sample is now:
%matplotlib inline
import math
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats
mu = 0
variance = 1
sigma = math.sqrt(variance)
x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)
plt.plot(x, scipy.stats.norm.pdf(x, mu, sigma))
plt.show()
My one stop solution for Linux commands on windows is scoop. Install scoop from scoop.sh
scoop install openssl
openssl rand -base64 32
Dca3c3pptVkcb8fx243wN/3f/rQxx/rWYL8y7rZrGrA=
You could open two textstreams, one for reading
Set filestreamIn = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt,1)
and one for appending
Set filestreamOUT = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt,8,true)
The filestreamIN can read from the begining of the file, and the filestreamOUT can write to the end of the file.
Why not just call window.open straight from OnClick?
<asp:Button ID="btnNewEntry" runat="Server" CssClass="button" Text="New Entry" OnClick="window.open('New.aspx')" />
Try this
button.addTarget(self, action:#selector(handleRegister()), for: .touchUpInside).
Just add parenthesis with name of method.
Also you can refer link : Value of type 'CustomButton' has no member 'touchDown'
Check the androidmanifest.xml
file and layoutfolder xml files. They should be created properly as the starting and ending clause in xml should be placed properly. Update the files, clean and build. And all set!
In Kotlin you can do as
val videoView = findViewById<VideoView>(R.id.videoView)
// If url is from raw
/* val url = "android.resource://" + packageName
.toString() + "/" + R.raw.video*/
// If url is from network
val url = "http://www.servername.com/projects/projectname/videos/1361439400.mp4"
val video =
Uri.parse(url)
videoView.setVideoURI(video)
videoView.setOnPreparedListener{
videoView.start()
}
Update: AdoptOpenJDK has changed its name to Adoptium, as part of its move to the Eclipse Foundation.
Difference between OpenJDK and AdoptOpenJDK
The first provides source-code, the other provides builds of that source-code.
Adoptium of the Eclipse Foundation, formerly known as AdoptOpenJDK, is only one of several vendors distributing implementations of the Java platform. These include:
See this flowchart of mine to help guide you in picking a vendor for an implementation of the Java platform. Click/tap to zoom.
Another resource: This comparison matrix by Azul Systems is useful, and seems true and fair to my mind.
Here is a list of considerations and motivations to consider in choosing a vendor and implementation.
Some vendors offer you a choice of JIT technologies.
To understand more about this Java ecosystem, read Java Is Still Free
If you want to insert only few rows and u have JPA Setup. You can use below
@SpringBootApplication
@Slf4j
public class HospitalManagementApplication {
public static void main(String[] args) {
SpringApplication.run(HospitalManagementApplication.class, args);
}
@Bean
ApplicationRunner init(PatientRepository repository) {
return (ApplicationArguments args) -> dataSetup(repository);
}
public void dataSetup(PatientRepository repository){
//inserts
}
Doing
SET FOREIGN_KEY_CHECKS=0;
before the Operation can also do the trick.
This is what I use:
private void ExpireAllCookies()
{
if (HttpContext.Current != null)
{
int cookieCount = HttpContext.Current.Request.Cookies.Count;
for (var i = 0; i < cookieCount; i++)
{
var cookie = HttpContext.Current.Request.Cookies[i];
if (cookie != null)
{
var expiredCookie = new HttpCookie(cookie.Name) {
Expires = DateTime.Now.AddDays(-1),
Domain = cookie.Domain
};
HttpContext.Current.Response.Cookies.Add(expiredCookie); // overwrite it
}
}
// clear cookies server side
HttpContext.Current.Request.Cookies.Clear();
}
}
If you can live with 3. and 3.0 appearing as "3.0", a very simple approach that right-strips zeros from float representations:
print("%s"%3.140)
(thanks @ellimilial for pointing out the exceptions)
As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:
<?php
$world = _("World");
$str = <<<EOF
<p>Hello</p>
<p>$world</p>
EOF;
echo $str;
?>
a workaround idea that comes to mind is building a class with a magic getter method.
You would declare a class like this:
class Translator
{
public function __get($name) {
return _($name); // Does the gettext lookup
}
}
Initialize an object of the class at some point:
$translate = new Translator();
You can then use the following syntax to do a gettext lookup inside a HEREDOC block:
$str = <<<EOF
<p>Hello</p>
<p>{$translate->World}</p>
EOF;
echo $str;
?>
$translate->World
will automatically be translated to the gettext lookup thanks to the magic getter method.
To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!
, you will have to use the following notation:
$translate->{"Hello World!!!!!!"}
This is all untested but should work.
Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.
When non of the above works, and still mails looks like ª הודפסה ×•× ×©×œ
:
$mail->addCustomHeader('Content-Type', 'text/plain;charset=utf-8');
$mail->Subject = '=?UTF-8?B?' . base64_encode($subject) . '?=';;
viewPager.addOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
switch (position) {
case 0:
img_page1.setImageResource(R.drawable.dot_selected);
img_page2.setImageResource(R.drawable.dot);
img_page3.setImageResource(R.drawable.dot);
img_page4.setImageResource(R.drawable.dot);
break;
case 1:
img_page1.setImageResource(R.drawable.dot);
img_page2.setImageResource(R.drawable.dot_selected);
img_page3.setImageResource(R.drawable.dot);
img_page4.setImageResource(R.drawable.dot);
break;
case 2:
img_page1.setImageResource(R.drawable.dot);
img_page2.setImageResource(R.drawable.dot);
img_page3.setImageResource(R.drawable.dot_selected);
img_page4.setImageResource(R.drawable.dot);
break;
case 3:
img_page1.setImageResource(R.drawable.dot);
img_page2.setImageResource(R.drawable.dot);
img_page3.setImageResource(R.drawable.dot);
img_page4.setImageResource(R.drawable.dot_selected);
break;
default:
break;
}
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
});
You need to open TCP port 8787 in the ec2 Security Group. Also need to open the same port on the EC2 instance's firewall.
If you prefer splitting a CSV list in SQL, there's a different way to do it using Common Table Expressions (CTEs). See Efficient way to string split using CTE.
You can use git log
with the pathnames of the respective folders:
git log A B
The log will only show commits made in A
and B
. I usually throw in --stat
to make things a little prettier, which helps for quick commit reviews.
Hi,
Well, I have tried the methods mentioned above! it's working yes, but not exactly the way I wanted. I wanted to redirect the default page extension to the main domain with our further action.
Here how I do that...
# Accesible Index Page
<IfModule dir_module>
DirectoryIndex index.php index.html
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.(html|htm|php|php3|php5|shtml|phtml) [NC]
RewriteRule ^index\.html|htm|php|php3|php5|shtml|phtml$ / [R=301,L]
</IfModule>
The above code simply captures any index.* and redirect it to the main domain.
Thank you
How bad is this?
function(obj){
for(var key in obj){
return false; // not empty
}
return true; // empty
}