qid
int64 46k
74.7M
| question
stringlengths 54
37.8k
| date
stringlengths 10
10
| metadata
listlengths 3
3
| response_j
stringlengths 17
26k
| response_k
stringlengths 26
26k
|
|---|---|---|---|---|---|
2,040,616
|
When I run my python script I get the following warning
```
DeprecationWarning: the sets module is deprecated
```
How do I fix this?
|
2010/01/11
|
[
"https://Stackoverflow.com/questions/2040616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247873/"
] |
If you want to fix it James definitely has the right answer, but in case you want to just turn off deprecation warnings, you can run python like so:
```
$ python -Wignore::DeprecationWarning
Python 2.6.2 (r262:71600, Sep 20 2009, 20:47:22)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sets
>>>
```
(From: <http://puzzling.org/logs/thoughts/2009/May/3/python26-deprecation-warning>)
You can also ignore it programmatically:
```
import warnings
warnings.simplefilter("ignore", DeprecationWarning)
```
|
Use the built-in `set` instead of importing and using `sets` module.
From [documentation](http://docs.python.org/whatsnew/2.6.html):
>
> The sets module has been deprecated;
> it’s better to use the built-in set
> and frozenset types.
>
>
>
|
2,040,616
|
When I run my python script I get the following warning
```
DeprecationWarning: the sets module is deprecated
```
How do I fix this?
|
2010/01/11
|
[
"https://Stackoverflow.com/questions/2040616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247873/"
] |
History:
Before Python 2.3: no set functionality
Python 2.3: `sets` module arrived
Python 2.4: `set` and `frozenset` built-ins introduced
Python 2.6: `sets` module deprecated
You should change your code to use `set` instead of `sets.Set`.
If you still wish to be able to support using Python 2.3, you can do this at the start of your script:
```
try:
set
except NameError:
from sets import Set as set
```
|
If you want to fix it James definitely has the right answer, but in case you want to just turn off deprecation warnings, you can run python like so:
```
$ python -Wignore::DeprecationWarning
Python 2.6.2 (r262:71600, Sep 20 2009, 20:47:22)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sets
>>>
```
(From: <http://puzzling.org/logs/thoughts/2009/May/3/python26-deprecation-warning>)
You can also ignore it programmatically:
```
import warnings
warnings.simplefilter("ignore", DeprecationWarning)
```
|
5,118,608
|
I'm novice in python and got a problem in which I would appreciate some help.
The problem in short:
1. ask for a string
2. check if all letter in a predefined list
3. if any letter is not in the list then ask for a new string, otherwise go to next step
4. ask for a second string
5. check again whether the second string's letters in the list
6. if any letter is not in the list then start over with asking for a new **FIRST** string
basicly my main question is how to go back to a previous part of my program, and it would also help if someone would write me the base of this code.
It start like this:
```
list1=[a,b,c,d]
string1=raw_input("first:")
for i in string1:
if i not in list1:
```
Thanks
|
2011/02/25
|
[
"https://Stackoverflow.com/questions/5118608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/634333/"
] |
I suggest you start here: <http://docs.python.org/tutorial/introduction.html#first-steps-towards-programming>
And continue to next chapter: <http://docs.python.org/tutorial/controlflow.html>
|
You have a couple of options, you could use iteration, or recursion. For this kind of problem I would go with iteration. If you don't know what iteration and recursion are, and how they work in Python then you should use the links Kugel suggested.
|
5,118,608
|
I'm novice in python and got a problem in which I would appreciate some help.
The problem in short:
1. ask for a string
2. check if all letter in a predefined list
3. if any letter is not in the list then ask for a new string, otherwise go to next step
4. ask for a second string
5. check again whether the second string's letters in the list
6. if any letter is not in the list then start over with asking for a new **FIRST** string
basicly my main question is how to go back to a previous part of my program, and it would also help if someone would write me the base of this code.
It start like this:
```
list1=[a,b,c,d]
string1=raw_input("first:")
for i in string1:
if i not in list1:
```
Thanks
|
2011/02/25
|
[
"https://Stackoverflow.com/questions/5118608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/634333/"
] |
I suggest you start here: <http://docs.python.org/tutorial/introduction.html#first-steps-towards-programming>
And continue to next chapter: <http://docs.python.org/tutorial/controlflow.html>
|
This sounds like a job for a while loop
<http://www.tutorialspoint.com/python/python_while_loop.htm>
pseudo code is
```
list=[a,b,c,d]
declare boolean passes = false
while (!passes)
passes = true
String1 = raw_input("first:")
foreach char in string1
if !list.contains(char)
passes = false
break
if passes
String2 = raw_input("second:")
foreach char in string2
if !list.contains(char)
passes = false
break
```
|
5,118,608
|
I'm novice in python and got a problem in which I would appreciate some help.
The problem in short:
1. ask for a string
2. check if all letter in a predefined list
3. if any letter is not in the list then ask for a new string, otherwise go to next step
4. ask for a second string
5. check again whether the second string's letters in the list
6. if any letter is not in the list then start over with asking for a new **FIRST** string
basicly my main question is how to go back to a previous part of my program, and it would also help if someone would write me the base of this code.
It start like this:
```
list1=[a,b,c,d]
string1=raw_input("first:")
for i in string1:
if i not in list1:
```
Thanks
|
2011/02/25
|
[
"https://Stackoverflow.com/questions/5118608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/634333/"
] |
I suggest you start here: <http://docs.python.org/tutorial/introduction.html#first-steps-towards-programming>
And continue to next chapter: <http://docs.python.org/tutorial/controlflow.html>
|
Another good place to start is by looking for common sequences of action and putting them in a separate subroutine.
```
# ignore this bit - it's here for compatibility
try:
inp = raw_input # Python 2.x
except NameError:
inp = input # Python 3.x
# this wraps the 'ask for a string, check if all characters are valid' bit in a single call
def GetValidString(msg, validChars):
i = inp(msg)
if all(ch in validChars for ch in i):
return i
else:
return None
def main():
while True:
str1 = GetValidInput('first: ', 'aeiou'):
if str1:
str2 = GetValidInput('second: ', 'rstvy'):
if str2:
break # good! we can leave the loop now
# got valid values for str1 and str2
```
the logic looks like 'loop until you get string1 and it is good and you get string2 and it is also good'.
Hope that helps.
|
52,345,375
|
i'm new with python and wants to do the following:
1. search inside text to check if token exists
2. token cannot be substring inside the text - must be "as is" (string11111 is not string1)
```
file = "string11111 aaaaa string1 bbbbb"
token = "string1"
if token in file:
print "NOT yay!"
```
3. token needs to be searched for end position to beginning (reversly)
|
2018/09/15
|
[
"https://Stackoverflow.com/questions/52345375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1596023/"
] |
First tokenize your `file` variable
```
tokens = file.split()
```
Then look for your token
```
if token in tokens:
# do your thing
```
|
hoping the below solution meets your need -
```
file = "string11111 aaaaa string1 bbbbb"
token = "string1"
token_matched = [file_token for file_token in file.split()[::-1] if token in file_token and len(token) == len(file_token)]
print('Matched tokens (reverse order) - ', token_matched)
if len(token_matched) > 1:
# Reoccurs more than one time which means the token could be sub-string
print("NOT yay!")
elif len(token_matched) == 1:
# Matches only time definitely it could not be the sub-string
print("OHH yay!")
else:
print("Token not exist in file.")
```
|
52,345,375
|
i'm new with python and wants to do the following:
1. search inside text to check if token exists
2. token cannot be substring inside the text - must be "as is" (string11111 is not string1)
```
file = "string11111 aaaaa string1 bbbbb"
token = "string1"
if token in file:
print "NOT yay!"
```
3. token needs to be searched for end position to beginning (reversly)
|
2018/09/15
|
[
"https://Stackoverflow.com/questions/52345375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1596023/"
] |
First tokenize your `file` variable
```
tokens = file.split()
```
Then look for your token
```
if token in tokens:
# do your thing
```
|
Try this one, using regex
```
file = "string11111 aaaaa string1 bbbbb"[::-1]
token = "string1"
regex = r"\b" + re.escape(token) + r"\b"
match = re.findall(regex , file)[0]
if match in file:
print "NOT yay!"
```
|
58,603,894
|
I am trying to convert the below mentioned json string to python dictionary. I am using python 3's json package for the same. Here is the code that I am using :
```
a = "[{'id': 35, 'name': 'Comedy'}, {'id': 18, 'name': 'Drama'}, {'id': 10751, 'name': 'Family'}, {'id': 10749, 'name': 'Romance'}]"
b = json.loads(json.dumps(a))
print(type(b))
```
And the output that I am getting from the above code is:
>
> <class 'str'>
>
>
>
I saw the similar questions asked in stackoverflow, but the solutions presented for those questions do not apply to my case.
|
2019/10/29
|
[
"https://Stackoverflow.com/questions/58603894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4720757/"
] |
The json string that you are trying to convert is not properly formatted. Also, you need to only call json.loads to convert string into `dict` or `list`.
The updated code would look like:
```
import json
a = '[{"id": 35, "name": "Comedy"}, {"id": 18, "name": "Drama"}, {"id": 10751, "name": "Family"}, {"id": 10749, "name": "Romance"}]'
b = json.loads(a)
print(type(b))
```
Hope this explains why you are not getting the expected results.
|
**JSON Array** is enclosed in `[ ]` while **JSON object** is enclosed in `{ }`
>
> The string in `a` is a *json array* so you can change that into a *list* only.
>
>
>
>
Your *key and value should be enclosed with double quotes*, that's the requirement to use json library of python.
>
> `b = json.loads(a)` will give a list of dictionary objects.
>
>
>
To get further dictionary of dictionary you need to associate a key with each individual dictionary.
```
d = dict()
ind = 0
for data in b:
d[ind] = data
ind+=1
```
Now the output that you get will be
`{0: {'id': 35, 'name': 'Comedy'}, 1: {'id': 18, 'name': 'Drama'}, 2: {'id': 10751, 'name': 'Family'}, 3: {'id': 10749, 'name': 'Romance'}}`
which is a dictionary of dictionary.
Thank you
|
44,780,952
|
So I'm writing a Python program that reads lines of serial data, and compares them to a dictionary of line codes to figure out which specific lines are being transmitted. I am attempting to use a Regular Expression in order to filter out the extra garbage line serial read string has on it, but I'm having a bit of an issue.
Every single code in my dictionary looks like this: `T12F8B0A22**F8`. The asterisks are the two alpha numeric pieces that differentiate each string code.
This is what I have so far as my regex: `'/^T12F8B0A22[A-Z0-9]{2}F8$/'`
I am getting a few errors with this however. My first error, is that there are some characters are the end of the string I still need to get rid of, which is odd because I thought `$/` denoted the end of the line in regex. However when I run my code through the debugger I notice that after running through the following code:
```
#regexString contains the serial read line data
regexString = re.sub('/^T12F8B0A22[A-Z0-9]{2}F8$/', '', regexString)
```
My string looks something like this: `'T12F8B0A2200F8\\r'`
I need to get rid of the `\\r`.
If for some reason I can't get rid of this with regex, how in python do you send specific string character through an argument? In this case I suppose it would be length - 3?
|
2017/06/27
|
[
"https://Stackoverflow.com/questions/44780952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3711832/"
] |
Your problem is threefold:
1) your string contains extra `\r` (Carriage Return character) before `\n` (New Line character); this is common in Windows and in network communication protocols; it is probably best to remove any trailing whitespace from your string:
```
regexString = regexString.rstrip()
```
2) as mentioned by Wiktor Stribiżew, your regexp is unnecessarily surrounded with `/` characters - some languages, like Perl, define regexp as a string delimited by `/` characters, but Python is not one of them;
3) your instruction using `re.sub` is actually replacing the matching part of `regexString` with an empty string - I believe this is the exact opposite of what you want (you want to **keep** the match and remove everything else, right?); that's why fixing the regexp makes things "even worse".
To summarize, I think you should use this instead of your current code:
```
m = re.match('T12F8B0A22[A-Z0-9]{2}F8', regexString)
regexString = m.group(0)
```
|
There are several ways to get rid of the "\r", but first a little analysis of your code :
1. the special charakter for the end is just '$' not '$\' in python.
2. re.sub will substitute the matched pattern with a string ( '' in your case) wich would substitute the string you want to get with an empty string and you are left with the //r
possible solutions:
1. use simple replace:
```
regexString.replace('\\r','')
```
2. if you want to stick to regex the approach is the same
```
pattern = '\\\\r'
match = re.sub(pattern, '',regexString)
```
2.2 if you want the acces the different groubs use re.search
```
match = re.search('(^T12F8B0A22[A-Z0-9]{2}F8)(.*)',regexString)
match.group(1) # will give you the T12...
match.groupe(2) # gives you the \\r
```
|
44,780,952
|
So I'm writing a Python program that reads lines of serial data, and compares them to a dictionary of line codes to figure out which specific lines are being transmitted. I am attempting to use a Regular Expression in order to filter out the extra garbage line serial read string has on it, but I'm having a bit of an issue.
Every single code in my dictionary looks like this: `T12F8B0A22**F8`. The asterisks are the two alpha numeric pieces that differentiate each string code.
This is what I have so far as my regex: `'/^T12F8B0A22[A-Z0-9]{2}F8$/'`
I am getting a few errors with this however. My first error, is that there are some characters are the end of the string I still need to get rid of, which is odd because I thought `$/` denoted the end of the line in regex. However when I run my code through the debugger I notice that after running through the following code:
```
#regexString contains the serial read line data
regexString = re.sub('/^T12F8B0A22[A-Z0-9]{2}F8$/', '', regexString)
```
My string looks something like this: `'T12F8B0A2200F8\\r'`
I need to get rid of the `\\r`.
If for some reason I can't get rid of this with regex, how in python do you send specific string character through an argument? In this case I suppose it would be length - 3?
|
2017/06/27
|
[
"https://Stackoverflow.com/questions/44780952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3711832/"
] |
Your problem is threefold:
1) your string contains extra `\r` (Carriage Return character) before `\n` (New Line character); this is common in Windows and in network communication protocols; it is probably best to remove any trailing whitespace from your string:
```
regexString = regexString.rstrip()
```
2) as mentioned by Wiktor Stribiżew, your regexp is unnecessarily surrounded with `/` characters - some languages, like Perl, define regexp as a string delimited by `/` characters, but Python is not one of them;
3) your instruction using `re.sub` is actually replacing the matching part of `regexString` with an empty string - I believe this is the exact opposite of what you want (you want to **keep** the match and remove everything else, right?); that's why fixing the regexp makes things "even worse".
To summarize, I think you should use this instead of your current code:
```
m = re.match('T12F8B0A22[A-Z0-9]{2}F8', regexString)
regexString = m.group(0)
```
|
Just match what you want to find. Couple of examples:
```
import re
data = '''lots of
otherT12F8B0A2212F8garbage
T12F8B0A2234F8around
T12F8B0A22ABF8the
stringsT12F8B0A22CDF8
'''
print(re.findall('T12F8B0A22..F8',data))
```
>
> ['T12F8B0A2212F8', 'T12F8B0A2234F8', 'T12F8B0A22ABF8', 'T12F8B0A22CDF8']
>
>
>
```
m = re.search('T12F8B0A22..F8',data)
if m:
print(m.group(0))
```
>
> T12F8B0A2212F8
>
>
>
|
25,518,623
|
I wonder why the python magic method (**str**) always looking for the return statement rather a print method ?
```
class test:
def __init__(self):
print("constructor called")
def __call__(self):
print("callable")
def __str__(self):
return "string method"
obj=test() ## print constructor called
obj() ### print callable
print(obj) ## print string method
```
my question is why i can't use something like this inside the **str** method
```
def __str__(self):
print("string method")
```
|
2014/08/27
|
[
"https://Stackoverflow.com/questions/25518623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2199012/"
] |
This is more to enable the conversion of an object into a `str` - your users don't necessary want all that stuff be printed into the terminal whenever they want to do something like
```
text = str(obj_instance)
```
They want `text` to contain the result, not printed out onto the terminal.
Doing it your way, the code would effectively be this
```
text = print(obj_instance)
```
Which is kind of nonsensical because the result of print isn't typically useful and `text` won't contain the stream of text that was passed into `str` type.
As you already commented (but since deleted), not providing the correct type for the return value will cause an exception to be raised, for example:
```
>>> class C(object):
... def __str__(self):
... return None
...
>>> str(C())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __str__ returned non-string (type NoneType)
>>>
```
|
Because `__str__()` is used when you `print` the object, so the user is already calling `print` which needs the String that represent the Object - as a variable to pass back to the user's `print`
In the example you provided above, if `__str__` would print you would get:
```
print(obj)
```
translated into:
```
print(print("string method"))
```
|
56,063,686
|
I've just recently switched to PyTorch after getting frustrated in debugging tf and understand that it is equivalent to coding in numpy almost completely. My question is what are the permitted python aspects we can use in a PyTorch model (to be put completely on GPU) eg. if-else has to be implemented as follows in tensorflow
```
a = tf.Variable([1,2,3,4,5], dtype=tf.float32)
b = tf.Variable([6,7,8,9,10], dtype=tf.float32)
p = tf.placeholder(dtype=tf.float32)
ps = tf.placeholder(dtype=tf.bool)
li = [None]*5
li_switch = [True, False, False, True, True]
for i in range(5):
li[i] = tf.Variable(tf.random.normal([5]))
sess = tf.Session()
sess.run(tf.global_variables_initializer())
def func_0():
return tf.add(a, p)
def func_1():
return tf.subtract(b, p)
with tf.device('GPU:0'):
my_op = tf.cond(ps, func_1, func_0)
for i in range(5):
print(sess.run(my_op, feed_dict={p:li[i], ps:li_switch[i]}))
```
How would the structure change in pytorch for the above code? How to place the variables and ops above on GPU and parallelize the list inputs to our graph in pytorch?
|
2019/05/09
|
[
"https://Stackoverflow.com/questions/56063686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7779411/"
] |
The problem is that if it can only contain one of those words, then where it doesn't contain one of the keywords the SEARCH function will return an error. Capture that using IFERROR to set errors (values not found) to 0, and then get the MAX to find the position of the word that was found (if any). If no values are found, then the result will just be 0:
```
=MAX(INDEX(IFERROR(SEARCH({"Success","Unknown","Failed"},Q_DTL_GetAll__3[@Message]),0),))
```
|
You can use the normally entered function:
```
=AGGREGATE(14,6,SEARCH({"Success","Unknown","Failed"},Q_DTL_GetAll__3[@MESSAGE]),1)
```
Your `SEARCH` is returning an array of values. In the given case:
`{#VALUE!,42,#VALUE!}`
So you need some way of only returning the non-error value. `AGGREGATE` can do that.
This formula will return a `#NUM!` error if none of the words are present. You can handle that as you wish.
|
28,532,672
|
I have N 10-dimensional vectors where each element can have value of 0,1 or 2.
For example, `vector v=(0,1,1,2,0,1,2,0,1,1)` is one of the vectors.
Is there an algorithm (preferably in python) that compresses these vectors into a minimum number of Cartesian products. If not perfect solution, is there a algorithm that at least gives a good compression.
Example: the two "Cartesian vectors"
`([1,2], 0, 1, 0, 0, 0, 1, 1, [0,1], 0])` (gives 4 vectors) and `(0, 1, 0, 2, 0, 0, [0,2], 2, 0, 1)` (gives 2 vectors) gives optimal solution for the N=6 vectors:
```
1,0,1,0,0,0,1,1,0,0
2,0,1,0,0,0,1,1,0,0
1,0,1,0,0,0,1,1,1,0
2,0,1,0,0,0,1,1,1,0
0,1,0,2,0,0,0,2,0,1
0,1,0,2,0,0,2,2,0,1
```
|
2015/02/15
|
[
"https://Stackoverflow.com/questions/28532672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4570066/"
] |
Another alternative way is using [.one()](http://api.jquery.com/one/) (the handler is executed at most once per element per event type), something like this,
```
$(".done p").one('click', function() {
$(this).parent().attr("class", "item not-done");
$(this).parent().hide().prependTo('.list').fadeIn('.5s');
});
```
|
You just need to unbind the click handler, so the following should work:
```
$(".done p").click(function() {
$(this).parent().attr("class", "item not-done");
$(this).parent().hide().prependTo('.list').fadeIn('.5s');
$(this).unbind('click');
});
```
|
28,532,672
|
I have N 10-dimensional vectors where each element can have value of 0,1 or 2.
For example, `vector v=(0,1,1,2,0,1,2,0,1,1)` is one of the vectors.
Is there an algorithm (preferably in python) that compresses these vectors into a minimum number of Cartesian products. If not perfect solution, is there a algorithm that at least gives a good compression.
Example: the two "Cartesian vectors"
`([1,2], 0, 1, 0, 0, 0, 1, 1, [0,1], 0])` (gives 4 vectors) and `(0, 1, 0, 2, 0, 0, [0,2], 2, 0, 1)` (gives 2 vectors) gives optimal solution for the N=6 vectors:
```
1,0,1,0,0,0,1,1,0,0
2,0,1,0,0,0,1,1,0,0
1,0,1,0,0,0,1,1,1,0
2,0,1,0,0,0,1,1,1,0
0,1,0,2,0,0,0,2,0,1
0,1,0,2,0,0,2,2,0,1
```
|
2015/02/15
|
[
"https://Stackoverflow.com/questions/28532672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4570066/"
] |
You just need to unbind the click handler, so the following should work:
```
$(".done p").click(function() {
$(this).parent().attr("class", "item not-done");
$(this).parent().hide().prependTo('.list').fadeIn('.5s');
$(this).unbind('click');
});
```
|
Try
```
$(document).ready(function() {
// Handles new entry submissions
$('.entry-form').submit(function(event) {
var entryValue = $(".entry").val();
// if `entryValue` _not_ have class `not-done` ,
// prepend `done` having `entryValue` to `.list` ,
// add class `not-done`
if (!$(".not-done:contains(" + entryValue + ")").is("*")) {
var elem = $(".done:contains(" + entryValue + ")");
elem.attr("class", "item not-done")
.prependTo('.list').fadeIn('.5s');
} else {
// else detach `done` class having `entryValue` from `DOM`
console.log(entryValue + " already listed");
$(".done:contains(" + entryValue + ")").detach()
}
event.preventDefault();
$('.entry-form')[0].reset();
});
// Handles adding entries back into the list
$(".done p").click(function() {
$(this).parent().attr("class", "item not-done")
.hide().prependTo('.list').fadeIn('.5s');
});
});
```
```js
$(document).ready(function() {
// Handles new entry submissions
$('.entry-form').submit(function(event) {
var entryValue = $(".entry").val();
if (!$(".not-done:contains("+entryValue+")").is("*")) {
var elem = $(".done:contains("+entryValue+")");
elem.attr("class", "item not-done")
.prependTo('.list').fadeIn('.5s');
} else {
console.log(entryValue + " already listed");
$(".done:contains("+entryValue+")").detach()
}
event.preventDefault();
$('.entry-form')[0].reset();
});
// Handles adding entries back into the list
$(".done p").click(function() {
$(this).parent().attr("class", "item not-done")
.hide().prependTo('.list').fadeIn('.5s');
});
});
```
```css
/**
* Eric Meyer's Reset CSS v2.0 (http://meyerweb.com/eric/tools/css/reset/)
* http://cssreset.com
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
font-family: "Source Sans Pro";
font-weight: 300;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
body {
background-color: grey;
background-size: cover;
}
a {
text-decoration: none;
}
.container {
margin: 0 20%;
height: 100%;
}
.header {
height: 2em;
background-color: white;
-webkit-box-shadow: 0px 1px 2px -1px rgba(0,0,0,.5);
-moz-box-shadow: 0px 1px 2px -1px rgba(0,0,0,.5);
box-shadow: 0px 1px 2px -1px rgba(0,0,0,.5);
}
.header h2 {
position: relative;
top: 50%;
transform: translateY(-50%);
}
.main h1 {
text-align: center;
margin: 1em 0;
font-family: "Libre Bakersville";
font-weight: 700;
font-size: 2em;
color: white;
text-shadow: 1px 1px 3px rgba(0,0,0,.2);
}
.entry-form {
background-color: rgba(0,0,0,0.3);
height: 2em;
border-radius: 2em;
width: 100%;
-webkit-box-shadow: inset -0px -1px 8px -2px rgba(0,0,0,1);
-moz-box-shadow: inset -0px -1px 8px -2px rgba(0,0,0,1);
box-shadow: inset -0px -1px 8px -2px rgba(0,0,0,1);
}
.entry {
background-color: rgba(0,0,0,0);
height: 2em;
width: 80%;
margin-left: 2em;
border: none;
font-size: 1em;
color: #fff;
position: relative;
top: 50%;
transform: translateY(-50%);
}
.entry::-webkit-input-placeholder {
color: #fff;
}
.entry:-moz-placeholder { /* Firefox 18- */
color: #fff;
}
.entry::-moz-placeholder { /* Firefox 19+ */
color: #fff;
}
.entry:-ms-input-placeholder {
color: #fff;
}
.entry, .submit {
outline: none;
}
.submit {
background-color: rgba(0,0,0,0);
border: 1px solid #fff;
border-radius: 1em;
color: #fff;
font-size: 1em;
padding: .1em 1em;
display: block;
margin-right: 25px;
float: right;
position: relative;
top: 50%;
transform: translateY(-50%);
}
.submit:hover {
background-color: #fff;
color: rgba(0,0,0,.5);
-webkit-transition: background-color .25s ease, color .1s ease;
-moz-transition: background-color .25s ease, color .1s ease;
-o-transition: background-color .25s ease, color .1s ease;
transition: background-color .25s ease, color .1s ease;
}
.list {
margin: 2em 20%;
}
.item {
margin: .33em 0;
height: 1.75em;
}
.not-done {
/* background-color: rgba(365,365,365,.8);
*/ border-radius: 2em;
-webkit-box-shadow: 0px 1px 2px -1px rgba(0,0,0,.5);
-moz-box-shadow: 0px 1px 2px -1px rgba(0,0,0,.5);
box-shadow: 0px 1px 2px -1px rgba(0,0,0,.5);
background-image: -webkit-linear-gradient(top, rgba(365,365,365,.8), rgba(235,235,235,.8));
background-image: -moz-linear-gradient(top, rgba(365,365,365,.8), rgba(235,235,235,.8));
background-image: -ms-linear-gradient(top, rgba(365,365,365,.8), rgba(235,235,235,.8));
background-image: -o-linear-gradient(top, rgba(365,365,365,.8), rgba(235,235,235,.8));
background-image: linear-gradient(to bottom, rgba(365,365,365,.8), rgba(235,235,235,.8));
}
.checkbox {
width: .75em;
height: .75em;
margin: 0 .75em;
background-color: rgba(365,365,365,.7);
border: 1px solid rgba(0,0,0,.2);
border-radius: .2em;
}
.checkbox, .item p {
position: relative;
top: 50%;
transform: translateY(-50%);
display: inline-block;
}
.not-done p {
}
.done .checkbox {
background-color: initial;
}
.done a {
color: black;
text-decoration: line-through;
}
.done a:hover {
text-decoration: none;
}
```
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The Fucking Milk</title>
<link rel="stylesheet" href="css/style.css">
<script src="http://code.jquery.com/jquery.min.js"></script>
<script src="js/script.js"></script>
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400|Libre+Baskerville:400,700' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="header">
<div class="container">
<h2>Made by @taykcrane</h2>
</div>
</div>
<div class="main">
<div class="container">
<h1>The Fucking Milk</h1>
<form class="entry-form">
<input type="text" placeholder="Go ahead. Add a new item to your shopping list here." class="entry">
<input type="submit" value="Enter" class="submit">
</form>
<div class="list">
<div class="item not-done">
<div class="checkbox"></div>
<p><a href="#">almond milk</a></p>
</div>
<div class="item not-done">
<div class="checkbox"></div>
<p>bananas</p>
</div>
<div class="item not-done">
<div class="checkbox"></div>
<p>peanut butter</p>
</div>
<div class="item not-done">
<div class="checkbox"></div>
<p>jelly</p>
</div>
<div class="item not-done">
<div class="checkbox"></div>
<p>whole wheat bread</p>
</div>
<div class="item done">
<div class="checkbox"></div>
<p><a href="#">shampoo</a></p>
</div>
<div class="item done">
<div class="checkbox"></div>
<p><a href="#">comb</a></p>
</div>
</div>
</div>
</div>
</body>
</html>
```
|
28,532,672
|
I have N 10-dimensional vectors where each element can have value of 0,1 or 2.
For example, `vector v=(0,1,1,2,0,1,2,0,1,1)` is one of the vectors.
Is there an algorithm (preferably in python) that compresses these vectors into a minimum number of Cartesian products. If not perfect solution, is there a algorithm that at least gives a good compression.
Example: the two "Cartesian vectors"
`([1,2], 0, 1, 0, 0, 0, 1, 1, [0,1], 0])` (gives 4 vectors) and `(0, 1, 0, 2, 0, 0, [0,2], 2, 0, 1)` (gives 2 vectors) gives optimal solution for the N=6 vectors:
```
1,0,1,0,0,0,1,1,0,0
2,0,1,0,0,0,1,1,0,0
1,0,1,0,0,0,1,1,1,0
2,0,1,0,0,0,1,1,1,0
0,1,0,2,0,0,0,2,0,1
0,1,0,2,0,0,2,2,0,1
```
|
2015/02/15
|
[
"https://Stackoverflow.com/questions/28532672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4570066/"
] |
Another alternative way is using [.one()](http://api.jquery.com/one/) (the handler is executed at most once per element per event type), something like this,
```
$(".done p").one('click', function() {
$(this).parent().attr("class", "item not-done");
$(this).parent().hide().prependTo('.list').fadeIn('.5s');
});
```
|
Try
```
$(document).ready(function() {
// Handles new entry submissions
$('.entry-form').submit(function(event) {
var entryValue = $(".entry").val();
// if `entryValue` _not_ have class `not-done` ,
// prepend `done` having `entryValue` to `.list` ,
// add class `not-done`
if (!$(".not-done:contains(" + entryValue + ")").is("*")) {
var elem = $(".done:contains(" + entryValue + ")");
elem.attr("class", "item not-done")
.prependTo('.list').fadeIn('.5s');
} else {
// else detach `done` class having `entryValue` from `DOM`
console.log(entryValue + " already listed");
$(".done:contains(" + entryValue + ")").detach()
}
event.preventDefault();
$('.entry-form')[0].reset();
});
// Handles adding entries back into the list
$(".done p").click(function() {
$(this).parent().attr("class", "item not-done")
.hide().prependTo('.list').fadeIn('.5s');
});
});
```
```js
$(document).ready(function() {
// Handles new entry submissions
$('.entry-form').submit(function(event) {
var entryValue = $(".entry").val();
if (!$(".not-done:contains("+entryValue+")").is("*")) {
var elem = $(".done:contains("+entryValue+")");
elem.attr("class", "item not-done")
.prependTo('.list').fadeIn('.5s');
} else {
console.log(entryValue + " already listed");
$(".done:contains("+entryValue+")").detach()
}
event.preventDefault();
$('.entry-form')[0].reset();
});
// Handles adding entries back into the list
$(".done p").click(function() {
$(this).parent().attr("class", "item not-done")
.hide().prependTo('.list').fadeIn('.5s');
});
});
```
```css
/**
* Eric Meyer's Reset CSS v2.0 (http://meyerweb.com/eric/tools/css/reset/)
* http://cssreset.com
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
font-family: "Source Sans Pro";
font-weight: 300;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
body {
background-color: grey;
background-size: cover;
}
a {
text-decoration: none;
}
.container {
margin: 0 20%;
height: 100%;
}
.header {
height: 2em;
background-color: white;
-webkit-box-shadow: 0px 1px 2px -1px rgba(0,0,0,.5);
-moz-box-shadow: 0px 1px 2px -1px rgba(0,0,0,.5);
box-shadow: 0px 1px 2px -1px rgba(0,0,0,.5);
}
.header h2 {
position: relative;
top: 50%;
transform: translateY(-50%);
}
.main h1 {
text-align: center;
margin: 1em 0;
font-family: "Libre Bakersville";
font-weight: 700;
font-size: 2em;
color: white;
text-shadow: 1px 1px 3px rgba(0,0,0,.2);
}
.entry-form {
background-color: rgba(0,0,0,0.3);
height: 2em;
border-radius: 2em;
width: 100%;
-webkit-box-shadow: inset -0px -1px 8px -2px rgba(0,0,0,1);
-moz-box-shadow: inset -0px -1px 8px -2px rgba(0,0,0,1);
box-shadow: inset -0px -1px 8px -2px rgba(0,0,0,1);
}
.entry {
background-color: rgba(0,0,0,0);
height: 2em;
width: 80%;
margin-left: 2em;
border: none;
font-size: 1em;
color: #fff;
position: relative;
top: 50%;
transform: translateY(-50%);
}
.entry::-webkit-input-placeholder {
color: #fff;
}
.entry:-moz-placeholder { /* Firefox 18- */
color: #fff;
}
.entry::-moz-placeholder { /* Firefox 19+ */
color: #fff;
}
.entry:-ms-input-placeholder {
color: #fff;
}
.entry, .submit {
outline: none;
}
.submit {
background-color: rgba(0,0,0,0);
border: 1px solid #fff;
border-radius: 1em;
color: #fff;
font-size: 1em;
padding: .1em 1em;
display: block;
margin-right: 25px;
float: right;
position: relative;
top: 50%;
transform: translateY(-50%);
}
.submit:hover {
background-color: #fff;
color: rgba(0,0,0,.5);
-webkit-transition: background-color .25s ease, color .1s ease;
-moz-transition: background-color .25s ease, color .1s ease;
-o-transition: background-color .25s ease, color .1s ease;
transition: background-color .25s ease, color .1s ease;
}
.list {
margin: 2em 20%;
}
.item {
margin: .33em 0;
height: 1.75em;
}
.not-done {
/* background-color: rgba(365,365,365,.8);
*/ border-radius: 2em;
-webkit-box-shadow: 0px 1px 2px -1px rgba(0,0,0,.5);
-moz-box-shadow: 0px 1px 2px -1px rgba(0,0,0,.5);
box-shadow: 0px 1px 2px -1px rgba(0,0,0,.5);
background-image: -webkit-linear-gradient(top, rgba(365,365,365,.8), rgba(235,235,235,.8));
background-image: -moz-linear-gradient(top, rgba(365,365,365,.8), rgba(235,235,235,.8));
background-image: -ms-linear-gradient(top, rgba(365,365,365,.8), rgba(235,235,235,.8));
background-image: -o-linear-gradient(top, rgba(365,365,365,.8), rgba(235,235,235,.8));
background-image: linear-gradient(to bottom, rgba(365,365,365,.8), rgba(235,235,235,.8));
}
.checkbox {
width: .75em;
height: .75em;
margin: 0 .75em;
background-color: rgba(365,365,365,.7);
border: 1px solid rgba(0,0,0,.2);
border-radius: .2em;
}
.checkbox, .item p {
position: relative;
top: 50%;
transform: translateY(-50%);
display: inline-block;
}
.not-done p {
}
.done .checkbox {
background-color: initial;
}
.done a {
color: black;
text-decoration: line-through;
}
.done a:hover {
text-decoration: none;
}
```
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The Fucking Milk</title>
<link rel="stylesheet" href="css/style.css">
<script src="http://code.jquery.com/jquery.min.js"></script>
<script src="js/script.js"></script>
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400|Libre+Baskerville:400,700' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="header">
<div class="container">
<h2>Made by @taykcrane</h2>
</div>
</div>
<div class="main">
<div class="container">
<h1>The Fucking Milk</h1>
<form class="entry-form">
<input type="text" placeholder="Go ahead. Add a new item to your shopping list here." class="entry">
<input type="submit" value="Enter" class="submit">
</form>
<div class="list">
<div class="item not-done">
<div class="checkbox"></div>
<p><a href="#">almond milk</a></p>
</div>
<div class="item not-done">
<div class="checkbox"></div>
<p>bananas</p>
</div>
<div class="item not-done">
<div class="checkbox"></div>
<p>peanut butter</p>
</div>
<div class="item not-done">
<div class="checkbox"></div>
<p>jelly</p>
</div>
<div class="item not-done">
<div class="checkbox"></div>
<p>whole wheat bread</p>
</div>
<div class="item done">
<div class="checkbox"></div>
<p><a href="#">shampoo</a></p>
</div>
<div class="item done">
<div class="checkbox"></div>
<p><a href="#">comb</a></p>
</div>
</div>
</div>
</div>
</body>
</html>
```
|
39,191,252
|
I'm running Spark 1.5.1 in standalone (client) mode using Pyspark. I'm trying to start a job that seems to be memory heavy (in python that is, so that should not be part of the executor-memory setting). I'm testing on a machine with 96 cores and 128 GB of RAM.
I have a master and worker running, started using the start-all.sh script in /sbin.
These are the config files I use in /conf.
spark-defaults.conf:
```
spark.eventLog.enabled true
spark.eventLog.dir /home/kv/Spark/spark-1.5.1-bin-hadoop2.6/logs
spark.serializer org.apache.spark.serializer.KryoSerializer
spark.dynamicAllocation.enabled false
spark.deploy.
defaultCores 40
```
spark-env.sh:
```
PARK_MASTER_IP='5.153.14.30' # Will become deprecated
SPARK_MASTER_HOST='5.153.14.30'
SPARK_MASTER_PORT=7079
SPARK_MASTER_WEBUI_PORT=8080
SPARK_WORKER_WEBUI_PORT=8081
```
I'm starting my script using the following command:
```
export SPARK_MASTER=spark://5.153.14.30:7079 #"local[*]"
spark-submit \
--master ${SPARK_MASTER} \
--num-executors 1 \
--driver-memory 20g \
--executor-memory 30g \
--executor-cores 40 \
--py-files code.zip \
<script>
```
Now, I'm noticing behaviour that I don't understand:
* When I start my application with the settings above, I expect there to be 1 executor. However, 2 executors are started, each having 30g of memory and 40 cores. Why does spark do this? I'm trying to limit the number of cores to have more memory per core, how can I enforce this? Now my application gets killed because it uses too much memory.
* When I increase `executor-cores` to over 40, my job does not get started because of not enough resources. I expect that this is because of the `defaultCores 40` setting in my spark-defaults. But is't this just as a backup for when my application does not provide a maximum number of cores? I should be able to overwrite that right?
Extract from the error messages I get:
```
Lost task 1532.0 in stage 2.0 (TID 5252, 5.153.14.30): org.apache.spark.SparkException: Python worker exited unexpectedly (crashed)
at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:203)
at org.apache.spark.api.python.PythonRunner$$anon$1.<init>(PythonRDD.scala:207)
at org.apache.spark.api.python.PythonRunner.compute(PythonRDD.scala:125)
at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:70)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:297)
at org.apache.spark.CacheManager.getOrCompute(CacheManager.scala:69)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:262)
at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:70)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:297)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:264)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
at org.apache.spark.scheduler.Task.run(Task.scala:88)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:214)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.EOFException
at java.io.DataInputStream.readInt(DataInputStream.java:392)
at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:139)
... 15 more
[...]
py4j.protocol.Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.collectAndServe.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 111 in stage 2.0 failed 4 times, most recent failure: Lost task 111.3 in stage 2.0 (TID 5673, 5.153.14.30): org.apache.spark.SparkException: Python worker exited unexpectedly (crashed)
```
|
2016/08/28
|
[
"https://Stackoverflow.com/questions/39191252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/696992/"
] |
Check or set the value for spark.executor.instances. The default is 2, which may explain why you get 2 executors.
Since your server has 96 cores, and you set defaultcores to 40, you only have room for 2 executors since 2\*40 = 80. The remaining 16 cores are insufficient for another executor and the driver also requires CPU cores.
|
>
> I expect there to be 1 executor. However, 2 executors are started
>
>
>
I think the one executor you see, it's actually the driver.
So one master, one slave (2 nodes in totals).
You can add to your script these configuration flags:
```
--conf spark.executor.cores=8 <-- will set it 8, you probably want less
--conf spark.driver.cores=8 <-- same, but for driver only
```
---
>
> my job does not get started because of not enough resources.
>
>
>
I believe the container gets killed. You see, you ask for too many resources, so every container/task/core tries to take as much memory as possible, and your system can't simple give more.
The container might exceed its memory limits (you should be able to see more in the logs to be certain though).
|
27,798,829
|
I have installed PySide in my Ubuntu 12.04. When I try to use import PySide in the python console I am getting the following error.
```
import PySide
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named PySide
```
My Python Path is :
```
print sys.path ['', '/usr/lib/python2.7',
'/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages/PIL',
'/usr/lib/python2.7/dist-packages/gst-0.10',
'/usr/lib/python2.7/dist-packages/gtk-2.0',
'/usr/lib/pymodules/python2.7',
'/usr/lib/python2.7/dist-packages/ubuntu-sso-client',
'/usr/lib/python2.7/dist-packages/ubuntuone-client',
'/usr/lib/python2.7/dist-packages/ubuntuone-control-panel',
'/usr/lib/python2.7/dist-packages/ubuntuone-couch',
'/usr/lib/python2.7/dist-packages/ubuntuone-installer',
'/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol']
```
how to fix this problem ?
|
2015/01/06
|
[
"https://Stackoverflow.com/questions/27798829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2871542/"
] |
To use python 3, just follow the instructions here:
<https://wiki.qt.io/PySide_Binaries_Linux>
which in ubuntu 12.04 means just typing one line in the console:
```
sudo apt-get install python3-pyside
```
|
The latest build and install instructions for PySide are here:
<http://pyside.readthedocs.org/en/latest/building/linux.html>
|
27,798,829
|
I have installed PySide in my Ubuntu 12.04. When I try to use import PySide in the python console I am getting the following error.
```
import PySide
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named PySide
```
My Python Path is :
```
print sys.path ['', '/usr/lib/python2.7',
'/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages/PIL',
'/usr/lib/python2.7/dist-packages/gst-0.10',
'/usr/lib/python2.7/dist-packages/gtk-2.0',
'/usr/lib/pymodules/python2.7',
'/usr/lib/python2.7/dist-packages/ubuntu-sso-client',
'/usr/lib/python2.7/dist-packages/ubuntuone-client',
'/usr/lib/python2.7/dist-packages/ubuntuone-control-panel',
'/usr/lib/python2.7/dist-packages/ubuntuone-couch',
'/usr/lib/python2.7/dist-packages/ubuntuone-installer',
'/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol']
```
how to fix this problem ?
|
2015/01/06
|
[
"https://Stackoverflow.com/questions/27798829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2871542/"
] |
To use python 3, just follow the instructions here:
<https://wiki.qt.io/PySide_Binaries_Linux>
which in ubuntu 12.04 means just typing one line in the console:
```
sudo apt-get install python3-pyside
```
|
Now, the `ModuleNotFoundError: No module named 'PySide'` - issue can be solved for `python` versions > 3.4x with `pip install pyside2` like so:
```
andylu@andylu-Lubuntu-PC:~$ pip install pyside2
Collecting pyside2
Downloading PySide2-5.15.2-5.15.2-cp35.cp36.cp37.cp38.cp39-abi3-manylinux1_x86_64.whl (164.3 MB)
|████████████████████████████████| 164.3 MB 2.4 kB/s
Collecting shiboken2==5.15.2
Downloading shiboken2-5.15.2-5.15.2-cp35.cp36.cp37.cp38.cp39-abi3-manylinux1_x86_64.whl (956 kB)
|████████████████████████████████| 956 kB 2.7 MB/s
Installing collected packages: shiboken2, pyside2
Successfully installed pyside2-5.15.2 shiboken2-5.15.2
```
To me the error occurred when trying to start the `jupyter qtconsole` from terminal:
```
andylu@andylu-Lubuntu-PC:~$ jupyter qtconsole
Traceback (most recent call last):
File "/home/andylu/.pyenv/versions/3.9.0/lib/python3.9/site-packages/qtpy/__init__.py", line 204, in <module>
from PySide import __version__ as PYSIDE_VERSION # analysis:ignore
ModuleNotFoundError: No module named 'PySide'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/andylu/.pyenv/versions/3.9.0/bin/jupyter-qtconsole", line 5, in <module>
from qtconsole.qtconsoleapp import main
File "/home/andylu/.pyenv/versions/3.9.0/lib/python3.9/site-packages/qtconsole/qtconsoleapp.py", line 60, in <module>
from qtpy import QtCore, QtGui, QtWidgets
File "/home/andylu/.pyenv/versions/3.9.0/lib/python3.9/site-packages/qtpy/__init__.py", line 210, in <module>
raise PythonQtError('No Qt bindings could be found')
qtpy.PythonQtError: No Qt bindings could be found
```
Then, I initially tried to install the ancient `pyside` in my current `Python 3.9.0` - environment, which led to the following error:
```
andylu@andylu-Lubuntu-PC:~$ pip install pyside
Collecting pyside
Downloading PySide-1.2.4.tar.gz (9.3 MB)
|████████████████████████████████| 9.3 MB 389 kB/s
ERROR: Command errored out with exit status 1:
command: /home/andylu/.pyenv/versions/3.9.0/bin/python3.9 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-kbfhpmbj/pyside_d579850ca35442f99958b51deaf6e16b/setup.py'"'"'; __file__='"'"'/tmp/pip-install-kbfhpmbj/pyside_d579850ca35442f99958b51deaf6e16b/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-07ab3csm
cwd: /tmp/pip-install-kbfhpmbj/pyside_d579850ca35442f99958b51deaf6e16b/
Complete output (1 lines):
only these python versions are supported: [(2, 6), (2, 7), (3, 2), (3, 3), (3, 4)]
----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
```
The solution to it was, as mentioned above in the beginning, installing `pyside2` instead of `pyside`:
```
pip install pyside2
```
|
70,922,066
|
I am building a docker image to run a flask app, which is named dp-offsets for context. This flask app uses matplotlib. I have been unable to fully install matlplotlib despite including all of the necessary dependencies (i think). The code seems to be erroring on timestamp **791.9**s due to bdist\_wheel. I'm not sure why bdist\_wheel is erroring, because I install wheel before I install matplotlib. Seen below is the terminal error, my requirements.txt file, and my Dockerfile.
Any help would be appreciated!
**Docker File**
```
FROM python:3.7.4-alpine
#Dependancies for matplotlib, pandas, and numpy
RUN apk add --no-cache --update \
python3 python3-dev gcc \
gfortran musl-dev g++ \
libffi-dev openssl-dev \
libxml2 libxml2-dev \
libxslt libxslt-dev \
jpeg-dev libjpeg make \
libjpeg-turbo-dev zlib-dev
RUN pip install --upgrade cython
RUN pip install --upgrade pip
RUN pip install --upgrade setuptools
WORKDIR /dp-offsets
ADD . /dp-offsets
RUN pip install -r requirements.txt
CMD ["python", "app_main.py"]
```
**Requirements.txt. File**
```
wheel==0.37.0
flask==2.0.1
flask_bootstrap
form
numpy==1.21.2
matplotlib==3.4.3
pandas==1.3.2
flask_wtf==0.15.1
wtforms==2.3.3
```
**Error Received**
```
> [8/8] RUN pip install -r requirements.txt:
#13 1.125 Collecting wheel==0.37.0
#13 1.713 Downloading wheel-0.37.0-py2.py3-none-any.whl (35 kB)
#13 1.874 Collecting flask==2.0.1
#13 1.975 Downloading Flask-2.0.1-py3-none-any.whl (94 kB)
#13 2.171 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 94.8/94.8 KB 444.0 kB/s eta 0:00:00
#13 2.348 Collecting flask_bootstrap
#13 2.458 Downloading Flask-Bootstrap-3.3.7.1.tar.gz (456 kB)
#13 3.130 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 456.4/456.4 KB 684.5 kB/s eta 0:00:00
#13 3.164 Preparing metadata (setup.py): started
#13 3.417 Preparing metadata (setup.py): finished with status 'done'
#13 3.585 Collecting form
#13 3.684 Downloading form-0.0.1.tar.gz (1.4 kB)
#13 3.699 Preparing metadata (setup.py): started
#13 3.929 Preparing metadata (setup.py): finished with status 'done'
#13 4.556 Collecting numpy==1.21.2
#13 4.641 Downloading numpy-1.21.2.zip (10.3 MB)
#13 15.18 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 10.3/10.3 MB 974.4 kB/s eta 0:00:00
#13 15.79 Installing build dependencies: started
#13 22.28 Installing build dependencies: finished with status 'done'
#13 22.28 Getting requirements to build wheel: started
#13 22.69 Getting requirements to build wheel: finished with status 'done'
#13 22.69 Preparing metadata (pyproject.toml): started
#13 23.05 Preparing metadata (pyproject.toml): finished with status 'done'
#13 23.34 Collecting matplotlib==3.4.3
#13 23.43 Downloading matplotlib-3.4.3.tar.gz (37.9 MB)
#13 53.17 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 37.9/37.9 MB 1.3 MB/s eta 0:00:00
#13 55.07 Preparing metadata (setup.py): started
#13 298.3 Preparing metadata (setup.py): still running...
#13 298.8 Preparing metadata (setup.py): finished with status 'done'
#13 299.1 Collecting pandas==1.3.2
#13 299.2 Downloading pandas-1.3.2.tar.gz (4.7 MB)
#13 302.7 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 4.7/4.7 MB 1.4 MB/s eta 0:00:00
#13 303.5 Installing build dependencies: started
#13 383.9 Installing build dependencies: still running...
#13 446.6 Installing build dependencies: still running...
#13 461.3 Installing build dependencies: finished with status 'done'
#13 461.4 Getting requirements to build wheel: started
#13 524.1 Getting requirements to build wheel: still running...
#13 524.5 Getting requirements to build wheel: finished with status 'done'
#13 524.5 Preparing metadata (pyproject.toml): started
#13 525.2 Preparing metadata (pyproject.toml): finished with status 'done'
#13 525.3 Collecting flask_wtf==0.15.1
#13 525.4 Downloading Flask_WTF-0.15.1-py2.py3-none-any.whl (13 kB)
#13 525.5 Collecting wtforms==2.3.3
#13 525.6 Downloading WTForms-2.3.3-py2.py3-none-any.whl (169 kB)
#13 525.7 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 169.1/169.1 KB 2.0 MB/s eta 0:00:00
#13 525.9 Collecting Werkzeug>=2.0
#13 526.1 Downloading Werkzeug-2.0.2-py3-none-any.whl (288 kB)
#13 526.3 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 288.9/288.9 KB 1.1 MB/s eta 0:00:00
#13 526.5 Collecting Jinja2>=3.0
#13 526.6 Downloading Jinja2-3.0.3-py3-none-any.whl (133 kB)
#13 526.7 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 133.6/133.6 KB 1.5 MB/s eta 0:00:00
#13 526.9 Collecting itsdangerous>=2.0
#13 527.0 Downloading itsdangerous-2.0.1-py3-none-any.whl (18 kB)
#13 527.2 Collecting click>=7.1.2
#13 527.3 Downloading click-8.0.3-py3-none-any.whl (97 kB)
#13 527.3 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 97.5/97.5 KB 1.8 MB/s eta 0:00:00
#13 527.5 Collecting cycler>=0.10
#13 527.6 Downloading cycler-0.11.0-py3-none-any.whl (6.4 kB)
#13 527.7 Collecting kiwisolver>=1.0.1
#13 527.9 Downloading kiwisolver-1.3.2.tar.gz (54 kB)
#13 527.9 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 54.6/54.6 KB 3.0 MB/s eta 0:00:00
#13 527.9 Preparing metadata (setup.py): started
#13 530.1 Preparing metadata (setup.py): finished with status 'done'
#13 530.7 Collecting pillow>=6.2.0
#13 530.8 Downloading Pillow-9.0.0.tar.gz (49.5 MB)
#13 569.3 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 49.5/49.5 MB 1.2 MB/s eta 0:00:00
#13 570.4 Preparing metadata (setup.py): started
#13 570.7 Preparing metadata (setup.py): finished with status 'done'
#13 570.8 Collecting pyparsing>=2.2.1
#13 571.0 Downloading pyparsing-3.0.7-py3-none-any.whl (98 kB)
#13 571.1 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 98.0/98.0 KB 825.7 kB/s eta 0:00:00
#13 571.2 Collecting python-dateutil>=2.7
#13 571.3 Downloading python_dateutil-2.8.2-py2.py3-none-any.whl (247 kB)
#13 571.6 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 247.7/247.7 KB 887.6 kB/s eta 0:00:00
#13 571.8 Collecting pytz>=2017.3
#13 572.0 Downloading pytz-2021.3-py2.py3-none-any.whl (503 kB)
#13 572.5 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 503.5/503.5 KB 944.0 kB/s eta 0:00:00
#13 572.7 Collecting MarkupSafe
#13 572.8 Downloading MarkupSafe-2.0.1-cp37-cp37m-musllinux_1_1_x86_64.whl (30 kB)
#13 573.1 Collecting dominate
#13 573.2 Downloading dominate-2.6.0-py2.py3-none-any.whl (29 kB)
#13 573.5 Collecting visitor
#13 573.6 Downloading visitor-0.1.3.tar.gz (3.3 kB)
#13 573.6 Preparing metadata (setup.py): started
#13 573.8 Preparing metadata (setup.py): finished with status 'done'
#13 574.0 Collecting importlib-metadata
#13 574.1 Downloading importlib_metadata-4.10.1-py3-none-any.whl (17 kB)
#13 574.2 Collecting six>=1.5
#13 574.3 Downloading six-1.16.0-py2.py3-none-any.whl (11 kB)
#13 574.5 Collecting typing-extensions>=3.6.4
#13 574.8 Downloading typing_extensions-4.0.1-py3-none-any.whl (22 kB)
#13 575.1 Collecting zipp>=0.5
#13 575.6 Downloading zipp-3.7.0-py3-none-any.whl (5.3 kB)
#13 575.6 Building wheels for collected packages: numpy, matplotlib, pandas, flask_bootstrap, form, kiwisolver, pillow, visitor
#13 575.6 Building wheel for numpy (pyproject.toml): started
#13 657.8 Building wheel for numpy (pyproject.toml): still running...
#13 720.6 Building wheel for numpy (pyproject.toml): still running...
#13 777.1 Building wheel for numpy (pyproject.toml): finished with status 'done'
#13 777.1 Created wheel for numpy: filename=numpy-1.21.2-cp37-cp37m-linux_x86_64.whl size=21275305 sha256=82ac227d9585fb707983648e7ab6b8ff47b953a1d5d687409339ad505a8467b4
#13 777.1 Stored in directory: /root/.cache/pip/wheels/6b/8c/55/e7f441ea696acba3eba6931857214e3b33dcfe1e971b663032
#13 777.1 Building wheel for matplotlib (setup.py): started
#13 791.9 Building wheel for matplotlib (setup.py): finished with status 'error'
#13 791.9 error: subprocess-exited-with-error
#13 791.9
#13 791.9 × python setup.py bdist_wheel did not run successfully.
#13 791.9 │ exit code: 1
#13 791.9 ╰─> [861 lines of output]
#13 791.9
#13 791.9 Edit setup.cfg to change the build options; suppress output with --quiet.
#13 791.9
#13 791.9 BUILDING MATPLOTLIB
#13 791.9 matplotlib: yes [3.4.3]
#13 791.9 python: yes [3.7.4 (default, Aug 21 2019, 00:19:59) [GCC 8.3.0]]
#13 791.9 platform: yes [linux]
#13 791.9 tests: no [skipping due to configuration]
#13 791.9 macosx: no [Mac OS-X only]
```
**The Error continues for a bit longer. Below is the final output**
```
#13 1427.6 UPDATING build/lib.linux-x86_64-3.7/matplotlib/_version.py
#13 1427.6 set build/lib.linux-x86_64-3.7/matplotlib/_version.py to '3.4.3'
#13 1427.6 running build_ext
#13 1427.6 gcc -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -DTHREAD_STACK_SIZE=0x100000 -fPIC -I/usr/local/include/python3.7m -c /tmp/tmpzzp8tz7k.cpp -o tmp/t
mpzzp8tz7k.o -fvisibility=hidden
#13 1427.6 gcc -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -DTHREAD_STACK_SIZE=0x100000 -fPIC -I/usr/local/include/python3.7m -c /tmp/tmpqr5gbp_k.cpp -o tmp/t
mpqr5gbp_k.o -fvisibility-inlines-hidden
#13 1427.6 gcc -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -DTHREAD_STACK_SIZE=0x100000 -fPIC -I/usr/local/include/python3.7m -c /tmp/tmptx14kry1.cpp -o tmp/t
mptx14kry1.o -flto
#13 1427.6 error: Failed to download any of the following: ['http://www.qhull.org/download/qhull-2020-src-8.0.2.tgz']. Please download one of these urls and extract it into 'bui
ld/' at the top-level of the source repository.
#13 1427.6 [end of output]
#13 1427.6
#13 1427.6 note: This error originates from a subprocess, and is likely not a problem with pip.
#13 1427.7 error: legacy-install-failure
#13 1427.7
#13 1427.7 × Encountered error while trying to install package.
#13 1427.7 ╰─> matplotlib
#13 1427.7
#13 1427.7 note: This is an issue with the package mentioned above, not pip.
#13 1427.7 hint: See above for output from the failure.
------
executor failed running [/bin/sh -c pip install -r requirements.txt]: exit code: 1
```
|
2022/01/31
|
[
"https://Stackoverflow.com/questions/70922066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18075955/"
] |
You have to rearrange the whole thing in your required format. To do that you have to access the data to it's specific position. You did something awkward there in your code at the second array base. you should specify your section somewhere else,maybe the next line. To access it you have to write:
```
obj.name //For the school name
```
|
Objects are defined like this: {key1: value1, key2: value2}
Keys are the identifiers of your values. When you are assigning section: 'A', section: 'B', section: 'C', you are using the same key, so the previous values are overwritten and only the last is stored. That's why it logs 'C'.
You can try changing the keys or maybe write it like this:
section:['A', 'B', 'C']
|
70,186,395
|
I have uploaded my databricks notebooks to a repo and replace %run sentences with import using the new databrick public available features (Repo integration and python import): <https://databricks.com/blog/2021/10/07/databricks-repos-is-now-generally-available.html>
But its seems its not working
I already activate the repo integration option in the Admin panel but i Get this error
>
> ModuleNotFoundError: No module named 'petitions'
>
>
>
For simplicity I moved all python files to the same directory. I get the error in the procesado notebook
[
|
2021/12/01
|
[
"https://Stackoverflow.com/questions/70186395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1075163/"
] |
You can use a hierarchical query and `CONNECT_BY_ROOT`.
Either starting at the root of the hierarchy and working down:
```sql
SELECT id,
CONNECT_BY_ROOT(id) AS root_id
FROM entry
WHERE id IN (6, 3)
START WITH parent_id IS NULL
CONNECT BY PRIOR id = parent_id;
```
Or, from the entry back up to the root:
```sql
SELECT CONNECT_BY_ROOT(id) AS id,
id AS root_id
FROM entry
WHERE parent_id IS NULL
START WITH id IN (6, 3)
CONNECT BY PRIOR parent_id = id;
```
Which, for the sample data:
```sql
CREATE TABLE entry( id, parent_id ) AS
SELECT 1, NULL FROM DUAL UNION ALL
SELECT 2, 1 FROM DUAL UNION ALL
SELECT 3, 2 FROM DUAL UNION ALL
SELECT 4, NULL FROM DUAL UNION ALL
SELECT 5, 4 FROM DUAL UNION ALL
SELECT 6, 5 FROM DUAL UNION ALL
SELECT 7, 6 FROM DUAL
```
Both output:
>
>
>
>
> | ID | ROOT\_ID |
> | --- | --- |
> | 3 | 1 |
> | 6 | 4 |
>
>
>
*db<>fiddle [here](https://dbfiddle.uk/?rdbms=oracle_18&fiddle=4a4ee39e30707104bb256336bd77f50f)*
|
You can use recursive CTE to walk the graph and find the initial parent. For example:
```
with
n (starting_id, current_id, parent_id, v) as (
select id, id, parent_id, 0 from entry where id in (6, 3)
union all
select n.starting_id, e.id, e.parent_id, n.v - 1
from n
join entry e on e.id = n.parent_id
)
select starting_id, current_id as initial_id
from (
select n.*, row_number() over(partition by starting_id order by v) as rn
from n
) x
where rn = 1
```
Result:
```
STARTING_ID INITIAL_ID
------------ ----------
3 1
6 4
```
See running example at [db<>fiddle](https://dbfiddle.uk/?rdbms=oracle_18&fiddle=81d2ae02d0006ecdbfb87de91b36d857).
|
18,541,648
|
I have a table in a database which contains query statements in the columns. I need to update this. Is there any way I can update this It seems to be giving me an error:
```
UPDATE Items
SET Query = 'SELECT isnull((sum(OrigDocAmt) ),0) amount from AP where Acct in (1234) and Status='O' and Doc in ('CK') {SLLocCode}'
WHERE ID='111'
```
It gives me an error because it considers 'O' as a separate string. Is there a way that I can do this like in python "What's up".
Not sure why it was setup this way but it was done so by my predecessor. Please help.
|
2013/08/30
|
[
"https://Stackoverflow.com/questions/18541648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2684009/"
] |
You need to use 2 single quotes ('') around each literal value
```
'SELECT isnull((sum(OrigDocAmt) ),0) amount from AP where Acct in (1234) and Status=''O'' and Doc in (''CK'') {SLLocCode}'
```
|
You need to escape the single quotes in the query string. In SQL Server, you just double the single quotes:
```
UPDATE Items
SET Query = 'SELECT isnull((sum(OrigDocAmt) ),0) amount from AP where Acct in (1234) and Status=''O'' and Doc in (''CK'') {SLLocCode}'
WHERE ID = '111';
```
|
18,541,648
|
I have a table in a database which contains query statements in the columns. I need to update this. Is there any way I can update this It seems to be giving me an error:
```
UPDATE Items
SET Query = 'SELECT isnull((sum(OrigDocAmt) ),0) amount from AP where Acct in (1234) and Status='O' and Doc in ('CK') {SLLocCode}'
WHERE ID='111'
```
It gives me an error because it considers 'O' as a separate string. Is there a way that I can do this like in python "What's up".
Not sure why it was setup this way but it was done so by my predecessor. Please help.
|
2013/08/30
|
[
"https://Stackoverflow.com/questions/18541648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2684009/"
] |
You need to use 2 single quotes ('') around each literal value
```
'SELECT isnull((sum(OrigDocAmt) ),0) amount from AP where Acct in (1234) and Status=''O'' and Doc in (''CK'') {SLLocCode}'
```
|
you would need to escape `'`(single quotes) in the query. This can be done by simplly doubling it.
```
UPDATE Items
SET Query = 'SELECT isnull((sum(OrigDocAmt) ),0) amount
from AP where Acct in (1234) and Status=''O'' and Doc in (''CK'') {SLLocCode}''
WHERE ID=''111';
```
|
49,781,303
|
I'm trying to write in a microsoft azure jupyter python notebook and I am receiving an error when I try to import the Tweepy module.
Please take a look at the simple code below and let me know your thoughts. Thank you. I'm working on a chromebook if that helps, but I'm not sure it's relevant.
```
import tweepy as tw
tw.__version__
```
Here's what comes up:
```
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-1-453b41c5a7f9> in <module>()
----> 1 import tweepy as tw
2 tw.__version__
ModuleNotFoundError: No module named 'tweepy'
```
|
2018/04/11
|
[
"https://Stackoverflow.com/questions/49781303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9631959/"
] |
From the [Azure Notebooks docs](https://notebooks.azure.com/help/jupyter-notebooks/package-installation/python):
>
> The simplest way to install packages is to do it from within a Jupyter Python notebook. Inside of the notebook your path will be setup to have both pip and conda on it pointing to the proper version of Python. So inside of a notebook you can simply do:
>
>
> `!pip install <pkg name>`
>
>
> or
>
>
> `!conda install <pkg name> -y`
>
>
>
So just first execute a cell that contains:
```
!pip install tweepy
```
and you should be good to go.
|
I had the same error when I was trying to use tweepy. You can try using these commands instead:
`from tweepy import OAuthHandler from tweepy import API from tweepy import Cursor`
|
46,509,906
|
This code is supposed to find the number which is biggest and then it should print out how many is there, but for some reason this commented if statement doesn't work.
```
#!/bin/python3
import sys
def birthdayCakeCandles(n, ar):
j=1
b=0
f=0
maxn=0
for f in range(0,n-1,1):
b=ar[f]
# if maxn==b:
j=j+1
elif b>maxn:
maxn=b
print(j)
n = 4
ar = 3, 1, 2, 3
print(birthdayCakeCandles(n, ar))
```
and when i run this code the output is:
```
1
1
1
None
```
so, final answer is supposed to be 2 instead of None.
|
2017/10/01
|
[
"https://Stackoverflow.com/questions/46509906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6659439/"
] |
I found the **almost** perfect working answer in [Levi Fuller's blog](https://medium.com/@levifuller/how-to-deploy-an-angular-cli-application-built-on-asp-net-1fa03c0ca365).
You can get it working with a minor change: unlike what Levi states, you really need **only a single** npm task
1. set up the **npm task**
* by clicking the three dots button -> set the **Working folder with package.json** to your folder that contains the package.json file.
2. set up the **Azure App Service Deploy**
* by clicking the three dots button -> set the **Package or folder** to your folder that contains the .csproj file.
[](https://i.stack.imgur.com/ButsI.png)
|
There isn’t the build template that you use directly, the template is convenient to use, you need to modify it per to detail requirement.
Refer to these steps:
1. Go to build page of team project (e.g. `https://XXX.visualstudio.com/[teamproject]/_build`)
2. Click +New button to create a build definition with ASP.NET Core template
[](https://i.stack.imgur.com/aLvJp.jpg)
[](https://i.stack.imgur.com/aKifI.jpg)
3. Add npm install task before .NET Core Restore task (Command: `install`; Working folder with package.json:[package.json folder path])
[](https://i.stack.imgur.com/oPLtx.jpg)
4. (optional) Delete/disable .NET Core Test task if you don’t need
5. Add Azure App Service Deploy task at the end (Package or folder: `$(build.artifactstagingdirectory)/**/*.zip`; Check `Publish using Web Deploy` option)
[](https://i.stack.imgur.com/QAX94.jpg)
Note: you can move step 4 to release and link this build to release (change package or folder to `$(System.DefaultWorkingDirectory)/**/*.zip`).
|
31,234,170
|
So I am a bit new to Java and Eclipse. I am more used to python. Using IDLE in python I am able to run my program from it's file and and then continue to use the variables. For example, if I have all the code written out defining a function, in idle I can just write it there.
```
x = foo()
print x
```
However, in Java it seems like I need to put that in the main method.
```
public static void main(String[] args)
```
This is fine if I already know everything I want to do with a function, but what if I am running a code that took a day to run, and forgot to write the out put to a file. In python, I can just wait for it to finish running and then write it to a file in IDLE. In Java I need to tell it to write it to a file in the main method and then re run it.
Is it possible to set up Eclipse to work like IDLE where you don't need rerun a program if you want to do new things with the variables already calculated?
I have never used NetBeans, but would this type of thing be easier to do in NetBeans?
|
2015/07/05
|
[
"https://Stackoverflow.com/questions/31234170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4967646/"
] |
Java is a compiled language, python is a scripting language. You could use scala, or jython (or another scripting language) to get the behavior you want. It's also possible to use a [*Scrapbook page*](http://help.eclipse.org/luna/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftask-create_scrapbook_page.htm) in eclipse, but that isn't a true [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) (which is what you same to be asking for).
|
Your environment is one that sounds like its a python based environment. in this case you are storing the variables into your IDE's runtime variable pool. thats why you can later go and act on a variable you set up. in eclipse when you run your program you are launching a new instance of java that is disconnected (from variables in the memory heap point of view) from the instance of java that is running eclipse. once that copy of java that is running your program exits all its memory (including that holding variables) is returned to the system you are running on.
|
399,991
|
When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file.
So I have this .py file that reads like:
```
starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
```
Then I execute the file and get the data. Since the program is all on my machine and no one else has access to it, it is secure in a trivial way.
I can also write a similar file very easily:
```
def writeoptions(directory):
options=""
options+="starting_length=%s%s"%(starting_length,os.linesep)
options+="starting_cell_size=%s%s"%(starting_cell_size,os.linesep)
options+="LengthofExperiments=%s%s"%(LengthofExperiments,os.linesep)
...
open("%s%soptions.py"%(directory,os.sep),'w').write(options)
```
I want to pass a function as one of the parameters:
```
starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
def pippo(a,b):
return a+b
functionoperator=pippo
```
And of course in the real experiment the function pippo will be much more complex. And different from experiment to experiment.
But what I am unable to do is to write the function automatically. In short I don't know how to generalise the writeoptions function to keep on writing the options, if one of the options is a function. I could of course copy the original file, but this is inelegant, inefficient (because it contains a lot of extra options that are not being used), and generally does not solve the question.
How do you get python to write down the code of a function, as it writes down the value of a variable?
|
2008/12/30
|
[
"https://Stackoverflow.com/questions/399991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46634/"
] |
```
vinko@mithril$ more a.py
def foo(a):
print a
vinko@mithril$ more b.py
import a
import inspect
a.foo(89)
print inspect.getsource(a.foo)
vinko@mithril$ python b.py
89
def foo(a):
print a
```
|
Are you asking about this?
```
def writeoptions(directory):
options=""
options+="starting_length=%s%s"%(starting_length,os.linesep)
options+="starting_cell_size=%s%s"%(starting_cell_size,os.linesep)
options+="LengthofExperiments=%s%s"%(LengthofExperiments,os.linesep)
options+="def pippo(a,b):%s" % ( os.linesep, )
options+=" '''Some version of pippo'''%s" % ( os.linesep, )
options+=" return 2*a+b%s" % ( os.linesep, )
open("%s%soptions.py"%(directory,os.sep),'w').write(options)
```
Or something else?
|
399,991
|
When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file.
So I have this .py file that reads like:
```
starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
```
Then I execute the file and get the data. Since the program is all on my machine and no one else has access to it, it is secure in a trivial way.
I can also write a similar file very easily:
```
def writeoptions(directory):
options=""
options+="starting_length=%s%s"%(starting_length,os.linesep)
options+="starting_cell_size=%s%s"%(starting_cell_size,os.linesep)
options+="LengthofExperiments=%s%s"%(LengthofExperiments,os.linesep)
...
open("%s%soptions.py"%(directory,os.sep),'w').write(options)
```
I want to pass a function as one of the parameters:
```
starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
def pippo(a,b):
return a+b
functionoperator=pippo
```
And of course in the real experiment the function pippo will be much more complex. And different from experiment to experiment.
But what I am unable to do is to write the function automatically. In short I don't know how to generalise the writeoptions function to keep on writing the options, if one of the options is a function. I could of course copy the original file, but this is inelegant, inefficient (because it contains a lot of extra options that are not being used), and generally does not solve the question.
How do you get python to write down the code of a function, as it writes down the value of a variable?
|
2008/12/30
|
[
"https://Stackoverflow.com/questions/399991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46634/"
] |
```
vinko@mithril$ more a.py
def foo(a):
print a
vinko@mithril$ more b.py
import a
import inspect
a.foo(89)
print inspect.getsource(a.foo)
vinko@mithril$ python b.py
89
def foo(a):
print a
```
|
While it is possible to do what you ask (as Vinko has shown), I'd say it is cleaner to *share code*. Put `pippo` and his buddies in a submodule that both programs can access.
|
399,991
|
When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file.
So I have this .py file that reads like:
```
starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
```
Then I execute the file and get the data. Since the program is all on my machine and no one else has access to it, it is secure in a trivial way.
I can also write a similar file very easily:
```
def writeoptions(directory):
options=""
options+="starting_length=%s%s"%(starting_length,os.linesep)
options+="starting_cell_size=%s%s"%(starting_cell_size,os.linesep)
options+="LengthofExperiments=%s%s"%(LengthofExperiments,os.linesep)
...
open("%s%soptions.py"%(directory,os.sep),'w').write(options)
```
I want to pass a function as one of the parameters:
```
starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
def pippo(a,b):
return a+b
functionoperator=pippo
```
And of course in the real experiment the function pippo will be much more complex. And different from experiment to experiment.
But what I am unable to do is to write the function automatically. In short I don't know how to generalise the writeoptions function to keep on writing the options, if one of the options is a function. I could of course copy the original file, but this is inelegant, inefficient (because it contains a lot of extra options that are not being used), and generally does not solve the question.
How do you get python to write down the code of a function, as it writes down the value of a variable?
|
2008/12/30
|
[
"https://Stackoverflow.com/questions/399991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46634/"
] |
```
vinko@mithril$ more a.py
def foo(a):
print a
vinko@mithril$ more b.py
import a
import inspect
a.foo(89)
print inspect.getsource(a.foo)
vinko@mithril$ python b.py
89
def foo(a):
print a
```
|
Instead of diving into the subject of [disassemblers](http://docs.python.org/library/dis.html) and bytecodes (e.g [inspect](http://docs.python.org/library/inspect.html)), why don't you just save the generated Python source in a module (*file.py*), and later, import it?
I would suggest looking into a more standard way of handling what you call *options*. For example, you can use the [JSON](http://docs.python.org/library/json.html) module and save or restore your data. Or look into the [marshal](http://docs.python.org/library/marshal.html#module-marshal) and [pickle](http://docs.python.org/library/pickle.html#module-pickle) modules.
|
399,991
|
When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file.
So I have this .py file that reads like:
```
starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
```
Then I execute the file and get the data. Since the program is all on my machine and no one else has access to it, it is secure in a trivial way.
I can also write a similar file very easily:
```
def writeoptions(directory):
options=""
options+="starting_length=%s%s"%(starting_length,os.linesep)
options+="starting_cell_size=%s%s"%(starting_cell_size,os.linesep)
options+="LengthofExperiments=%s%s"%(LengthofExperiments,os.linesep)
...
open("%s%soptions.py"%(directory,os.sep),'w').write(options)
```
I want to pass a function as one of the parameters:
```
starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
def pippo(a,b):
return a+b
functionoperator=pippo
```
And of course in the real experiment the function pippo will be much more complex. And different from experiment to experiment.
But what I am unable to do is to write the function automatically. In short I don't know how to generalise the writeoptions function to keep on writing the options, if one of the options is a function. I could of course copy the original file, but this is inelegant, inefficient (because it contains a lot of extra options that are not being used), and generally does not solve the question.
How do you get python to write down the code of a function, as it writes down the value of a variable?
|
2008/12/30
|
[
"https://Stackoverflow.com/questions/399991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46634/"
] |
```
vinko@mithril$ more a.py
def foo(a):
print a
vinko@mithril$ more b.py
import a
import inspect
a.foo(89)
print inspect.getsource(a.foo)
vinko@mithril$ python b.py
89
def foo(a):
print a
```
|
You might also consider some other means of data persistence. In my own (astronomy) research, I've been experimenting with two different means of storing scripts for reproducibility. The first is to have them exclusively inside a subversion repository, and then have the job submission script automatically commit them. For instance, if you just wanted to do this in bash:
```
alias run_py='svn ci -m "Commit before running"; python2.5 $*'
```
and inside the script, have the output prefixed by the [current subversion revision number](http://svnbook.red-bean.com/en/1.5/svn.advanced.props.special.keywords.html) for that file, you'd have a record of each script that was run and what the input was. You could pull this back out of subversion as need be.
Another, substantially less full-featured, means of tracking the input to a function could be via something like [LodgeIt](http://paste.pocoo.org/), a pastebin that accepts XML-RPC input and comes with Python bindings. (It can be installed locally, and has support for replying to and updating existing pastes.)
But, if you are looking for a relatively small amount of code to be included, Vinko's solution using inspect should work quite well. Doug Hellman [covered the `inspect` module](http://www.doughellmann.com/PyMOTW/inspect/index.html) in his [Python Module of the Week](http://www.doughellmann.com/PyMOTW/) series. You could create a decorator that examines each option and argument and then prints it out as appropriate (I'll use `inspect.getargspec` to get the names of the arguments.)
```
import inspect
from functools import wraps
def option_printer(func):
@wraps(func)
def run_func(*args, **kwargs):
for name, arg in zip(inspect.getargspec(func)[0], args) \
+ sorted(kwargs.items()):
if isinstance(arg, types.FunctionType):
print "Function argument '%s' named '%s':\n" % (name, func.func_name)
print inspect.getsource(func)
else:
print "%s: %s" % (name, arg)
return func(*args, **kwargs)
return run_func
```
This could probably be made a bit more elegant, but in my tests it works for simple sets of arguments and variables. Additionally, it might have some trouble with lambdas.
|
399,991
|
When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file.
So I have this .py file that reads like:
```
starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
```
Then I execute the file and get the data. Since the program is all on my machine and no one else has access to it, it is secure in a trivial way.
I can also write a similar file very easily:
```
def writeoptions(directory):
options=""
options+="starting_length=%s%s"%(starting_length,os.linesep)
options+="starting_cell_size=%s%s"%(starting_cell_size,os.linesep)
options+="LengthofExperiments=%s%s"%(LengthofExperiments,os.linesep)
...
open("%s%soptions.py"%(directory,os.sep),'w').write(options)
```
I want to pass a function as one of the parameters:
```
starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
def pippo(a,b):
return a+b
functionoperator=pippo
```
And of course in the real experiment the function pippo will be much more complex. And different from experiment to experiment.
But what I am unable to do is to write the function automatically. In short I don't know how to generalise the writeoptions function to keep on writing the options, if one of the options is a function. I could of course copy the original file, but this is inelegant, inefficient (because it contains a lot of extra options that are not being used), and generally does not solve the question.
How do you get python to write down the code of a function, as it writes down the value of a variable?
|
2008/12/30
|
[
"https://Stackoverflow.com/questions/399991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46634/"
] |
You might also consider some other means of data persistence. In my own (astronomy) research, I've been experimenting with two different means of storing scripts for reproducibility. The first is to have them exclusively inside a subversion repository, and then have the job submission script automatically commit them. For instance, if you just wanted to do this in bash:
```
alias run_py='svn ci -m "Commit before running"; python2.5 $*'
```
and inside the script, have the output prefixed by the [current subversion revision number](http://svnbook.red-bean.com/en/1.5/svn.advanced.props.special.keywords.html) for that file, you'd have a record of each script that was run and what the input was. You could pull this back out of subversion as need be.
Another, substantially less full-featured, means of tracking the input to a function could be via something like [LodgeIt](http://paste.pocoo.org/), a pastebin that accepts XML-RPC input and comes with Python bindings. (It can be installed locally, and has support for replying to and updating existing pastes.)
But, if you are looking for a relatively small amount of code to be included, Vinko's solution using inspect should work quite well. Doug Hellman [covered the `inspect` module](http://www.doughellmann.com/PyMOTW/inspect/index.html) in his [Python Module of the Week](http://www.doughellmann.com/PyMOTW/) series. You could create a decorator that examines each option and argument and then prints it out as appropriate (I'll use `inspect.getargspec` to get the names of the arguments.)
```
import inspect
from functools import wraps
def option_printer(func):
@wraps(func)
def run_func(*args, **kwargs):
for name, arg in zip(inspect.getargspec(func)[0], args) \
+ sorted(kwargs.items()):
if isinstance(arg, types.FunctionType):
print "Function argument '%s' named '%s':\n" % (name, func.func_name)
print inspect.getsource(func)
else:
print "%s: %s" % (name, arg)
return func(*args, **kwargs)
return run_func
```
This could probably be made a bit more elegant, but in my tests it works for simple sets of arguments and variables. Additionally, it might have some trouble with lambdas.
|
Are you asking about this?
```
def writeoptions(directory):
options=""
options+="starting_length=%s%s"%(starting_length,os.linesep)
options+="starting_cell_size=%s%s"%(starting_cell_size,os.linesep)
options+="LengthofExperiments=%s%s"%(LengthofExperiments,os.linesep)
options+="def pippo(a,b):%s" % ( os.linesep, )
options+=" '''Some version of pippo'''%s" % ( os.linesep, )
options+=" return 2*a+b%s" % ( os.linesep, )
open("%s%soptions.py"%(directory,os.sep),'w').write(options)
```
Or something else?
|
399,991
|
When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file.
So I have this .py file that reads like:
```
starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
```
Then I execute the file and get the data. Since the program is all on my machine and no one else has access to it, it is secure in a trivial way.
I can also write a similar file very easily:
```
def writeoptions(directory):
options=""
options+="starting_length=%s%s"%(starting_length,os.linesep)
options+="starting_cell_size=%s%s"%(starting_cell_size,os.linesep)
options+="LengthofExperiments=%s%s"%(LengthofExperiments,os.linesep)
...
open("%s%soptions.py"%(directory,os.sep),'w').write(options)
```
I want to pass a function as one of the parameters:
```
starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
def pippo(a,b):
return a+b
functionoperator=pippo
```
And of course in the real experiment the function pippo will be much more complex. And different from experiment to experiment.
But what I am unable to do is to write the function automatically. In short I don't know how to generalise the writeoptions function to keep on writing the options, if one of the options is a function. I could of course copy the original file, but this is inelegant, inefficient (because it contains a lot of extra options that are not being used), and generally does not solve the question.
How do you get python to write down the code of a function, as it writes down the value of a variable?
|
2008/12/30
|
[
"https://Stackoverflow.com/questions/399991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46634/"
] |
You might also consider some other means of data persistence. In my own (astronomy) research, I've been experimenting with two different means of storing scripts for reproducibility. The first is to have them exclusively inside a subversion repository, and then have the job submission script automatically commit them. For instance, if you just wanted to do this in bash:
```
alias run_py='svn ci -m "Commit before running"; python2.5 $*'
```
and inside the script, have the output prefixed by the [current subversion revision number](http://svnbook.red-bean.com/en/1.5/svn.advanced.props.special.keywords.html) for that file, you'd have a record of each script that was run and what the input was. You could pull this back out of subversion as need be.
Another, substantially less full-featured, means of tracking the input to a function could be via something like [LodgeIt](http://paste.pocoo.org/), a pastebin that accepts XML-RPC input and comes with Python bindings. (It can be installed locally, and has support for replying to and updating existing pastes.)
But, if you are looking for a relatively small amount of code to be included, Vinko's solution using inspect should work quite well. Doug Hellman [covered the `inspect` module](http://www.doughellmann.com/PyMOTW/inspect/index.html) in his [Python Module of the Week](http://www.doughellmann.com/PyMOTW/) series. You could create a decorator that examines each option and argument and then prints it out as appropriate (I'll use `inspect.getargspec` to get the names of the arguments.)
```
import inspect
from functools import wraps
def option_printer(func):
@wraps(func)
def run_func(*args, **kwargs):
for name, arg in zip(inspect.getargspec(func)[0], args) \
+ sorted(kwargs.items()):
if isinstance(arg, types.FunctionType):
print "Function argument '%s' named '%s':\n" % (name, func.func_name)
print inspect.getsource(func)
else:
print "%s: %s" % (name, arg)
return func(*args, **kwargs)
return run_func
```
This could probably be made a bit more elegant, but in my tests it works for simple sets of arguments and variables. Additionally, it might have some trouble with lambdas.
|
While it is possible to do what you ask (as Vinko has shown), I'd say it is cleaner to *share code*. Put `pippo` and his buddies in a submodule that both programs can access.
|
399,991
|
When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file.
So I have this .py file that reads like:
```
starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
```
Then I execute the file and get the data. Since the program is all on my machine and no one else has access to it, it is secure in a trivial way.
I can also write a similar file very easily:
```
def writeoptions(directory):
options=""
options+="starting_length=%s%s"%(starting_length,os.linesep)
options+="starting_cell_size=%s%s"%(starting_cell_size,os.linesep)
options+="LengthofExperiments=%s%s"%(LengthofExperiments,os.linesep)
...
open("%s%soptions.py"%(directory,os.sep),'w').write(options)
```
I want to pass a function as one of the parameters:
```
starting_length=9
starting_cell_size=1000
LengthofExperiments=5000000
def pippo(a,b):
return a+b
functionoperator=pippo
```
And of course in the real experiment the function pippo will be much more complex. And different from experiment to experiment.
But what I am unable to do is to write the function automatically. In short I don't know how to generalise the writeoptions function to keep on writing the options, if one of the options is a function. I could of course copy the original file, but this is inelegant, inefficient (because it contains a lot of extra options that are not being used), and generally does not solve the question.
How do you get python to write down the code of a function, as it writes down the value of a variable?
|
2008/12/30
|
[
"https://Stackoverflow.com/questions/399991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46634/"
] |
You might also consider some other means of data persistence. In my own (astronomy) research, I've been experimenting with two different means of storing scripts for reproducibility. The first is to have them exclusively inside a subversion repository, and then have the job submission script automatically commit them. For instance, if you just wanted to do this in bash:
```
alias run_py='svn ci -m "Commit before running"; python2.5 $*'
```
and inside the script, have the output prefixed by the [current subversion revision number](http://svnbook.red-bean.com/en/1.5/svn.advanced.props.special.keywords.html) for that file, you'd have a record of each script that was run and what the input was. You could pull this back out of subversion as need be.
Another, substantially less full-featured, means of tracking the input to a function could be via something like [LodgeIt](http://paste.pocoo.org/), a pastebin that accepts XML-RPC input and comes with Python bindings. (It can be installed locally, and has support for replying to and updating existing pastes.)
But, if you are looking for a relatively small amount of code to be included, Vinko's solution using inspect should work quite well. Doug Hellman [covered the `inspect` module](http://www.doughellmann.com/PyMOTW/inspect/index.html) in his [Python Module of the Week](http://www.doughellmann.com/PyMOTW/) series. You could create a decorator that examines each option and argument and then prints it out as appropriate (I'll use `inspect.getargspec` to get the names of the arguments.)
```
import inspect
from functools import wraps
def option_printer(func):
@wraps(func)
def run_func(*args, **kwargs):
for name, arg in zip(inspect.getargspec(func)[0], args) \
+ sorted(kwargs.items()):
if isinstance(arg, types.FunctionType):
print "Function argument '%s' named '%s':\n" % (name, func.func_name)
print inspect.getsource(func)
else:
print "%s: %s" % (name, arg)
return func(*args, **kwargs)
return run_func
```
This could probably be made a bit more elegant, but in my tests it works for simple sets of arguments and variables. Additionally, it might have some trouble with lambdas.
|
Instead of diving into the subject of [disassemblers](http://docs.python.org/library/dis.html) and bytecodes (e.g [inspect](http://docs.python.org/library/inspect.html)), why don't you just save the generated Python source in a module (*file.py*), and later, import it?
I would suggest looking into a more standard way of handling what you call *options*. For example, you can use the [JSON](http://docs.python.org/library/json.html) module and save or restore your data. Or look into the [marshal](http://docs.python.org/library/marshal.html#module-marshal) and [pickle](http://docs.python.org/library/pickle.html#module-pickle) modules.
|
51,007,893
|
I have a homework to draw a spiral(from inside to outside) in python with turtle, but I cant think of a way to do that, beside what I did its need to be like this:
[](https://i.stack.imgur.com/UQCW8.gif)
I tried to do it like that, but its not working properly.
```
import turtle
turtle.shape ('turtle')
d = 20 #Distance
a = 1 #StartingAngle
x = 200 #Num of loops
for i in range (x):
turtle.left(a)
turtle.forward(d)
a = a + 5
```
|
2018/06/24
|
[
"https://Stackoverflow.com/questions/51007893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7528938/"
] |
As described in this link : [Create Deep Links](https://developer.android.com/training/app-links/deep-linking)
You should add this in your manifest :
```
<activity
android:name="com.example.android.GizmosActivity"
android:label="@string/title_gizmos" >
<intent-filter android:label="@string/filter_view_http_gizmos">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<!-- Accepts URIs that begin with "http://www.example.com/gizmos” -->
<data android:scheme="http"
android:host="www.example.com"
android:pathPrefix="/gizmos" />
<!-- note that the leading "/" is required for pathPrefix-->
</intent-filter>
</activity>
```
and then share a link that starts with "<http://www.example.com/gizmos>" (fake url) with another person.
|
Yes it is possible by handling adding state parms in your url and then redirecting to play store from your server side code.
eg - your app generates url which points to some user profile -
<https://www.yourSocialNewtwork.com/profile/sandeshDahake>
Step 1 - Create a deep link in your app with intent filter. This will handle your app is already installed and pass params to it -
```
<data android:scheme="https"
android:host="www.yourSocialNewtwork.com"
android:pathPrefix="/profile" />
```
Step2 - If app is not installed you can redirect to play store from your server side
<https://developer.android.com/google/play/installreferrer/library#java>
<https://play.google.com/store/apps/details?id=com.profile.yourHierarchy> &referrer=sandeshDahake
I have heard there are some opensource projects which handle this scenario but not explored them yet.
Basically trick here is proper url structure and deep linking.
<https://developer.android.com/training/app-links/deep-linking>
|
70,431,040
|
I think the title gives the general idea of what I am looking for, but to be more specific I will give an example with code.
So let's say I have a Python class with a few required position variables that also takes an arbitrary number of keyword arguments. The class has many data members, and some of them will be defined by the required position variables, but most are keyword argument variables where the program has default values for these variables, but if the user uses a keyword argument this will override the defaults. I am looking for the most "pythonic" way to initialize a class of this type. I have two ideas for how to do this, but each of them feels unsatisfying and like there is a more pythonic way I am missing.
```
#First Option
class SampleOne:
def __init__(pos1, pos2, **kwargs):
def do_defaults():
self.kwarg1 = default_kwarg1
self.kwarg2 = default_kwarg2
self.kwarg3 = default_kwarg3
def do_given():
for variable, value in kwargs.items():
self.variable = value
self.pos1 = pos1
self.pos2 = pos2
do_defaults()
do_given()
```
Or
```
#Second Option
class SampleTwo:
def __init__(pos1, pos2, **kwargs):
self.pos1 = pos1
self.pos2 = pos2
self.kwarg1 = kwargs[kwarg1] if kwarg1 in kwargs else default_kwarg1
self.kwarg2 = kwargs[kwarg2] if kwarg2 in kwargs else default_kwarg2
self.kwarg3 = kwargs[kwarg3] if kwarg3 in kwargs else default_kwarg3
```
I don't love the first option because it seems wasteful to set a bunch of default data members if a bunch are going to be changed, especially if there are many data members.
I don't love the second option because it looks unnecessarily busy and less readable in my opinion - I like the separation of the default values from the user-defined values and think it will make my code easier to read and change.
Also, I am using \*\*kwargs instead of keyword arguments with default values because I am still in the early phase of the development of this codebase so the member variables needed are subject to change, but also because there is going to be a lot of member variables and it will make the function signature very ugly to have all of those parameters.
Apologies if my question is a bit long-winded, this is one of my first times asking questions on StackOverflow and I wanted to make sure I gave enough detail.
Also if it makes a difference my code needs to work in Python 3.8 and later.
|
2021/12/21
|
[
"https://Stackoverflow.com/questions/70431040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16043632/"
] |
It would be easier to find the answer if you explained the purpose for the requirement.
From my experience one common task is to distinguish `authorization_code` and `client_credentials` flow use for the same client, but that's easy: the second one does not contain user information (`sub` and `sid` claims).
Also don't forget about restricted auth flow combinations in Identityserver (for instance you can't allow both `implicit` and `authorization_code` flow for the same client), so one client is usually bound to the only user interactive flow.
Finally, the auth flow is generally not about API. It's only about interaction among IdP and Client. API usually use scopes as general information about clients, so... when you have two clients -- one with `implicit` grant and the other with `authorization_code`, you can distinguish which one is in use by setting different scopes.
Isn't that enough?
A [check for a particular grant type](https://github.com/dfrunet/IdentityServer4.Quickstart.UI/blob/9bb00961aa22c2d105b2259541acc065415b7d9b/Extensions/ExtendedClaimsService.cs#L159) could be performed in Identityserver the following way:
```cs
public class ExtendedClaimsService : DefaultClaimsService{
public override async Task<IEnumerable<Claim>> GetAccessTokenClaimsAsync(
ClaimsPrincipal subject,
ResourceValidationResult resourceResult,
ValidatedRequest request)
{
var outputClaims = (await base.GetAccessTokenClaimsAsync(subject, resourceResult, request)).ToList();
//if (request.Secret.Type == "NoSecret") //this is more or less the same
if ((request as ValidatedTokenRequest)?.GrantType != "client_credentials")
{
//filter out server-side-only scopes here
//or add any custom claim you like
}
return outputClaims;
}
}
```
Registration: `services.AddTransient<IClaimsService, ExtendedClaimsService>();` after `services.AddIdentityServer()` in your `Startup`
|
One option is to have different client definitions for the different flows and then use a [ClientClaim](https://docs.duendesoftware.com/identityserver/v5/fundamentals/claims/#client-claims) to indicate what type of client it is:
To set the client claims in the client definition just set it like:
```
ClientClaimsPrefix="",
AlwaysSendClientClaims=true,
Claims = new List<ClientClaim>()
{
new ClientClaim("role","admin"),
new ClientClaim("name","joe"),
new ClientClaim("admin","yes"),
new ClientClaim("employmentid","employee"),
new ClientClaim("employeetype","yes"),
new ClientClaim("creditlimit","100000")
}
```
|
10,062,967
|
Is there an idiomatic way of encoding and decoding a string in Clojure as hexadecimal? Example from Python:
```python
'Clojure'.encode('hex')
# ⇒ '436c6f6a757265'
'436c6f6a757265'.decode('hex')
# ⇒ 'Clojure'
```
To show some effort on my part:
```clj
(defn hexify [s]
(apply str
(map #(format "%02x" (int %)) s)))
(defn unhexify [hex]
(apply str
(map
(fn [[x y]] (char (Integer/parseInt (str x y) 16)))
(partition 2 hex))))
(hexify "Clojure")
;; ⇒ "436c6f6a757265"
(unhexify "436c6f6a757265")
;; ⇒ "Clojure"
```
|
2012/04/08
|
[
"https://Stackoverflow.com/questions/10062967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/165806/"
] |
Your implementation(s) don't work for non-ascii characters,
```clj
(defn hexify [s]
(apply str
(map #(format "%02x" (int %)) s)))
(defn unhexify [hex]
(apply str
(map
(fn [[x y]] (char (Integer/parseInt (str x y) 16)))
(partition 2 hex))))
(= "\u2195" (unhexify(hexify "\u2195")))
false ; should be true
```
To overcome this you need to serialize the bytes of the string using the required character encoding, which can be multi-byte per character.
There are a few 'issues' with this.
* Remember that all numeric types are signed in the JVM.
* There is no unsigned-byte.
In idiomatic java you would use the low byte of an integer and mask it like this wherever you used it.
```java
int intValue = 0x80;
byte byteValue = (byte)(intValue & 0xff); -- use only low byte
System.out.println("int:\t" + intValue);
System.out.println("byte:\t" + byteValue);
-- output:
-- int: 128
-- byte: -128
```
clojure has `(unchecked-byte)` to effectively do the same.
For example, using UTF-8 you can do this:
```clj
(defn hexify [s]
(apply str (map #(format "%02x" %) (.getBytes s "UTF-8"))))
(defn unhexify [s]
(let [bytes (into-array Byte/TYPE
(map (fn [[x y]]
(unchecked-byte (Integer/parseInt (str x y) 16)))
(partition 2 s)))]
(String. bytes "UTF-8")))
; with the above implementation:
;=> (hexify "\u2195")
"e28695"
;=> (unhexify "e28695")
"↕"
;=> (= "\u2195" (unhexify (hexify "\u2195")))
true
```
|
I believe your `unhexify` function is as idiomatic as it can be. However, `hexify` can be written in a simpler way:
```
(defn hexify [s]
(format "%x" (new java.math.BigInteger (.getBytes s))))
```
|
10,062,967
|
Is there an idiomatic way of encoding and decoding a string in Clojure as hexadecimal? Example from Python:
```python
'Clojure'.encode('hex')
# ⇒ '436c6f6a757265'
'436c6f6a757265'.decode('hex')
# ⇒ 'Clojure'
```
To show some effort on my part:
```clj
(defn hexify [s]
(apply str
(map #(format "%02x" (int %)) s)))
(defn unhexify [hex]
(apply str
(map
(fn [[x y]] (char (Integer/parseInt (str x y) 16)))
(partition 2 hex))))
(hexify "Clojure")
;; ⇒ "436c6f6a757265"
(unhexify "436c6f6a757265")
;; ⇒ "Clojure"
```
|
2012/04/08
|
[
"https://Stackoverflow.com/questions/10062967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/165806/"
] |
Since all posted solutions have some flaws, I'm sharing my own:
```clj
(defn hexify "Convert byte sequence to hex string" [coll]
(let [hex [\0 \1 \2 \3 \4 \5 \6 \7 \8 \9 \a \b \c \d \e \f]]
(letfn [(hexify-byte [b]
(let [v (bit-and b 0xFF)]
[(hex (bit-shift-right v 4)) (hex (bit-and v 0x0F))]))]
(apply str (mapcat hexify-byte coll)))))
(defn hexify-str [s]
(hexify (.getBytes s)))
```
and
```clj
(defn unhexify "Convert hex string to byte sequence" [s]
(letfn [(unhexify-2 [c1 c2]
(unchecked-byte
(+ (bit-shift-left (Character/digit c1 16) 4)
(Character/digit c2 16))))]
(map #(apply unhexify-2 %) (partition 2 s))))
(defn unhexify-str [s]
(apply str (map char (unhexify s))))
```
Pros:
* High performance
* Generic byte stream <--> string conversions with specialized wrappers
* Handling leading zero in hex result
|
I believe your `unhexify` function is as idiomatic as it can be. However, `hexify` can be written in a simpler way:
```
(defn hexify [s]
(format "%x" (new java.math.BigInteger (.getBytes s))))
```
|
10,062,967
|
Is there an idiomatic way of encoding and decoding a string in Clojure as hexadecimal? Example from Python:
```python
'Clojure'.encode('hex')
# ⇒ '436c6f6a757265'
'436c6f6a757265'.decode('hex')
# ⇒ 'Clojure'
```
To show some effort on my part:
```clj
(defn hexify [s]
(apply str
(map #(format "%02x" (int %)) s)))
(defn unhexify [hex]
(apply str
(map
(fn [[x y]] (char (Integer/parseInt (str x y) 16)))
(partition 2 hex))))
(hexify "Clojure")
;; ⇒ "436c6f6a757265"
(unhexify "436c6f6a757265")
;; ⇒ "Clojure"
```
|
2012/04/08
|
[
"https://Stackoverflow.com/questions/10062967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/165806/"
] |
Your implementation(s) don't work for non-ascii characters,
```clj
(defn hexify [s]
(apply str
(map #(format "%02x" (int %)) s)))
(defn unhexify [hex]
(apply str
(map
(fn [[x y]] (char (Integer/parseInt (str x y) 16)))
(partition 2 hex))))
(= "\u2195" (unhexify(hexify "\u2195")))
false ; should be true
```
To overcome this you need to serialize the bytes of the string using the required character encoding, which can be multi-byte per character.
There are a few 'issues' with this.
* Remember that all numeric types are signed in the JVM.
* There is no unsigned-byte.
In idiomatic java you would use the low byte of an integer and mask it like this wherever you used it.
```java
int intValue = 0x80;
byte byteValue = (byte)(intValue & 0xff); -- use only low byte
System.out.println("int:\t" + intValue);
System.out.println("byte:\t" + byteValue);
-- output:
-- int: 128
-- byte: -128
```
clojure has `(unchecked-byte)` to effectively do the same.
For example, using UTF-8 you can do this:
```clj
(defn hexify [s]
(apply str (map #(format "%02x" %) (.getBytes s "UTF-8"))))
(defn unhexify [s]
(let [bytes (into-array Byte/TYPE
(map (fn [[x y]]
(unchecked-byte (Integer/parseInt (str x y) 16)))
(partition 2 s)))]
(String. bytes "UTF-8")))
; with the above implementation:
;=> (hexify "\u2195")
"e28695"
;=> (unhexify "e28695")
"↕"
;=> (= "\u2195" (unhexify (hexify "\u2195")))
true
```
|
Sadly the "idiom" appears to be using the [Apache Commons Codec](http://commons.apache.org/proper/commons-codec/), e.g. as [done in `buddy`](https://github.com/funcool/buddy-core/blob/master/src/buddy/core/codecs.clj):
```
(ns name-of-ns
(:import org.apache.commons.codec.binary.Hex))
(defn str->bytes
"Convert string to byte array."
([^String s]
(str->bytes s "UTF-8"))
([^String s, ^String encoding]
(.getBytes s encoding)))
(defn bytes->str
"Convert byte array to String."
([^bytes data]
(bytes->str data "UTF-8"))
([^bytes data, ^String encoding]
(String. data encoding)))
(defn bytes->hex
"Convert a byte array to hex encoded string."
[^bytes data]
(Hex/encodeHexString data))
(defn hex->bytes
"Convert hexadecimal encoded string to bytes array."
[^String data]
(Hex/decodeHex (.toCharArray data)))
```
|
10,062,967
|
Is there an idiomatic way of encoding and decoding a string in Clojure as hexadecimal? Example from Python:
```python
'Clojure'.encode('hex')
# ⇒ '436c6f6a757265'
'436c6f6a757265'.decode('hex')
# ⇒ 'Clojure'
```
To show some effort on my part:
```clj
(defn hexify [s]
(apply str
(map #(format "%02x" (int %)) s)))
(defn unhexify [hex]
(apply str
(map
(fn [[x y]] (char (Integer/parseInt (str x y) 16)))
(partition 2 hex))))
(hexify "Clojure")
;; ⇒ "436c6f6a757265"
(unhexify "436c6f6a757265")
;; ⇒ "Clojure"
```
|
2012/04/08
|
[
"https://Stackoverflow.com/questions/10062967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/165806/"
] |
Since all posted solutions have some flaws, I'm sharing my own:
```clj
(defn hexify "Convert byte sequence to hex string" [coll]
(let [hex [\0 \1 \2 \3 \4 \5 \6 \7 \8 \9 \a \b \c \d \e \f]]
(letfn [(hexify-byte [b]
(let [v (bit-and b 0xFF)]
[(hex (bit-shift-right v 4)) (hex (bit-and v 0x0F))]))]
(apply str (mapcat hexify-byte coll)))))
(defn hexify-str [s]
(hexify (.getBytes s)))
```
and
```clj
(defn unhexify "Convert hex string to byte sequence" [s]
(letfn [(unhexify-2 [c1 c2]
(unchecked-byte
(+ (bit-shift-left (Character/digit c1 16) 4)
(Character/digit c2 16))))]
(map #(apply unhexify-2 %) (partition 2 s))))
(defn unhexify-str [s]
(apply str (map char (unhexify s))))
```
Pros:
* High performance
* Generic byte stream <--> string conversions with specialized wrappers
* Handling leading zero in hex result
|
Sadly the "idiom" appears to be using the [Apache Commons Codec](http://commons.apache.org/proper/commons-codec/), e.g. as [done in `buddy`](https://github.com/funcool/buddy-core/blob/master/src/buddy/core/codecs.clj):
```
(ns name-of-ns
(:import org.apache.commons.codec.binary.Hex))
(defn str->bytes
"Convert string to byte array."
([^String s]
(str->bytes s "UTF-8"))
([^String s, ^String encoding]
(.getBytes s encoding)))
(defn bytes->str
"Convert byte array to String."
([^bytes data]
(bytes->str data "UTF-8"))
([^bytes data, ^String encoding]
(String. data encoding)))
(defn bytes->hex
"Convert a byte array to hex encoded string."
[^bytes data]
(Hex/encodeHexString data))
(defn hex->bytes
"Convert hexadecimal encoded string to bytes array."
[^String data]
(Hex/decodeHex (.toCharArray data)))
```
|
57,318,921
|
I'm trying to use xtensor-python example found [here](https://xtensor-python.readthedocs.io/en/latest/).
I have xtensor-python, pybind11, and xtensor installed and also created a CMakeLists.txt.
from /build I ran.
$ cmake ..
$ make
and it builds without errors.
My CMakeLists.txt looks like this.
```
cmake_minimum_required(VERSION 3.15)
project(P3)
find_package(xtensor-python REQUIRED)
find_package(pybind11 REQUIRED)
find_package(xtensor REQUIRED)
```
My example.cpp file.
```
#include <numeric> // Standard library import for std::accumulate
#include "pybind11/pybind11.h" // Pybind11 import to define Python bindings
#include "xtensor/xmath.hpp" // xtensor import for the C++ universal functions
#define FORCE_IMPORT_ARRAY // numpy C api loading
#include "xtensor-python/pyarray.hpp" // Numpy bindings
double sum_of_sines(xt::pyarray<double>& m)
{
auto sines = xt::sin(m); // sines does not actually hold values.
return std::accumulate(sines.cbegin(), sines.cend(), 0.0);
}
PYBIND11_MODULE(ex3, m)
{
xt::import_numpy();
m.doc() = "Test module for xtensor python bindings";
m.def("sum_of_sines", sum_of_sines, "Sum the sines of the input values");
}
```
My python file.
```
import numpy as np
import example as ext
a = np.arange(15).reshape(3, 5)
s = ext.sum_of_sines(v)
s
```
But my python file can't import my example.cpp file.
```
File "examplepyth.py", line 2, in <module>
import example as ext
ImportError: No module named 'example'
```
I am new to cmake. I would like to know how to set this project up properly with CMakeLists.txt
|
2019/08/02
|
[
"https://Stackoverflow.com/questions/57318921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11395552/"
] |
This is actually really simple and done in a few lines
```c#
public GameObject prefab;
public float radius;
public float amount;
// Start is called before the first frame update
private void Start()
{
var angle = 0f;
for (var i = 0; i <= amount; i++)
{
var y = Mathf.Sin(Mathf.Deg2Rad * angle) * radius;
var z = - Mathf.Cos(Mathf.Deg2Rad * angle) * radius;
var obj = Instantiate(prefab, transform);
obj.transform.localPosition = new Vector3(0, y, z);
obj.transform.localRotation = Quaternion.Euler(angle, 0, 0);
angle += (360f / amount);
}
}
// just for demo
private void Update()
{
transform.localRotation = Quaternion.Euler(Time.time * 45, 0, 0);
}
```
---
[](https://i.stack.imgur.com/S2P0Y.png)
[](https://i.stack.imgur.com/0jTCe.gif)
|
Ok, so this is more of a math problem then anything else really. Now assuming that you are not a total beginner with Unity I will not write you code for your solution, but just generaly describe it.
First thing you need to be inputed is radius, this will determine how far away from the center of the circle should your items be. You can just take the scale of the circle object and multiply it by some variable value. Then you also need the number of ticks that you wish to place around the circle as a variable. In your case this can be 27. Then divide 360 by that variable and you should get a segment of the circle for each item.
Last thing you need to do is put a for loop for each tick on the circle and in there spawn an item on point where you get the point position by taking a vector from the center of the circle to the top point and multiply it by an Euler that has as many degrees as the segment size that we got earlier. For the rotation of the object, you just need to subtract it with the same segment size and thats basically it.
Hope this helps. If you need some code clarification I can provide it later today.
|
48,825,312
|
I am new to python,
I have written test cases for my class ,
I am using
`python -m pytest --cov=azuread_api` to get code coverage.
I am getting coverage on the console as [](https://i.stack.imgur.com/iKRNP.png)
How do I get which lines are missed by test for e.g in aadadapter.py file
Thanks,
|
2018/02/16
|
[
"https://Stackoverflow.com/questions/48825312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3556028/"
] |
If you check the [documentation for reporting](https://pytest-cov.readthedocs.io/en/latest/reporting.html) in pytest-cov, you can see how to manipulate the report and generate extra versions.
For example, adding the option `--cov-report term-missing` you'll get the missing lines printed in the terminal.
A more user friendly option, would be to generate an html report by usign the `--cov-report html` option. Then you can navigate to the generated folder (`htmlcov` by default) and open the `index.html` with your browser and navigate your source code where the missing lines are highlighted.
|
In addition to the [answer from Ignacio](https://stackoverflow.com/a/48825483/149900), one can also set [`show_missing = true`](https://coverage.readthedocs.io/en/latest/config.html#config-report-show-missing) in `.coveragerc`, as pytest-cov reads that config file as well.
|
30,987,825
|
I have a list of lists in python. I want to group similar lists together. That is, if first three elements of each list are the same then those three lists should go in one group. For eg
```
[["a", "b", "c", 1, 2],
["d", "f", "g", 8, 9],
["a", "b", "c", 3, 4],
["d","f", "g", 3, 4],
["a", "b", "c", 5, 6]]
```
I want this to look like
```
[[["a", "b", "c", 1, 2],
["a", "b", "c", 5, 6],
["a", "b", "c", 3, 4]],
[["d","f", "g", 3, 4],
["d", "f", "g", 8, 9]]]
```
I could do this by running an iterator and manually comparing each element of two consecutive lists and then based on the no of elements within those lists that were same I can decide to group them together. But i was just wondering if there is any other way or a pythonic way to do this.
|
2015/06/22
|
[
"https://Stackoverflow.com/questions/30987825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4378672/"
] |
You can use [`itertools.groupby`](https://docs.python.org/3.4/library/itertools.html#itertools.groupby) :
```
>>> A=[["a", "b", "c", 1, 2],
... ["d", "f", "g", 8, 9],
... ["a", "b", "c", 3, 4],
... ["d","f", "g", 3, 4],
... ["a", "b", "c", 5, 6]]
>>> from operator import itemgetter
>>> [list(g) for _,g in groupby(sorted(A),itemgetter(0,1,2)]
[[['a', 'b', 'c', 1, 2], ['a', 'b', 'c', 3, 4], ['a', 'b', 'c', 5, 6]], [['d', 'f', 'g', 3, 4], ['d', 'f', 'g', 8, 9]]]
```
|
You don't need to sort, you can group in a dict using a tuple of the first three elements from each list as the key:
```
from collections import OrderedDict
l=[
["a", "b", "c", 1, 2],
["d", "f", "g", 8, 9],
["a", "b", "c", 3, 4],
["d","f", "g", 3, 4],
["a", "b", "c", 5, 6]
]
od = OrderedDict()
for sub in l:
k = tuple(sub[:3])
od.setdefault(k,[]).append(sub)
from pprint import pprint as pp
pp(od.values())
[[['a', 'b', 'c', 1, 2], ['a', 'b', 'c', 3, 4], ['a', 'b', 'c', 5, 6]],
[['d', 'f', 'g', 8, 9], ['d', 'f', 'g', 3, 4]]]
```
Which is `O(n)` as opposed to `O(n log n)`.
If you don't care about order use a defaultdict:
```
from collections import defaultdict
od = defaultdict(list)
for sub in l:
a, b, c, *_ = sub # python3
k = a,b,c
od[k].append(sub)
from pprint import pprint as pp
pp(list(od.values()))
[[['a', 'b', 'c', 1, 2], ['a', 'b', 'c', 3, 4], ['a', 'b', 'c', 5, 6]],
[['d', 'f', 'g', 8, 9], ['d', 'f', 'g', 3, 4]]]
```
|
24,272,228
|
I am using ArgParse for giving commandline parameters in Python.
```
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--quality", type=int,help="enter some quality limit")
args = parser.parse_args()
qual=args.quality
if args.quality:
qual=0
$ python a.py --quality
a.py: error: argument --quality: expected one argument
```
In case of no value provided,I want to use it as 0,I also have tried to put it as "default=0" in parser.add\_argument,and also with an if statement.But,I get the error above.
Basically,I want to use it as a flag and give a default value in case no value is provided.
|
2014/06/17
|
[
"https://Stackoverflow.com/questions/24272228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2596951/"
] |
Use `nargs='?'` to allow `--quality` to be used with 0 or 1 value supplied. Use `const=0` to handle `script.py --quality` without a value supplied. Use `default=0` to handle bare calls to `script.py` (without `--quality` supplied).
```
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--quality", type=int, help="enter some quality limit",
nargs='?', default=0, const=0)
args = parser.parse_args()
print(args)
```
behaves like this:
```
% script.py
Namespace(quality=0)
% script.py --quality
Namespace(quality=0)
% script.py --quality 1
Namespace(quality=1)
```
|
Have a loot at <https://docs.python.org/2/howto/argparse.html#id1>. Simply add the argument `default` to your add\_argument call.
`parser.add_argument("--quality", type=int, default=0, nargs='?', help="enter some quality limit")`
If you want to use `--quality` as a flag you should use `action="store_true"`. This will set `args.quality` to `True` if `--quality` is used.
|
24,272,228
|
I am using ArgParse for giving commandline parameters in Python.
```
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--quality", type=int,help="enter some quality limit")
args = parser.parse_args()
qual=args.quality
if args.quality:
qual=0
$ python a.py --quality
a.py: error: argument --quality: expected one argument
```
In case of no value provided,I want to use it as 0,I also have tried to put it as "default=0" in parser.add\_argument,and also with an if statement.But,I get the error above.
Basically,I want to use it as a flag and give a default value in case no value is provided.
|
2014/06/17
|
[
"https://Stackoverflow.com/questions/24272228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2596951/"
] |
Have a loot at <https://docs.python.org/2/howto/argparse.html#id1>. Simply add the argument `default` to your add\_argument call.
`parser.add_argument("--quality", type=int, default=0, nargs='?', help="enter some quality limit")`
If you want to use `--quality` as a flag you should use `action="store_true"`. This will set `args.quality` to `True` if `--quality` is used.
|
With `docopt` use `[default: 0]` in docstring
=============================================
Deliberately ignoring the `argparse` part of your question, here is how you could define default using `docopt`.
With `docopt` you define default value (and almost all the rest) as part of docstring.
First, install `docopt` and for validating values also `schema`
```
$ pip install docopt schema
```
Then write the script `a.py`:
```
"""
Usage:
a.py [--quality <qlimit>]
a.py -h
Options:
--quality=<qlimit> Quality limit [default: 0]
"""
def main(quality):
print "FROM MAIN: minimal quality was set to", quality
if __name__ == "__main__":
from docopt import docopt
from schema import Schema, And, Use, SchemaError
args = docopt(__doc__)
print args
schema = Schema({
"--quality":
And(Use(int), lambda n: 0 <= n, error="<qlimit> must be non-negative integer"),
"-h": bool
})
try:
args = schema.validate(args)
except SchemaError as e:
exit(e)
quality = args["--quality"]
main(quality)
```
and use the script, first asking for help string:
```
$ python a.py -h
Usage:
a.py [--quality <qlimit>]
a.py -h
Options:
--quality=<qlimit> Quality limit [default: 0]
```
Then use it using default value:
```
$ python a.py
{'--quality': '0',
'-h': False}
FROM MAIN: minimal quality was set to 0
```
setting non-default correct one to 5:
```
$ python a.py --quality 5
{'--quality': '5',
'-h': False}
FROM MAIN: minimal quality was set to 5
```
trying not allowed negative value:
```
$ python a.py --quality -99
{'--quality': '-99',
'-h': False}
<qlimit> must be non-negative integer
```
or non integer one:
```
$ python a.py --quality poor
{'--quality': 'poor',
'-h': False}
<qlimit> must be non-negative integer
```
Note, that as soon as the `validate` step passes, the value for "--quality" key is already converted to `int`.
|
24,272,228
|
I am using ArgParse for giving commandline parameters in Python.
```
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--quality", type=int,help="enter some quality limit")
args = parser.parse_args()
qual=args.quality
if args.quality:
qual=0
$ python a.py --quality
a.py: error: argument --quality: expected one argument
```
In case of no value provided,I want to use it as 0,I also have tried to put it as "default=0" in parser.add\_argument,and also with an if statement.But,I get the error above.
Basically,I want to use it as a flag and give a default value in case no value is provided.
|
2014/06/17
|
[
"https://Stackoverflow.com/questions/24272228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2596951/"
] |
Use `nargs='?'` to allow `--quality` to be used with 0 or 1 value supplied. Use `const=0` to handle `script.py --quality` without a value supplied. Use `default=0` to handle bare calls to `script.py` (without `--quality` supplied).
```
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--quality", type=int, help="enter some quality limit",
nargs='?', default=0, const=0)
args = parser.parse_args()
print(args)
```
behaves like this:
```
% script.py
Namespace(quality=0)
% script.py --quality
Namespace(quality=0)
% script.py --quality 1
Namespace(quality=1)
```
|
With `docopt` use `[default: 0]` in docstring
=============================================
Deliberately ignoring the `argparse` part of your question, here is how you could define default using `docopt`.
With `docopt` you define default value (and almost all the rest) as part of docstring.
First, install `docopt` and for validating values also `schema`
```
$ pip install docopt schema
```
Then write the script `a.py`:
```
"""
Usage:
a.py [--quality <qlimit>]
a.py -h
Options:
--quality=<qlimit> Quality limit [default: 0]
"""
def main(quality):
print "FROM MAIN: minimal quality was set to", quality
if __name__ == "__main__":
from docopt import docopt
from schema import Schema, And, Use, SchemaError
args = docopt(__doc__)
print args
schema = Schema({
"--quality":
And(Use(int), lambda n: 0 <= n, error="<qlimit> must be non-negative integer"),
"-h": bool
})
try:
args = schema.validate(args)
except SchemaError as e:
exit(e)
quality = args["--quality"]
main(quality)
```
and use the script, first asking for help string:
```
$ python a.py -h
Usage:
a.py [--quality <qlimit>]
a.py -h
Options:
--quality=<qlimit> Quality limit [default: 0]
```
Then use it using default value:
```
$ python a.py
{'--quality': '0',
'-h': False}
FROM MAIN: minimal quality was set to 0
```
setting non-default correct one to 5:
```
$ python a.py --quality 5
{'--quality': '5',
'-h': False}
FROM MAIN: minimal quality was set to 5
```
trying not allowed negative value:
```
$ python a.py --quality -99
{'--quality': '-99',
'-h': False}
<qlimit> must be non-negative integer
```
or non integer one:
```
$ python a.py --quality poor
{'--quality': 'poor',
'-h': False}
<qlimit> must be non-negative integer
```
Note, that as soon as the `validate` step passes, the value for "--quality" key is already converted to `int`.
|
4,858,733
|
Python has this magic [`__call__`](http://docs.python.org/reference/datamodel.html#object.__call__) method that gets called when the object is called like a function. Does C# support something similar?
---
Specifically, I was hoping for a way to use delegates and objects interchangeably. Trying to design an API where a user can pass in a list of functions, but sometimes those functions need some initial params, in which case they'd use one of those callable objects instead.
|
2011/02/01
|
[
"https://Stackoverflow.com/questions/4858733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/65387/"
] |
Sure, if you inherit from [DynamicObject](http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx). I think you're after [TryInvoke](http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.tryinvoke.aspx) which executes on `obj(...)`, but there are several other method you can override to handle casting, index access (`obj[idx]`), method invocations, property invocations, etc.
```
using System;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Text;
namespace ConsoleApplication {
public static class ConsoleApp {
public static void Main() {
dynamic x = new MyDynamicObject();
var result = x("awe", "some");
Debug.Assert(result == "awesome");
}
}
public class MyDynamicObject : DynamicObject {
public override Boolean TryInvoke(InvokeBinder binder, Object[] args, out Object result) {
result = args.Aggregate(new StringBuilder(), (builder, item) => builder.Append(item), builder => builder.ToString());
return true;
}
}
}
```
|
I bow to Simon Svensson - who shows a way to do it if you inherit from DynamicObject - for a more strait forward non dynamic point of view:
Sorry but no - but there are types of objects that can be called - delegates for instance.
```
Func<int, int> myDelagate = x=>x*2;
int four = myDelagate(2)
```
There is a default property though - that has to have at least one parameter and its access looks like an array access:
```
class Test1
{
public int this[int i, int j]
{
get { return i * j; }
}
}
```
Calling
```
Test1 test1 = new Test1();
int six = test1[2, 3];
```
Then you can do some really silly stuff with delegates like this:
```
class Test2 // I am not saying that this is a good idea.
{
private int MyFunc(int z, int i)
{
return z * i;
}
public Func<int, int> this[int i] { get { return x => MyFunc(x, i); } }
}
```
Then calling it looks weird like this:
```
Test2 test = new Test2();
test[2](2); // this is quite silly - don't use this.....
```
|
4,858,733
|
Python has this magic [`__call__`](http://docs.python.org/reference/datamodel.html#object.__call__) method that gets called when the object is called like a function. Does C# support something similar?
---
Specifically, I was hoping for a way to use delegates and objects interchangeably. Trying to design an API where a user can pass in a list of functions, but sometimes those functions need some initial params, in which case they'd use one of those callable objects instead.
|
2011/02/01
|
[
"https://Stackoverflow.com/questions/4858733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/65387/"
] |
Sure, if you inherit from [DynamicObject](http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx). I think you're after [TryInvoke](http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.tryinvoke.aspx) which executes on `obj(...)`, but there are several other method you can override to handle casting, index access (`obj[idx]`), method invocations, property invocations, etc.
```
using System;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Text;
namespace ConsoleApplication {
public static class ConsoleApp {
public static void Main() {
dynamic x = new MyDynamicObject();
var result = x("awe", "some");
Debug.Assert(result == "awesome");
}
}
public class MyDynamicObject : DynamicObject {
public override Boolean TryInvoke(InvokeBinder binder, Object[] args, out Object result) {
result = args.Aggregate(new StringBuilder(), (builder, item) => builder.Append(item), builder => builder.ToString());
return true;
}
}
}
```
|
This would be akin to overloading the function call operator (as is possible in C++). Unfortunately, this is not something which is supported in C#. The only objects that can be called like methods are instances of delegates.
|
21,377,656
|
Why is the self.year twice? I am having trouble to find out the logic of the line. Can some one help me with this?
```
return (self.year and self.year == date.year or True)
```
I am going through <http://www.openp2p.com/pub/a/python/2004/12/02/tdd_pyunit.html> and encountered the line ... And of course I have no problem understanding and, or, nor, xor, xnor, or any boolean expression. But I am confused by the way it has been used here..
:-)
|
2014/01/27
|
[
"https://Stackoverflow.com/questions/21377656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2770850/"
] |
Assuming these are parallel arrays (the first entry in `eenhedennamen` uses the first entry in `value`), you can loop through with jQuery's [`$.each`](http://api.jquery.com/jQuery.each), which gives you the index and the entry for each entry, and build the object from the loop.
```
var obj = {};
$.each(eenhedennamen, function(index, entry) {
obj[entry] = value[index];
});
```
This works because in JavaScript, you can access properties using either dot notation and a property name literal (`obj.foo = "bar"`), or *bracketed* notation with a *string* property name (`obj["foo"] = "bar"`). In the latter case, the string can be the result of any expression. So in the above, we're using `entry` as the property name, which will be each name in `eenhedennamen`. Then of course, we get the corresponding value from `value` using the `index`.
|
```
var eenhedennamen = [ 'unit1', 'unit2', 'unit3' ];
var value = [ 1, 2, 3 ];
var z = new Array();
for ( var i = 0; i < eenhedennamen.length; i++) {
z[eenhedennamen[i]]=value[i];
}
```
The previous answer is better.
|
21,377,656
|
Why is the self.year twice? I am having trouble to find out the logic of the line. Can some one help me with this?
```
return (self.year and self.year == date.year or True)
```
I am going through <http://www.openp2p.com/pub/a/python/2004/12/02/tdd_pyunit.html> and encountered the line ... And of course I have no problem understanding and, or, nor, xor, xnor, or any boolean expression. But I am confused by the way it has been used here..
:-)
|
2014/01/27
|
[
"https://Stackoverflow.com/questions/21377656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2770850/"
] |
Assuming these are parallel arrays (the first entry in `eenhedennamen` uses the first entry in `value`), you can loop through with jQuery's [`$.each`](http://api.jquery.com/jQuery.each), which gives you the index and the entry for each entry, and build the object from the loop.
```
var obj = {};
$.each(eenhedennamen, function(index, entry) {
obj[entry] = value[index];
});
```
This works because in JavaScript, you can access properties using either dot notation and a property name literal (`obj.foo = "bar"`), or *bracketed* notation with a *string* property name (`obj["foo"] = "bar"`). In the latter case, the string can be the result of any expression. So in the above, we're using `entry` as the property name, which will be each name in `eenhedennamen`. Then of course, we get the corresponding value from `value` using the `index`.
|
You can use [`Array.prototype.reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce)
Try this:
```
var eenhedennamen = ['unit1', 'unit2', 'unit3'];
var value = [1,2,3];
var arr3 = eenhedennamen.reduce(function(obj, val, i) {
obj[val] = value[i];
return obj;
}, {});
console.log(JSON.stringify(arr3));
```
[Try in fiddle](http://jsfiddle.net/y3Kn9/)
[Reference](https://stackoverflow.com/questions/11487123/combine-two-arrays-in-javascript)
|
33,106,871
|
I have a batch script runs python script continuously in a loop.
```
:start
python log_capture.py > log.txt
goto start
```
I want to print the output of each iteration in a .txt file. I am using following command get output from log\_capture.py to a log.txt file.
```
python log_capture.py >log.txt
```
But in the next loop, the logs from previous iteration is overwritten. How can I prevent log.txt file being overwritten or lets say save output from each iteration in different log.txt file
|
2015/10/13
|
[
"https://Stackoverflow.com/questions/33106871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5138377/"
] |
I have used this service in the past and I noticed today that text messages sent were not received. Looking into this a bit further it seems something happened due to folks using this service to spam... and it's not working at present. Not sure what the future holds...
See: [issue listed on textbelt](https://github.com/typpo/textbelt/issues/76)
Looking for a solution still....
Joel Parke
|
2-563-567-890 doesn't look like a valid US phone number, so I would double-check that. There is also an international endpoint, `/intl`, but it tends to be less reliable.
|
20,307,590
|
I am trying to make an HTTP POST request using javascript and connecting it to an onclick event.
For example, if someone clicks on a button then make a HTTP POST request to `http://www.example.com/?test=test1&test2=test2`. It just needs to hit the url and can close the connection.
I've messed around in python and got this to work.
```
import urllib2
def hitURL():
urllib2.urlopen("http://www.example.com/?test=test1&test2=test2").close
hitURL()
```
I have read about some ways to make HTTP requests using JavaScript in this thread [JavaScript post request like a form submit](https://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit), but think it's overkill for what I need to do.
Is it possible to just say something like this:
```
<button onclick=POST(http://www.example.com/?test=test1&test2=test2)>hello</button>
Or build it in to an event listener.
```
I know that is not anything real but I am just looking for a simple solution that non-technical people can use, follow directions, and implement.
I honestly doubt there is something that simple out there but still any recommendations would be appreciated.
|
2013/12/01
|
[
"https://Stackoverflow.com/questions/20307590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2159019/"
] |
You need to use `XMLHttpRequest` (see [MDN](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)).
```
var xhr = new XMLHttpRequest();
xhr.open("POST", url, false);
xhr.onload = // something
document.getElementById("your_button's_ID").addEventListener("click",
function() {xhr.send(data)},
false
);
```
|
If you can include the JQuery library, then I'd suggest you look in to the jQuery .ajax() method (<http://api.jquery.com/jQuery.ajax/>):
```
$.ajax("http://www.example.com/", {
type: 'POST',
data: {
test: 'test1',
test2: 'test2'
}
})
```
|
17,793,742
|
I want to profile python code on Widnows 7. I would like to use something a little more user friendly than the raw dump of cProfile. In that search I found the GUI RunSnakeRun, but I cannot find a way to download RunSnakeRun on Windows. Is it possible to use RunSnakeRun on windows or what other tools could I use?
**Edit:** I have installed RunSnakeRun now. That's progress, thanks guys. How do you run it without a linux command line?
**Edit 2:** I am using this tutorial <http://sullivanmatas.wordpress.com/2013/02/03/profiling-python-scripts-with-runsnakerun/> but I hang up at the last line with "python: can't open file 'runsnake.py': [Errno 2] No such file or directory "
|
2013/07/22
|
[
"https://Stackoverflow.com/questions/17793742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/417902/"
] |
The standard solution is to use cProfile (which is in the standard library) and then open the profiles in RunSnakeRun:
<http://www.vrplumber.com/programming/runsnakerun/>
cProfile, however only profiles at the per-functions level. If you want line by line profiling try line profiler:
<https://github.com/rkern/line_profiler>
|
I installed runsnake following these [installation instructions](http://www.vrplumber.com/programming/runsnakerun/).
The step `python runsnake.py profile.pfl` failed because the installation step (`easy_install SquareMap RunSnakeRun`) did not create a file `runsnake.py`.
For me (on Ubuntu), the installation step created an executable at `/usr/local/bin/runsnake`. I figured this out by reading the console output from the installation step. It may be in a different place on Windows, but it should be printed in the output of `easy_install`. To read a profile file, I can execute `/usr/local/bin/runsnake profile.pfl`.
|
17,793,742
|
I want to profile python code on Widnows 7. I would like to use something a little more user friendly than the raw dump of cProfile. In that search I found the GUI RunSnakeRun, but I cannot find a way to download RunSnakeRun on Windows. Is it possible to use RunSnakeRun on windows or what other tools could I use?
**Edit:** I have installed RunSnakeRun now. That's progress, thanks guys. How do you run it without a linux command line?
**Edit 2:** I am using this tutorial <http://sullivanmatas.wordpress.com/2013/02/03/profiling-python-scripts-with-runsnakerun/> but I hang up at the last line with "python: can't open file 'runsnake.py': [Errno 2] No such file or directory "
|
2013/07/22
|
[
"https://Stackoverflow.com/questions/17793742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/417902/"
] |
The standard solution is to use cProfile (which is in the standard library) and then open the profiles in RunSnakeRun:
<http://www.vrplumber.com/programming/runsnakerun/>
cProfile, however only profiles at the per-functions level. If you want line by line profiling try line profiler:
<https://github.com/rkern/line_profiler>
|
There's also [py-spy](https://github.com/benfred/py-spy), written in Rust, safe to use even in production, without modifying any code.
Works on Windows, to install run `pip install py-spy`.
From there you can run `py-spy record -o profile.svg -- python myprogram.py` which produces nice flame graphs.
|
72,452,208
|
I'm trying to make a publisher for a Ublox GPS sensor, but I'm getting this ROS error:
>
> ubuntu@fieldrover:~/field-rover-gps/gps/gps\_pkg$ cd
> ~/field-rover-gps/gps/gps\_pkg/ && colcon build && . install/setup.bash
> && ros2 run gps\_pkg gps
>
>
> Starting >>> gps\_pkg Finished <<< gps\_pkg [2.98s]
>
>
> Summary: 1 package finished [3.49s] Traceback (most recent call last):
> File
> "/opt/ros/galactic/lib/python3.8/site-packages/rosidl\_generator\_py/import\_type\_support\_impl.py",
> line 46, in import\_type\_support
> return importlib.import\_module(module\_name, package=pkg\_name) File "/usr/lib/python3.8/importlib/**init**.py", line 127, in
> import\_module
> return \_bootstrap.\_gcd\_import(name[level:], package, level) File "", line 1014, in \_gcd\_import File
> "", line 991, in \_find\_and\_load File
> "", line 975, in \_find\_and\_load\_unlocked
> File "", line 657, in \_load\_unlocked
>
> File "", line 556, in module\_from\_spec
>
> File "", line 1166, in
> create\_module File "", line 219, in
> \_call\_with\_frames\_removed ImportError: /opt/ros/galactic/lib/libgeometry\_msgs\_\_rosidl\_generator\_c.so:
> undefined symbol: std\_msgs\_\_msg\_\_Header\_\_copy
>
>
> During handling of the above exception, another exception occurred:
>
>
> Traceback (most recent call last): File
> "/home/ubuntu/field-rover-gps/gps/gps\_pkg/install/gps\_pkg/lib/gps\_pkg/gps",
> line 33, in
> sys.exit(load\_entry\_point('gps-pkg==0.0.0', 'console\_scripts', 'gps')()) File
> "/home/ubuntu/field-rover-gps/gps/gps\_pkg/install/gps\_pkg/lib/python3.8/site-packages/gps\_pkg/gps.py",
> line 49, in main
> gps\_node = GpsNode() File "/home/ubuntu/field-rover-gps/gps/gps\_pkg/install/gps\_pkg/lib/python3.8/site-packages/gps\_pkg/gps.py",
> line 17, in **init**
> self.publisher\_ = self.create\_publisher(NavSatFix, 'gps/fix', 10) File "/opt/ros/galactic/lib/python3.8/site-packages/rclpy/node.py",
> line 1282, in create\_publisher
> check\_is\_valid\_msg\_type(msg\_type) File "/opt/ros/galactic/lib/python3.8/site-packages/rclpy/type\_support.py",
> line 35, in check\_is\_valid\_msg\_type
> check\_for\_type\_support(msg\_type) File "/opt/ros/galactic/lib/python3.8/site-packages/rclpy/type\_support.py",
> line 29, in check\_for\_type\_support
> msg\_or\_srv\_type.**class**.**import\_type\_support**() File "/opt/ros/galactic/lib/python3.8/site-packages/sensor\_msgs/msg/\_nav\_sat\_fix.py",
> line 34, in **import\_type\_support**
> module = import\_type\_support('sensor\_msgs') File "/opt/ros/galactic/lib/python3.8/site-packages/rosidl\_generator\_py/import\_type\_support\_impl.py",
> line 48, in import\_type\_support
> raise UnsupportedTypeSupport(pkg\_name) rosidl\_generator\_py.import\_type\_support\_impl.UnsupportedTypeSupport:
> Could not import 'rosidl\_typesupport\_c' for package 'sensor\_msgs'
>
>
>
It seems to have an issue with NavSatFix. I've tested other sensor\_msgs types like Image in the same package, and that works fine. Here's the code I tried running.
```
import rclpy
import os
from rclpy.node import Node
from sensor_msgs.msg import NavSatFix
from sensor_msgs.msg import NavSatStatus
from std_msgs.msg import Header
import serial
from ublox_gps import UbloxGps
port = serial.Serial('/dev/ttyACM0', baudrate=38400, timeout=1)
gps = UbloxGps(port)
class GpsNode(Node):
def __init__(self):
super().__init__('gps_node')
self.publisher_ = self.create_publisher(NavSatFix, 'gps/fix', 10)
timer_period = 0.5 # seconds
self.timer = self.create_timer(timer_period, self.timer_callback)
def timer_callback(self):
msg = NavSatFix()
msg.header = Header()
msg.header.stamp = self.get_clock().now().to_msg()
msg.header.frame_id = "gps"
msg.status.status = NavSatStatus.STATUS_FIX
msg.status.service = NavSatStatus.SERVICE_GPS
geo = gps.geo_coords()
# Position in degrees.
msg.latitude = geo.lat
msg.longitude = geo.lon
# Altitude in metres.
#msg.altitude = 1.15
msg.position_covariance[0] = 0
msg.position_covariance[4] = 0
msg.position_covariance[8] = 0
msg.position_covariance_type = NavSatFix.COVARIANCE_TYPE_DIAGONAL_KNOWN
self.publisher_.publish(msg)
self.best_pos_a = None
def main(args=None):
rclpy.init(args=args)
gps_node = GpsNode()
rclpy.spin(gps_node)
# Destroy the node explicitly
# (optional - otherwise it will be done automatically
# when the garbage collector destroys the node object)
gps_node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
```
|
2022/05/31
|
[
"https://Stackoverflow.com/questions/72452208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12497264/"
] |
As it already has been pointed outed both in the comments and the answer by *@AbhinavMathur*, in order to improve performance you need to implement [*Doubly linked list*](https://en.wikipedia.org/wiki/Doubly_linked_list) data structure.
Note that it's mandatory to create your *own implementation* that will maintain a reference to the *current node*. Attempt to utilize an implementation built-in in the JDK in place of the `items` array will not buy you anything because the advantage of the fast deletion will be nullified by the cost of iteration (in order to reach the element at position `n`, `LinkedList` needs to crawl through the `n` elements starting from the *head*, and this operation has a liner time complexity).
Methods `left()`, `right()` and `position()` will have the following outcome:
* `left()` - in case when the *previous* node (denoted as `prev` in the code) associated with `current` is not `null`, and in tern its *previous node* exists, the *current node* will be dereferenced (i.e. next and previous nodes associated with the `current` node will be linked with each other), and the variable `current` would be assigned to the `prev` of the *previous node*, i.e. `current.prev.prev`. Time complexity **O(1)**.
* `right()` - in case when the *next* node (denoted as `next` in the code) associated with `current` is not `null`, and in tern its *next node* exists, the *current node* will be dereferenced in a way that has been described above, and the variable `current` would be assigned to the `next` of the *next node*, i.e. `current.next.next`. Time complexity **O(1)**.
* `position()` - will return a value of the `current` node. Time complexity **O(1)**.
That's how it might look like:
```
public class MyClass {
private Node current; // a replacement for both position and items fields
public MyClass(int n, int position) {
Node current = new Node(0, null, null); // initialing the head node
if (position == 0) {
this.current = current;
}
for (int i = 1; i < n; i++) { // initialing the rest past of the linked list
Node nextNode = new Node(i, current, null);
current.setNext(nextNode);
current = nextNode;
if (position == i) {
this.current = current;
}
}
}
public void left() { // removes the current node and sets the current to the node 2 position to the left (`prev` of the `prev` node)
if (current.prev == null || current.prev.prev == null) {
return;
}
Node prev = current.prev;
Node next = current.next;
prev.setNext(next);
next.setPrev(prev);
this.current = prev.prev;
}
public void right() { // removes the current node and sets the current to the node 2 position to the right (`next` of the `next` node)
if (current.next == null || current.next.next == null) {
return;
}
Node prev = current.prev;
Node next = current.next;
prev.setNext(next);
next.setPrev(prev);
this.current = next.next;
}
public int position() {
return current.getValue();
}
public static class Node {
private int value;
private Node prev;
private Node next;
public Node(int value, Node prev, Node next) {
this.value = value;
this.prev = prev;
this.next = next;
}
// getters and setters
}
}
```
[*A link to Online Demo*](https://www.jdoodle.com/ia/rFs)
|
Using an array, you're setting the "removed" elements as `-1`; repeatedly skipping them in each traversal causes the performance penalty.
Instead of an array, use a [doubly linked list](https://www.geeksforgeeks.org/doubly-linked-list/). Each removal can be easily done in `O(1)` time, and each left/right operation would only require shifting the current pointer by 2 nodes.
|
52,787,147
|
I want to use CTR mode in DES algorithm in python by using PyCryptodome package. My code presented at the end of this post. However I got this error: "TypeError: Impossible to create a safe nonce for short block sizes". It is worth to mention that, this code work well for AES algorithm but it does not work for DES, DES3 , Blowfish and etc (with 64 block size). To my knowledge CTR mode can be applied in the 64 block cipher algorithms.
```
from Crypto.Cipher import DES
from Crypto.Random import get_random_bytes
data = b'My plain text'
key = get_random_bytes(8)
cipher = DES.new(key, DES.MODE_CTR)
ct_bytes = cipher.encrypt(data)
nonce = cipher.nonce
cipher = DES.new(key, DES.MODE_CTR, nonce=nonce)
pt = cipher.decrypt(ct_bytes)
print("The message was: ", pt)
```
Thanks alot.
|
2018/10/12
|
[
"https://Stackoverflow.com/questions/52787147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9982452/"
] |
The library [defines the nonce](https://www.pycryptodome.org/en/latest/src/cipher/classic.html#ctr-mode)
as that part of the counter block that is not incremented.
Since the block is only 64 bits long, it is hard to securely define how long that nonce should be,
given the danger of wraparound (if you encrypt a lot of blocks) or nonce reuse (if you generate the nonce randomly).
You can instead decide that the nonce is not present, the counter takes the full 64 bits and a random initial value.
```
iv = get_random_bytes(8)
cipher = DES.new(key, nonce=b'', initial_value=iv)
```
Finally, I guess that this is only an exercise.
DES is a very weak cipher, with a key length of only 56 bits and a block size of only 64 bits.
Use AES instead.
|
```
bs = DES.block_size
plen = bs - len(plaintext) % bs
padding = [plen] * plen
padding = pack('b' * plen, *padding)
key = get_random_bytes(8)
nonce = Random.get_random_bytes(4)
ctr = Counter.new(32, prefix=nonce)
cipher = DES.new(key, DES.MODE_CTR,counter=ctr)
ciphertext = cipher.encrypt(plaintext+padding)
```
|
52,416,852
|
I am trying to use your project named dask-spark proposed by Matthew Rocklin.
When adding the dask-spark into my project, I have a problem: Waiting for workers as shown in the following figure.
Here, I run two worker nodes (dask) as dask-worker tcp://ubuntu8:8786 and tcp://ubuntu9:8786 and run two worker nodes (spark) over a standalone model, as worker-20180918112328-ubuntu8-45764 and worker-20180918112413-ubuntu9-41972
[Waiting for workers](https://i.stack.imgur.com/xaPOb.jpg)
My python code is as:
```
from tpot import TPOTClassifier
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.externals import joblib
from dask.distributed import Client
import distributed.joblib
from sklearn.externals.joblib import parallel_backend
from dask_spark import spark_to_dask
from pyspark import SparkConf, SparkContext
from dask_spark import dask_to_spark
if __name__ == '__main__':
sc = SparkContext()
#connect to the cluster
client = spark_to_dask(sc)
digits = load_digits()
X_train, X_test, y_train, y_test = train_test_split(
digits.data,
digits.target,
train_size=0.75,
test_size=0.25,
)
tpot = TPOTClassifier(
generations=2,
population_size=10,
cv=2,
n_jobs=-1,
random_state=0,
verbosity=0
)
with joblib.parallel_backend('dask.distributed', scheduler_host=' ubuntu8:8786'):
tpot.fit(X_train, y_train)
print(tpot.score(X_test, y_test))
```
I will highly appreciate it if you can help me to solve this question.
|
2018/09/20
|
[
"https://Stackoverflow.com/questions/52416852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have revised the program in core.py, as:
```
def spark_to_dask(sc, loop=None):
""" Launch a Dask cluster from a Spark Context
"""
cluster = LocalCluster(n_workers=None, loop=loop, threads_per_worker=None)
rdd = sc.parallelize(range(1000))
address = cluster.scheduler.address
```
Following which, running my test case over Spark with Standalone or Mesos was successful.
|
As noted in the README of the project, dask-spark is not mature. It was a weekend project and I do not recommend its use.
Instead, I recommend launching Dask directly using one of the mechanisms described here: <http://dask.pydata.org/en/latest/setup.html>
If you have to use Mesos then I'm not sure I'll be of much help, but there is a package [daskathon](https://github.com/daskos/daskathon) that runs on top of Marathon that may interest you.
|
59,697,566
|
My input is a list, say `l`
It can either contain 4 or 5 elements. I want to assign it to 5 variables , say `a`, `b`, `c`, `d` and `e`.
If the list has only 4 elements then the third variable (`c`) should be `None`.
If python had an increment (++) operator I could do something like this.
```
l = [4 or 5 string inputs]
i = -1
a = l[i++]
b = l[i++]
c = None
if len(l) > 4:
c = l[i++]
d = l[i++]
e = l[i++]
```
I can't seem to find an elegant way to do this apart from writing `i+=1` before each assignment. Is there a simpler pythonic way to do this?
|
2020/01/11
|
[
"https://Stackoverflow.com/questions/59697566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11316253/"
] |
You're trying to use a C solution because you're unfamiliar with Python's tools. Using unpacking is much cleaner than trying to emulate `++`:
```
a, b, *c, d, e = l
c = c[0] if c else None
```
The `*c` target receives a list of all elements of `l` that weren't unpacked into the other targets. If this list is nonempty, then `c` is considered true when coerced to boolean, so `c[0] if c else None` takes `c[0]` if there is a `c[0]` and `None` otherwise.
|
I can't see that you really need to be incrementing at all since you have fixed positions for each variable subject to your c condition.
```
l = [4 or 5 string inputs]
a = l[0]
b = l[1]
if len(l) > 4:
c = l[2]
d = l[3]
e = l[4]
else:
c = None
d = l[2]
e = l[3]
```
|
59,697,566
|
My input is a list, say `l`
It can either contain 4 or 5 elements. I want to assign it to 5 variables , say `a`, `b`, `c`, `d` and `e`.
If the list has only 4 elements then the third variable (`c`) should be `None`.
If python had an increment (++) operator I could do something like this.
```
l = [4 or 5 string inputs]
i = -1
a = l[i++]
b = l[i++]
c = None
if len(l) > 4:
c = l[i++]
d = l[i++]
e = l[i++]
```
I can't seem to find an elegant way to do this apart from writing `i+=1` before each assignment. Is there a simpler pythonic way to do this?
|
2020/01/11
|
[
"https://Stackoverflow.com/questions/59697566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11316253/"
] |
In the specific case of this question, [list unpacking is the best solution](https://stackoverflow.com/a/59697622/1399279).
For other users needing to emulate `++` for other purposes (typically the desire to increment without an explicit `i += 1` statement), they can use [`itertools.count`](https://docs.python.org/3/library/itertools.html#itertools.count). This will return an iterator that will increment indefinitely each time it is passed to `next()`.
```py
import itertools
i = itertools.count(0) # start counting at 0
print(next(i)) # 0
print(next(i)) # 1
# ...and so on...
```
|
I can't see that you really need to be incrementing at all since you have fixed positions for each variable subject to your c condition.
```
l = [4 or 5 string inputs]
a = l[0]
b = l[1]
if len(l) > 4:
c = l[2]
d = l[3]
e = l[4]
else:
c = None
d = l[2]
e = l[3]
```
|
59,697,566
|
My input is a list, say `l`
It can either contain 4 or 5 elements. I want to assign it to 5 variables , say `a`, `b`, `c`, `d` and `e`.
If the list has only 4 elements then the third variable (`c`) should be `None`.
If python had an increment (++) operator I could do something like this.
```
l = [4 or 5 string inputs]
i = -1
a = l[i++]
b = l[i++]
c = None
if len(l) > 4:
c = l[i++]
d = l[i++]
e = l[i++]
```
I can't seem to find an elegant way to do this apart from writing `i+=1` before each assignment. Is there a simpler pythonic way to do this?
|
2020/01/11
|
[
"https://Stackoverflow.com/questions/59697566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11316253/"
] |
You're trying to use a C solution because you're unfamiliar with Python's tools. Using unpacking is much cleaner than trying to emulate `++`:
```
a, b, *c, d, e = l
c = c[0] if c else None
```
The `*c` target receives a list of all elements of `l` that weren't unpacked into the other targets. If this list is nonempty, then `c` is considered true when coerced to boolean, so `c[0] if c else None` takes `c[0]` if there is a `c[0]` and `None` otherwise.
|
There is no ++ operator in Python. A similar question to this was answered here [Behaviour of increment and decrement operators in Python](https://stackoverflow.com/questions/1485841/behaviour-of-increment-and-decrement-operators-in-python)
|
59,697,566
|
My input is a list, say `l`
It can either contain 4 or 5 elements. I want to assign it to 5 variables , say `a`, `b`, `c`, `d` and `e`.
If the list has only 4 elements then the third variable (`c`) should be `None`.
If python had an increment (++) operator I could do something like this.
```
l = [4 or 5 string inputs]
i = -1
a = l[i++]
b = l[i++]
c = None
if len(l) > 4:
c = l[i++]
d = l[i++]
e = l[i++]
```
I can't seem to find an elegant way to do this apart from writing `i+=1` before each assignment. Is there a simpler pythonic way to do this?
|
2020/01/11
|
[
"https://Stackoverflow.com/questions/59697566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11316253/"
] |
You're trying to use a C solution because you're unfamiliar with Python's tools. Using unpacking is much cleaner than trying to emulate `++`:
```
a, b, *c, d, e = l
c = c[0] if c else None
```
The `*c` target receives a list of all elements of `l` that weren't unpacked into the other targets. If this list is nonempty, then `c` is considered true when coerced to boolean, so `c[0] if c else None` takes `c[0]` if there is a `c[0]` and `None` otherwise.
|
In the specific case of this question, [list unpacking is the best solution](https://stackoverflow.com/a/59697622/1399279).
For other users needing to emulate `++` for other purposes (typically the desire to increment without an explicit `i += 1` statement), they can use [`itertools.count`](https://docs.python.org/3/library/itertools.html#itertools.count). This will return an iterator that will increment indefinitely each time it is passed to `next()`.
```py
import itertools
i = itertools.count(0) # start counting at 0
print(next(i)) # 0
print(next(i)) # 1
# ...and so on...
```
|
59,697,566
|
My input is a list, say `l`
It can either contain 4 or 5 elements. I want to assign it to 5 variables , say `a`, `b`, `c`, `d` and `e`.
If the list has only 4 elements then the third variable (`c`) should be `None`.
If python had an increment (++) operator I could do something like this.
```
l = [4 or 5 string inputs]
i = -1
a = l[i++]
b = l[i++]
c = None
if len(l) > 4:
c = l[i++]
d = l[i++]
e = l[i++]
```
I can't seem to find an elegant way to do this apart from writing `i+=1` before each assignment. Is there a simpler pythonic way to do this?
|
2020/01/11
|
[
"https://Stackoverflow.com/questions/59697566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11316253/"
] |
In the specific case of this question, [list unpacking is the best solution](https://stackoverflow.com/a/59697622/1399279).
For other users needing to emulate `++` for other purposes (typically the desire to increment without an explicit `i += 1` statement), they can use [`itertools.count`](https://docs.python.org/3/library/itertools.html#itertools.count). This will return an iterator that will increment indefinitely each time it is passed to `next()`.
```py
import itertools
i = itertools.count(0) # start counting at 0
print(next(i)) # 0
print(next(i)) # 1
# ...and so on...
```
|
There is no ++ operator in Python. A similar question to this was answered here [Behaviour of increment and decrement operators in Python](https://stackoverflow.com/questions/1485841/behaviour-of-increment-and-decrement-operators-in-python)
|
66,593,382
|
To run `pytest` within GitHub Actions, I have to pass some `secrets` for Python running environ.
e.g.,
```
- name: Test env vars for python
run: python -c 'import os;print(os.environ)'
env:
TEST_ENV: 'hello world'
TEST_SECRET: ${{ secrets.MY_TOKEN }}
```
However, the output is as follows,
```
environ({
'TEST_ENV': 'hello world',
'TEST_SECRET':'',
...})
```
It seems not working due to [GitHub's redaction](https://docs.github.com/en/actions/learn-github-actions/security-hardening-for-github-actions#using-secrets).
Based on @raspiduino 's answer, I did more explore on both options to import env vars.
```
name: python
on: push
jobs:
test_env:
runs-on: ubuntu-latest
steps:
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: 3.8
- name: Test env vars for python
run: python -c 'import os;print(os.environ)'
env:
ENV_SECRET: ${{ secrets.ENV_SECRET }}
REPO_SECRET: ${{ secrets.REPO_SECRET }}
- name: Test inline env vars for python
run: ENV_SECRET=${{ secrets.ENV_SECRET }} REPO_SECRET=${{ secrets.REPO_SECRET }} python -c 'import os;print(os.environ)'
```
Basically, both steps are in same outputs. The `REPO_SECRET` can be passed thru but not the `ENV_SECRET`.
[](https://i.stack.imgur.com/Q9CbS.png)
Outputs
[](https://i.stack.imgur.com/gjLYJ.png)
|
2021/03/12
|
[
"https://Stackoverflow.com/questions/66593382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/482899/"
] |
There are three types of secrets within GitHub Actions.
1. Organization secrets
2. Repository secrets
3. Environment secrets
To access Environment secrets, you have to [referencing an environment](https://docs.github.com/en/actions/reference/environments#referencing-an-environment) in your job. (Thanks to @riQQ)
[](https://i.stack.imgur.com/Q9CbS.png)
```
name: python
on: push
jobs:
test_env:
environment: TEST_SECRET
runs-on: ubuntu-latest
steps:
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: 3.8
- name: Test env vars for python
run: python -c 'import os;print(os.environ)'
env:
ENV_SECRET: ${{ secrets.ENV_SECRET }}
REPO_SECRET: ${{ secrets.REPO_SECRET }}
```
|
You try the things below:
```
- name: Test env vars for python
run: TEST_SECRET=${{ secrets.MY_TOKEN }} python -c 'import os;print(os.environ['TEST_SECRET'])
```
This will pass `${{ secrets.MY_TOKEN }}` directly as an environment variable to the python process and not share with other processes. Then you can use `os.environ['TEST_SECRET']` to get it.
I have done this [here](https://github.com/raspiduino/raspiduino/blob/main/.github/workflows/minesweeper.yml) and [here](https://github.com/raspiduino/raspiduino/blob/main/minesweeper.py)
|
12,763,015
|
Sorry if my title is not correct. Below is the explanation of what i'm looking for.
I've coded a small GUI game (let say a snake game) in python, and I want it to be run on Linux machine. I can run this program by just run command "python snake.py" in the terminal.
However, I want to combine all my .py files into one file, and when I click on this file, it just run my game. I don't want to go to shell and type "python snake.py". I means something like manifest .jar in java.
Could any one help me please? If my explanation is not good enough, please let me know. I'll give some more explanation.
|
2012/10/06
|
[
"https://Stackoverflow.com/questions/12763015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1058861/"
] |
You can use [Freeze](http://wiki.python.org/moin/Freeze) for Unix, or [py2exe](http://wiki.python.org/moin/Py2Exe) for Windows.
[cx\_freeze](http://cx-freeze.sourceforge.net/), [PyInstaller](http://www.pyinstaller.org/), [bbfreeze](http://www.jroller.com/alessiopace/entry/python_standalone_executables_with_bbfreeze) and [py2app](http://svn.pythonmac.org/py2app/py2app/trunk/doc/index.html) - which I have never tried - are also available for various platforms, so there are many options.
|
If you only want it to run on a Linux machine, using Python eggs is the simplest way.
python snake.egg will try to execute the **main**.py inside the egg.
Python eggs are meant to be packages, and basically is a zip file with metadata files included.
|
57,035,263
|
I'm trying RSA encrypt text with JSEncrypt(javascript) and decrypt with python crypto (python3.7). Most of the time, it works. But sometimes, python cannot decrypt.
```js
const encrypt = new JSEncrypt()
encrypt.setPublicKey(publicKey)
encrypt.encrypt(data)
```
```py
from base64 import b64decode
from Crypto.Cipher import PKCS1_v1_5 as Cipher_PKCS1_v1_5
from Crypto.PublicKey import RSA
crypt_text = "J9I/IdsSGZqrQ5XBTlDrze5+U3otrGEGn7J7f330/tbIpdPNwu9k5gCh35HJHuRF6tXhbOD9XbHS6dGXwRdj0KNSWa43tDQMyGp/ZSewCd4wWkqIx83YzDKnYTVc9zWYbg2iYrmR03AqtWMysl8vZDUSmQn7gNdYEJGxSUzVng=="
private_key = "MIICXQIBAAKBgQClFImg7N+5ziGtjrMDwN7frootgwrLUmbE9YFBtecnjchCRjAn1wqq69XiWynEv0q3/U91N5g0nJxeMuolSM8cwdQbT3KZFwQF6vreSzDNhfEYOsFVZknILLPiJpUYm5w3Gi34UeM60iHGH9EUnmQeVwKSG0WF2nK2SCU6EyfoJwIDAQABAoGAHHk2Y/N3g2zykiUS64rQ5nQMkV0Q95D2+PH/oX3mqQPjjsrcc4K77E9RTQG8aps0IBgpJGa6chixP+44RMYSMvRIK0wqgX7s6AFIkFIIM+v+bP9pd3kKaVKTcNIjfnKJZokgAnU0QVdf0zeSNElZC+2qe1FbblsSQ6sqaFmHaMECQQC4oZO+w0q2smQh7VZbM0fSIbdZEimX/4y9KN4VYzPQZkDzQcEQX1Al2YAP8eqlzB4r7QcpRJgvUQDODhzMUtP9AkEA5ORFhPVK5slpqYP7pj2F+D2xAoL9XkgBKmhVppD/Sje/vg4yEKCTQ7fRlIzSvtwAvbDJi3ytYqXQWVdaD/Eb8wJAdYC3k8ecTCu6WHFA7Wf0hIJausA5YngMLPLObFQnTLFXErm9UlsmmgATZZJz4LLIXPJMBXKXXD20Qm9u2oa4TQJBAKxBopP6KiFfSNabDkLAoFb+znzuaZGPrNjmZjcRfh6zr+hvNHxQ7CMVbnNWO7AJT8FyD2ubK71GvnLOC2hd8sMCQQCT70B5EpFqULt7RBvCa7wwJsmwaMZLhBcfNmbry/J9SZG3FVrfYf15r0SBRug7mT2gRmH+tvt/mFafjG50VCnw"
decode_data = b64decode(crypt_text)
other_private_key = RSA.importKey(b64decode(private_key))
cipher = Cipher_PKCS1_v1_5.new(other_private_key)
decrypt_text = cipher.decrypt(decode_data, None).decode()
print(decrypt_text)
```
this is a example text that python can't decrypt, but js can decrypt it well.
python throws the error:
```
File "/usr/local/lib/python3.7/site-packages/Crypto/Cipher/PKCS1_v1_5.py", line 165, in decrypt
raise ValueError("Ciphertext with incorrect length.")
ValueError: Ciphertext with incorrect length.
```
|
2019/07/15
|
[
"https://Stackoverflow.com/questions/57035263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11784926/"
] |
If the ciphertext is Base64-decoded, the reason becomes clearer: The ciphertext doesn't have the length of the modulus (128 byte), but only 127 byte, i.e. it isn't padded to the length of the modulus with leading `0x00` values. This ciphertext is invalid (see [RFC8017](https://www.rfc-editor.org/rfc/rfc8017#section-7.2.2), step 1) and the decryption in the Python code fails with the error message *Ciphertext with incorrect length*. In contrast, the decryption in the JavaScript code works, i.e. `JSEncrypt#decrypt` obviously adjusts the ciphertext to the length of the modulus by stealthily padding with `0x00` values. If the ciphertext was created with `JSEncrypt#encrypt`, this method doesn't seem to work properly.
In detail: The modulus can be determined with:
```
openssl rsa -modulus -noout -in <path to private key>
```
and is (as hex-string):
```
A51489A0ECDFB9CE21AD8EB303C0DEDFAE8A2D830ACB5266C4F58141B5E7278DC842463027D70AAAEBD5E25B29C4BF4AB7FD4F753798349C9C5E32EA2548CF1CC1D41B4F7299170405EAFADE4B30CD85F1183AC1556649C82CB3E22695189B9C371A2DF851E33AD221C61FD1149E641E5702921B4585DA72B648253A1327E827
```
The length is 128 byte. The Base64-decoded ciphertext is (as hex-string):
```
27d23f21db12199aab4395c14e50ebcdee7e537a2dac61069fb27b7f7df4fed6c8a5d3cdc2ef64e600a1df91c91ee445ead5e16ce0fd5db1d2e9d197c11763d0a35259ae37b4340cc86a7f6527b009de305a4a88c7cdd8cc32a761355cf735986e0da262b991d3702ab56332b25f2f6435129909fb80d7581091b1494cd59e
```
The length is 127 byte. If the ciphertext is padded manually to the length of the modulus with `0x00`-values, it can also be decrypted in the Python code:
```
0027d23f21db12199aab4395c14e50ebcdee7e537a2dac61069fb27b7f7df4fed6c8a5d3cdc2ef64e600a1df91c91ee445ead5e16ce0fd5db1d2e9d197c11763d0a35259ae37b4340cc86a7f6527b009de305a4a88c7cdd8cc32a761355cf735986e0da262b991d3702ab56332b25f2f6435129909fb80d7581091b1494cd59e
```
The decrypted data are:
```
Mzg4MDE1NDU4MTI1ODI0OA==NDQyODYwNjI1MjU4NTM2MA==
```
which are two valid Base64-encoded strings.
|
Thanks to Topaco, it solved.
```
from base64 import b64decode, b16decode
from Crypto.Cipher import PKCS1_v1_5 as Cipher_PKCS1_v1_5
from Crypto.PublicKey import RSA
crypt_text = \
"R247QGAFEeSW1wwXQuNf/cm/K/tnW5xwXLb5MuHW6/Fr8SRklM0n6Rmj07TgFwApeN72j/avXAvpoR70U92ehOJsDnnZguYN4u2bMXHDyTNmAXuJw9xPm59bSGcvgRm1X+V0Zq1FLzGEsPG6tOYEIX+wnIuH3P7QMd02XJfj0w0="
private_key = "MIICXQIBAAKBgQClFImg7N+5ziGtjrMDwN7frootgwrLUmbE9YFBtecnjchCRjAn1wqq69XiWynEv0q3/U91N5g0nJxeMuolSM8cwdQbT3KZFwQF6vreSzDNhfEYOsFVZknILLPiJpUYm5w3Gi34UeM60iHGH9EUnmQeVwKSG0WF2nK2SCU6EyfoJwIDAQABAoGAHHk2Y/N3g2zykiUS64rQ5nQMkV0Q95D2+PH/oX3mqQPjjsrcc4K77E9RTQG8aps0IBgpJGa6chixP+44RMYSMvRIK0wqgX7s6AFIkFIIM+v+bP9pd3kKaVKTcNIjfnKJZokgAnU0QVdf0zeSNElZC+2qe1FbblsSQ6sqaFmHaMECQQC4oZO+w0q2smQh7VZbM0fSIbdZEimX/4y9KN4VYzPQZkDzQcEQX1Al2YAP8eqlzB4r7QcpRJgvUQDODhzMUtP9AkEA5ORFhPVK5slpqYP7pj2F+D2xAoL9XkgBKmhVppD/Sje/vg4yEKCTQ7fRlIzSvtwAvbDJi3ytYqXQWVdaD/Eb8wJAdYC3k8ecTCu6WHFA7Wf0hIJausA5YngMLPLObFQnTLFXErm9UlsmmgATZZJz4LLIXPJMBXKXXD20Qm9u2oa4TQJBAKxBopP6KiFfSNabDkLAoFb+znzuaZGPrNjmZjcRfh6zr+hvNHxQ7CMVbnNWO7AJT8FyD2ubK71GvnLOC2hd8sMCQQCT70B5EpFqULt7RBvCa7wwJsmwaMZLhBcfNmbry/J9SZG3FVrfYf15r0SBRug7mT2gRmH+tvt/mFafjG50VCnw"
decode_data = b64decode(crypt_text)
if len(decode_data) == 127:
hex_fixed = '00' + decode_data.hex()
decode_data = b16decode(hex_fixed.upper())
other_private_key = RSA.importKey(b64decode(private_key))
cipher = Cipher_PKCS1_v1_5.new(other_private_key)
decrypt_text = cipher.decrypt(decode_data, None).decode()
print(decrypt_text)
```
|
54,813,438
|
I am looking to extract content from [a page](https://app.updateimpact.com/treeof/org.json4s/json4s-native_2.11/3.5.2) that is requires a list node to be selected. I have retrieve the page html using python and Selenium. Passing the page source to BS4 I can parse out the content that I am looking for using
```
open_li = soup.select('div#tree ul.jstree-container-ul li')
```
Each list item returned has an
```
aria-expanded = "false" and class="jstree-node jstree-closed"
```
Looking at inspect element the content is called when these variables are set to
```
aria-expanded = "true" and class="jstree-node jstree-open"
```
I have tried using .click method on the content
```
driver.find_element_by_id('tree').click()
```
But that only changes other content on the page. I think the list nodes themselves have to be expanded when making the request.
Does someone know how to change aria-expand elements on a page before returning the content ?
Thanks
|
2019/02/21
|
[
"https://Stackoverflow.com/questions/54813438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2033214/"
] |
```
=Unique(A:B)
```
should be enough to return non-duplicate rows
<https://support.google.com/docs/answer/3093198?hl=en>
[](https://i.stack.imgur.com/w77Gm.png)
You can also use Sortn:
```
=sortn(A:B,9E+99,2,1,true,2,true)
```
|
```
=QUERY(QUERY(A1:B,
"select A, B, count(A)
group by A, B", 1),
"select Col1, Col2
where Col1 is not null", 1)
```
[](https://i.stack.imgur.com/oQyB2.png)
|
54,813,438
|
I am looking to extract content from [a page](https://app.updateimpact.com/treeof/org.json4s/json4s-native_2.11/3.5.2) that is requires a list node to be selected. I have retrieve the page html using python and Selenium. Passing the page source to BS4 I can parse out the content that I am looking for using
```
open_li = soup.select('div#tree ul.jstree-container-ul li')
```
Each list item returned has an
```
aria-expanded = "false" and class="jstree-node jstree-closed"
```
Looking at inspect element the content is called when these variables are set to
```
aria-expanded = "true" and class="jstree-node jstree-open"
```
I have tried using .click method on the content
```
driver.find_element_by_id('tree').click()
```
But that only changes other content on the page. I think the list nodes themselves have to be expanded when making the request.
Does someone know how to change aria-expand elements on a page before returning the content ?
Thanks
|
2019/02/21
|
[
"https://Stackoverflow.com/questions/54813438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2033214/"
] |
```
=QUERY(QUERY(A1:B,
"select A, B, count(A)
group by A, B", 1),
"select Col1, Col2
where Col1 is not null", 1)
```
[](https://i.stack.imgur.com/oQyB2.png)
|
You can also install my add-on called [Flookup](https://gsuite.google.com/marketplace/app/flookup/593806014962) and use the function below:
```
ULIST(colArray, [indexNum], [threshold])
```
* **colArray** The range from which you want to return unique values.
* **indexNum** The column index to analyse for unique values.
* **threshold** The percentage similarity between the non-unique values. This helps eliminate potential duplicates.
So for your case you would simply type:
```
=ULIST(A1:B6, 2)
```
Find out more details at the [official website](https://www.getflookup.com/tutorial).
|
54,813,438
|
I am looking to extract content from [a page](https://app.updateimpact.com/treeof/org.json4s/json4s-native_2.11/3.5.2) that is requires a list node to be selected. I have retrieve the page html using python and Selenium. Passing the page source to BS4 I can parse out the content that I am looking for using
```
open_li = soup.select('div#tree ul.jstree-container-ul li')
```
Each list item returned has an
```
aria-expanded = "false" and class="jstree-node jstree-closed"
```
Looking at inspect element the content is called when these variables are set to
```
aria-expanded = "true" and class="jstree-node jstree-open"
```
I have tried using .click method on the content
```
driver.find_element_by_id('tree').click()
```
But that only changes other content on the page. I think the list nodes themselves have to be expanded when making the request.
Does someone know how to change aria-expand elements on a page before returning the content ?
Thanks
|
2019/02/21
|
[
"https://Stackoverflow.com/questions/54813438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2033214/"
] |
```
=Unique(A:B)
```
should be enough to return non-duplicate rows
<https://support.google.com/docs/answer/3093198?hl=en>
[](https://i.stack.imgur.com/w77Gm.png)
You can also use Sortn:
```
=sortn(A:B,9E+99,2,1,true,2,true)
```
|
You can also install my add-on called [Flookup](https://gsuite.google.com/marketplace/app/flookup/593806014962) and use the function below:
```
ULIST(colArray, [indexNum], [threshold])
```
* **colArray** The range from which you want to return unique values.
* **indexNum** The column index to analyse for unique values.
* **threshold** The percentage similarity between the non-unique values. This helps eliminate potential duplicates.
So for your case you would simply type:
```
=ULIST(A1:B6, 2)
```
Find out more details at the [official website](https://www.getflookup.com/tutorial).
|
31,695,910
|
I'm parsing the US Patent XML files (downloaded from [Google patent dumps](https://www.google.com/googlebooks/uspto-patents-redbook.html)) using Python and Beautifulsoup; parsed data is exported to MYSQL database.
Each year's data contains close to 200-300K patents - which means parsing 200-300K xml files.
The server on which I'm running the python script is pretty powerful - 16 cores, 160 gigs of RAM, etc. but still it is taking close to 3 days to parse one year's worth of data.
[](https://i.stack.imgur.com/Rve8M.png)
[](https://i.stack.imgur.com/dEmQB.png)
I've been learning and using python since 2 years - so I can get stuff done but do not know how to get it done in the most efficient manner. I'm reading on it.
How can I optimize the below script to make it efficient?
Any guidance would be greatly appreciated.
Below is the code:
```
from bs4 import BeautifulSoup
import pandas as pd
from pandas.core.frame import DataFrame
import MySQLdb as db
import os
cnxn = db.connect('xx.xx.xx.xx','xxxxx','xxxxx','xxxx',charset='utf8',use_unicode=True)
def separated_xml(infile):
file = open(infile, "r")
buffer = [file.readline()]
for line in file:
if line.startswith("<?xml "):
yield "".join(buffer)
buffer = []
buffer.append(line)
yield "".join(buffer)
file.close()
def get_data(soup):
df = pd.DataFrame(columns = ['doc_id','patcit_num','patcit_document_id_country', 'patcit_document_id_doc_number','patcit_document_id_kind','patcit_document_id_name','patcit_document_id_date','category'])
if soup.findAll('us-citation'):
cit = soup.findAll('us-citation')
else:
cit = soup.findAll('citation')
doc_id = soup.findAll('publication-reference')[0].find('doc-number').text
for x in cit:
try:
patcit_num = x.find('patcit')['num']
except:
patcit_num = None
try:
patcit_document_id_country = x.find('country').text
except:
patcit_document_id_country = None
try:
patcit_document_id_doc_number = x.find('doc-number').text
except:
patcit_document_id_doc_number = None
try:
patcit_document_id_kind = x.find('kind').text
except:
patcit_document_id_kind = None
try:
patcit_document_id_name = x.find('name').text
except:
patcit_document_id_name = None
try:
patcit_document_id_date = x.find('date').text
except:
patcit_document_id_date = None
try:
category = x.find('category').text
except:
category = None
print doc_id
val = {'doc_id':doc_id,'patcit_num':patcit_num, 'patcit_document_id_country':patcit_document_id_country,'patcit_document_id_doc_number':patcit_document_id_doc_number, 'patcit_document_id_kind':patcit_document_id_kind,'patcit_document_id_name':patcit_document_id_name,'patcit_document_id_date':patcit_document_id_date,'category':category}
df = df.append(val, ignore_index=True)
df.to_sql(name = 'table_name', con = cnxn, flavor='mysql', if_exists='append')
print '1 doc exported'
i=0
l = os.listdir('/path/')
for item in l:
f = '/path/'+item
print 'Currently parsing - ',item
for xml_string in separated_xml(f):
soup = BeautifulSoup(xml_string,'xml')
if soup.find('us-patent-grant'):
print item, i, xml_string[177:204]
get_data(soup)
else:
print item, i, xml_string[177:204],'***********************************soup not found********************************************'
i+=1
print 'DONE!!!'
```
|
2015/07/29
|
[
"https://Stackoverflow.com/questions/31695910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2404998/"
] |
Here is a [tutorial on multi-threading](http://www.tutorialspoint.com/python/python_multithreading.htm), because currently that code will run on 1 thread, 1 core.
Remove all try/except statements and handle the code properly. Exceptions are expensive.
Run a [profiler](http://docs.python.org/2/library/profile.html) to find the chokepoints, and multi-thread those or find a way to do them less times.
|
So, you're doing two things wrong. First, you're using BeautifulSoup, which is slow, and second, you're using a "find" call, which is also slow.
As a first cut, look at `lxml`'s [ability to pre-compile xpath queries](https://lxml.de/xpathxslt.html) (Look at the heading "The Xpath class). That will give you a **huge** speed boost.
Alternatively, I've been working on a library to do this kind of parsing declaratively, using best practices for `lxml` speed, including precompiled xpath called `yankee`.
[Yankee on PyPI](https://pypi.org/project/yankee/) |
[Yankee on GitHub](https://github.com/parkerhancock/yankee)
You could do the same thing with `yankee` like this:
```py
from yankee.xml import Schema, fields as f
# Create a schema for citations
class Citation(Schema):
num = f.Str(".//patcit")
country = f.Str(".//country")
# ... and so forth for the rest of your fields
# Then create a "wrapper" to get all the citations
class Patent(Schema):
citations = f.List(".//us-citation|.//citation")
# Then just feed the Schema your lxml.etrees for each patent:
import lxml.etree as ET
schema = Patent()
for _, doc in ET.iterparse(xml_string, "xml"):
result = schema.load(doc)
```
The result will look like this:
```py
{
"citations": [
{
"num": "<some value>",
"country": "<some value>",
},
{
"num": "<some value>",
"country": "<some value>",
},
]
}
```
I would also check out [Dask](https://www.dask.org/) to help you multithread it more efficiently. Pretty much all my projects use it.
|
11,707,151
|
allow me to preface this by saying that i am learning python on my own as part of my own curiosity, and i was recommended a free online computer science course that is publicly available, so i apologize if i am using terms incorrectly.
i have seen questions regarding this particular problem on here before - but i have a separate question from them and did not want to hijack those threads. the question:
"a substring is any consecutive sequence of characters inside another string. The same substring may occur several times inside the same string: for example "assesses" has the substring "sses" 2 times, and "trans-Panamanian banana" has the substring "an" 6 times. Write a program that takes two lines of input, we call the first needle and the second haystack. Print the number of times that needle occurs as a substring of haystack."
my solution (which works) is:
```
first = str(input())
second = str(input())
count = 0
location = 0
while location < len(second):
if location == 0:
location = str.find(second,first,0)
if location < 0:
break
count = count + 1
location = str.find(second,first,location +1)
if location < 0:
break
count = count + 1
print(count)
```
if you notice, i have on two separate occasions made the if statement that if location is less than 0, to break. is there some way to make this a 'global' condition so i do not have repetitive code? i imagine efficiency becomes paramount with increasing program sophistication so i am trying to develop good practice now.
how would python gurus optimize this code or am i just being too nitpicky?
|
2012/07/29
|
[
"https://Stackoverflow.com/questions/11707151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1560582/"
] |
Check out regular expressions, python's `re` module (http://docs.python.org/library/re.html). For example,
```
import re
first = str(input())
second = str(input())
regex = first[:-1] + '(?=' + first[-1] + ')'
print(len(re.findall(regex, second)))
```
|
**Answer**
```
needle=input()
haystack=input()
counter=0
for i in range(0,len(haystack)):
if(haystack[i:len(needle)+i]!=needle):
continue
counter=counter+1
print(counter)
```
|
11,707,151
|
allow me to preface this by saying that i am learning python on my own as part of my own curiosity, and i was recommended a free online computer science course that is publicly available, so i apologize if i am using terms incorrectly.
i have seen questions regarding this particular problem on here before - but i have a separate question from them and did not want to hijack those threads. the question:
"a substring is any consecutive sequence of characters inside another string. The same substring may occur several times inside the same string: for example "assesses" has the substring "sses" 2 times, and "trans-Panamanian banana" has the substring "an" 6 times. Write a program that takes two lines of input, we call the first needle and the second haystack. Print the number of times that needle occurs as a substring of haystack."
my solution (which works) is:
```
first = str(input())
second = str(input())
count = 0
location = 0
while location < len(second):
if location == 0:
location = str.find(second,first,0)
if location < 0:
break
count = count + 1
location = str.find(second,first,location +1)
if location < 0:
break
count = count + 1
print(count)
```
if you notice, i have on two separate occasions made the if statement that if location is less than 0, to break. is there some way to make this a 'global' condition so i do not have repetitive code? i imagine efficiency becomes paramount with increasing program sophistication so i am trying to develop good practice now.
how would python gurus optimize this code or am i just being too nitpicky?
|
2012/07/29
|
[
"https://Stackoverflow.com/questions/11707151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1560582/"
] |
I think Matthew and darshan have the best solution. I will just post a variation which is based on your solution:
```
first = str(input())
second = str(input())
def count_needle(first, second):
location = str.find(second,first)
if location == -1:
return 0 # none whatsoever
else:
count = 1
while location < len(second):
location = str.find(second,first,location +1)
if location < 0:
break
count = count + 1
return count
print(count_needle(first, second))
```
Idea:
* use function to structure the code when appropriate
* initialise the variable `location` before entering the while loop save you from checking location < 0 multiple times
|
As mentioned by Matthew Adams the best way to do it is using python'd re module [Python re module](http://docs.python.org/library/re.html).
For your case the solution would look something like this:
```
import re
def find_needle_in_heystack(needle, heystack):
return len(re.findall(needle, heystack))
```
Since you are learning python, best way would be to use 'DRY' [Don't Repeat Yourself] mantra. There are lots of python utilities that you can use for many similar situation.
For a quick overview of few very important python modules you can go through this class:
[Google Python Class](http://code.google.com/edu/languages/google-python-class/)
which should only take you a day.
|
11,707,151
|
allow me to preface this by saying that i am learning python on my own as part of my own curiosity, and i was recommended a free online computer science course that is publicly available, so i apologize if i am using terms incorrectly.
i have seen questions regarding this particular problem on here before - but i have a separate question from them and did not want to hijack those threads. the question:
"a substring is any consecutive sequence of characters inside another string. The same substring may occur several times inside the same string: for example "assesses" has the substring "sses" 2 times, and "trans-Panamanian banana" has the substring "an" 6 times. Write a program that takes two lines of input, we call the first needle and the second haystack. Print the number of times that needle occurs as a substring of haystack."
my solution (which works) is:
```
first = str(input())
second = str(input())
count = 0
location = 0
while location < len(second):
if location == 0:
location = str.find(second,first,0)
if location < 0:
break
count = count + 1
location = str.find(second,first,location +1)
if location < 0:
break
count = count + 1
print(count)
```
if you notice, i have on two separate occasions made the if statement that if location is less than 0, to break. is there some way to make this a 'global' condition so i do not have repetitive code? i imagine efficiency becomes paramount with increasing program sophistication so i am trying to develop good practice now.
how would python gurus optimize this code or am i just being too nitpicky?
|
2012/07/29
|
[
"https://Stackoverflow.com/questions/11707151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1560582/"
] |
Check out regular expressions, python's `re` module (http://docs.python.org/library/re.html). For example,
```
import re
first = str(input())
second = str(input())
regex = first[:-1] + '(?=' + first[-1] + ')'
print(len(re.findall(regex, second)))
```
|
I think Matthew and darshan have the best solution. I will just post a variation which is based on your solution:
```
first = str(input())
second = str(input())
def count_needle(first, second):
location = str.find(second,first)
if location == -1:
return 0 # none whatsoever
else:
count = 1
while location < len(second):
location = str.find(second,first,location +1)
if location < 0:
break
count = count + 1
return count
print(count_needle(first, second))
```
Idea:
* use function to structure the code when appropriate
* initialise the variable `location` before entering the while loop save you from checking location < 0 multiple times
|
11,707,151
|
allow me to preface this by saying that i am learning python on my own as part of my own curiosity, and i was recommended a free online computer science course that is publicly available, so i apologize if i am using terms incorrectly.
i have seen questions regarding this particular problem on here before - but i have a separate question from them and did not want to hijack those threads. the question:
"a substring is any consecutive sequence of characters inside another string. The same substring may occur several times inside the same string: for example "assesses" has the substring "sses" 2 times, and "trans-Panamanian banana" has the substring "an" 6 times. Write a program that takes two lines of input, we call the first needle and the second haystack. Print the number of times that needle occurs as a substring of haystack."
my solution (which works) is:
```
first = str(input())
second = str(input())
count = 0
location = 0
while location < len(second):
if location == 0:
location = str.find(second,first,0)
if location < 0:
break
count = count + 1
location = str.find(second,first,location +1)
if location < 0:
break
count = count + 1
print(count)
```
if you notice, i have on two separate occasions made the if statement that if location is less than 0, to break. is there some way to make this a 'global' condition so i do not have repetitive code? i imagine efficiency becomes paramount with increasing program sophistication so i am trying to develop good practice now.
how would python gurus optimize this code or am i just being too nitpicky?
|
2012/07/29
|
[
"https://Stackoverflow.com/questions/11707151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1560582/"
] |
Check out regular expressions, python's `re` module (http://docs.python.org/library/re.html). For example,
```
import re
first = str(input())
second = str(input())
regex = first[:-1] + '(?=' + first[-1] + ')'
print(len(re.findall(regex, second)))
```
|
```
needle = "ss"
haystack = "ssi lass 2 vecess estan ss."
print 'needle occurs %d times in haystack.' % haystack.count(needle)
```
|
11,707,151
|
allow me to preface this by saying that i am learning python on my own as part of my own curiosity, and i was recommended a free online computer science course that is publicly available, so i apologize if i am using terms incorrectly.
i have seen questions regarding this particular problem on here before - but i have a separate question from them and did not want to hijack those threads. the question:
"a substring is any consecutive sequence of characters inside another string. The same substring may occur several times inside the same string: for example "assesses" has the substring "sses" 2 times, and "trans-Panamanian banana" has the substring "an" 6 times. Write a program that takes two lines of input, we call the first needle and the second haystack. Print the number of times that needle occurs as a substring of haystack."
my solution (which works) is:
```
first = str(input())
second = str(input())
count = 0
location = 0
while location < len(second):
if location == 0:
location = str.find(second,first,0)
if location < 0:
break
count = count + 1
location = str.find(second,first,location +1)
if location < 0:
break
count = count + 1
print(count)
```
if you notice, i have on two separate occasions made the if statement that if location is less than 0, to break. is there some way to make this a 'global' condition so i do not have repetitive code? i imagine efficiency becomes paramount with increasing program sophistication so i am trying to develop good practice now.
how would python gurus optimize this code or am i just being too nitpicky?
|
2012/07/29
|
[
"https://Stackoverflow.com/questions/11707151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1560582/"
] |
I think Matthew and darshan have the best solution. I will just post a variation which is based on your solution:
```
first = str(input())
second = str(input())
def count_needle(first, second):
location = str.find(second,first)
if location == -1:
return 0 # none whatsoever
else:
count = 1
while location < len(second):
location = str.find(second,first,location +1)
if location < 0:
break
count = count + 1
return count
print(count_needle(first, second))
```
Idea:
* use function to structure the code when appropriate
* initialise the variable `location` before entering the while loop save you from checking location < 0 multiple times
|
even your aproach could be imo simplified (which uses the fact, that find returns -1, while you aks it to search from non existent offset):
```
>>> x = 'xoxoxo'
>>> start = x.find('o')
>>> indexes = []
>>> while start > -1:
... indexes.append(start)
... start = x.find('o',start+1)
>>> indexes
[1, 3, 5]
```
|
11,707,151
|
allow me to preface this by saying that i am learning python on my own as part of my own curiosity, and i was recommended a free online computer science course that is publicly available, so i apologize if i am using terms incorrectly.
i have seen questions regarding this particular problem on here before - but i have a separate question from them and did not want to hijack those threads. the question:
"a substring is any consecutive sequence of characters inside another string. The same substring may occur several times inside the same string: for example "assesses" has the substring "sses" 2 times, and "trans-Panamanian banana" has the substring "an" 6 times. Write a program that takes two lines of input, we call the first needle and the second haystack. Print the number of times that needle occurs as a substring of haystack."
my solution (which works) is:
```
first = str(input())
second = str(input())
count = 0
location = 0
while location < len(second):
if location == 0:
location = str.find(second,first,0)
if location < 0:
break
count = count + 1
location = str.find(second,first,location +1)
if location < 0:
break
count = count + 1
print(count)
```
if you notice, i have on two separate occasions made the if statement that if location is less than 0, to break. is there some way to make this a 'global' condition so i do not have repetitive code? i imagine efficiency becomes paramount with increasing program sophistication so i am trying to develop good practice now.
how would python gurus optimize this code or am i just being too nitpicky?
|
2012/07/29
|
[
"https://Stackoverflow.com/questions/11707151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1560582/"
] |
Check out regular expressions, python's `re` module (http://docs.python.org/library/re.html). For example,
```
import re
first = str(input())
second = str(input())
regex = first[:-1] + '(?=' + first[-1] + ')'
print(len(re.findall(regex, second)))
```
|
As mentioned by Matthew Adams the best way to do it is using python'd re module [Python re module](http://docs.python.org/library/re.html).
For your case the solution would look something like this:
```
import re
def find_needle_in_heystack(needle, heystack):
return len(re.findall(needle, heystack))
```
Since you are learning python, best way would be to use 'DRY' [Don't Repeat Yourself] mantra. There are lots of python utilities that you can use for many similar situation.
For a quick overview of few very important python modules you can go through this class:
[Google Python Class](http://code.google.com/edu/languages/google-python-class/)
which should only take you a day.
|
11,707,151
|
allow me to preface this by saying that i am learning python on my own as part of my own curiosity, and i was recommended a free online computer science course that is publicly available, so i apologize if i am using terms incorrectly.
i have seen questions regarding this particular problem on here before - but i have a separate question from them and did not want to hijack those threads. the question:
"a substring is any consecutive sequence of characters inside another string. The same substring may occur several times inside the same string: for example "assesses" has the substring "sses" 2 times, and "trans-Panamanian banana" has the substring "an" 6 times. Write a program that takes two lines of input, we call the first needle and the second haystack. Print the number of times that needle occurs as a substring of haystack."
my solution (which works) is:
```
first = str(input())
second = str(input())
count = 0
location = 0
while location < len(second):
if location == 0:
location = str.find(second,first,0)
if location < 0:
break
count = count + 1
location = str.find(second,first,location +1)
if location < 0:
break
count = count + 1
print(count)
```
if you notice, i have on two separate occasions made the if statement that if location is less than 0, to break. is there some way to make this a 'global' condition so i do not have repetitive code? i imagine efficiency becomes paramount with increasing program sophistication so i am trying to develop good practice now.
how would python gurus optimize this code or am i just being too nitpicky?
|
2012/07/29
|
[
"https://Stackoverflow.com/questions/11707151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1560582/"
] |
I think Matthew and darshan have the best solution. I will just post a variation which is based on your solution:
```
first = str(input())
second = str(input())
def count_needle(first, second):
location = str.find(second,first)
if location == -1:
return 0 # none whatsoever
else:
count = 1
while location < len(second):
location = str.find(second,first,location +1)
if location < 0:
break
count = count + 1
return count
print(count_needle(first, second))
```
Idea:
* use function to structure the code when appropriate
* initialise the variable `location` before entering the while loop save you from checking location < 0 multiple times
|
```
needle = "ss"
haystack = "ssi lass 2 vecess estan ss."
print 'needle occurs %d times in haystack.' % haystack.count(needle)
```
|
11,707,151
|
allow me to preface this by saying that i am learning python on my own as part of my own curiosity, and i was recommended a free online computer science course that is publicly available, so i apologize if i am using terms incorrectly.
i have seen questions regarding this particular problem on here before - but i have a separate question from them and did not want to hijack those threads. the question:
"a substring is any consecutive sequence of characters inside another string. The same substring may occur several times inside the same string: for example "assesses" has the substring "sses" 2 times, and "trans-Panamanian banana" has the substring "an" 6 times. Write a program that takes two lines of input, we call the first needle and the second haystack. Print the number of times that needle occurs as a substring of haystack."
my solution (which works) is:
```
first = str(input())
second = str(input())
count = 0
location = 0
while location < len(second):
if location == 0:
location = str.find(second,first,0)
if location < 0:
break
count = count + 1
location = str.find(second,first,location +1)
if location < 0:
break
count = count + 1
print(count)
```
if you notice, i have on two separate occasions made the if statement that if location is less than 0, to break. is there some way to make this a 'global' condition so i do not have repetitive code? i imagine efficiency becomes paramount with increasing program sophistication so i am trying to develop good practice now.
how would python gurus optimize this code or am i just being too nitpicky?
|
2012/07/29
|
[
"https://Stackoverflow.com/questions/11707151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1560582/"
] |
Check out regular expressions, python's `re` module (http://docs.python.org/library/re.html). For example,
```
import re
first = str(input())
second = str(input())
regex = first[:-1] + '(?=' + first[-1] + ')'
print(len(re.findall(regex, second)))
```
|
even your aproach could be imo simplified (which uses the fact, that find returns -1, while you aks it to search from non existent offset):
```
>>> x = 'xoxoxo'
>>> start = x.find('o')
>>> indexes = []
>>> while start > -1:
... indexes.append(start)
... start = x.find('o',start+1)
>>> indexes
[1, 3, 5]
```
|
11,707,151
|
allow me to preface this by saying that i am learning python on my own as part of my own curiosity, and i was recommended a free online computer science course that is publicly available, so i apologize if i am using terms incorrectly.
i have seen questions regarding this particular problem on here before - but i have a separate question from them and did not want to hijack those threads. the question:
"a substring is any consecutive sequence of characters inside another string. The same substring may occur several times inside the same string: for example "assesses" has the substring "sses" 2 times, and "trans-Panamanian banana" has the substring "an" 6 times. Write a program that takes two lines of input, we call the first needle and the second haystack. Print the number of times that needle occurs as a substring of haystack."
my solution (which works) is:
```
first = str(input())
second = str(input())
count = 0
location = 0
while location < len(second):
if location == 0:
location = str.find(second,first,0)
if location < 0:
break
count = count + 1
location = str.find(second,first,location +1)
if location < 0:
break
count = count + 1
print(count)
```
if you notice, i have on two separate occasions made the if statement that if location is less than 0, to break. is there some way to make this a 'global' condition so i do not have repetitive code? i imagine efficiency becomes paramount with increasing program sophistication so i am trying to develop good practice now.
how would python gurus optimize this code or am i just being too nitpicky?
|
2012/07/29
|
[
"https://Stackoverflow.com/questions/11707151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1560582/"
] |
I think Matthew and darshan have the best solution. I will just post a variation which is based on your solution:
```
first = str(input())
second = str(input())
def count_needle(first, second):
location = str.find(second,first)
if location == -1:
return 0 # none whatsoever
else:
count = 1
while location < len(second):
location = str.find(second,first,location +1)
if location < 0:
break
count = count + 1
return count
print(count_needle(first, second))
```
Idea:
* use function to structure the code when appropriate
* initialise the variable `location` before entering the while loop save you from checking location < 0 multiple times
|
**Answer**
```
needle=input()
haystack=input()
counter=0
for i in range(0,len(haystack)):
if(haystack[i:len(needle)+i]!=needle):
continue
counter=counter+1
print(counter)
```
|
11,707,151
|
allow me to preface this by saying that i am learning python on my own as part of my own curiosity, and i was recommended a free online computer science course that is publicly available, so i apologize if i am using terms incorrectly.
i have seen questions regarding this particular problem on here before - but i have a separate question from them and did not want to hijack those threads. the question:
"a substring is any consecutive sequence of characters inside another string. The same substring may occur several times inside the same string: for example "assesses" has the substring "sses" 2 times, and "trans-Panamanian banana" has the substring "an" 6 times. Write a program that takes two lines of input, we call the first needle and the second haystack. Print the number of times that needle occurs as a substring of haystack."
my solution (which works) is:
```
first = str(input())
second = str(input())
count = 0
location = 0
while location < len(second):
if location == 0:
location = str.find(second,first,0)
if location < 0:
break
count = count + 1
location = str.find(second,first,location +1)
if location < 0:
break
count = count + 1
print(count)
```
if you notice, i have on two separate occasions made the if statement that if location is less than 0, to break. is there some way to make this a 'global' condition so i do not have repetitive code? i imagine efficiency becomes paramount with increasing program sophistication so i am trying to develop good practice now.
how would python gurus optimize this code or am i just being too nitpicky?
|
2012/07/29
|
[
"https://Stackoverflow.com/questions/11707151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1560582/"
] |
I think Matthew and darshan have the best solution. I will just post a variation which is based on your solution:
```
first = str(input())
second = str(input())
def count_needle(first, second):
location = str.find(second,first)
if location == -1:
return 0 # none whatsoever
else:
count = 1
while location < len(second):
location = str.find(second,first,location +1)
if location < 0:
break
count = count + 1
return count
print(count_needle(first, second))
```
Idea:
* use function to structure the code when appropriate
* initialise the variable `location` before entering the while loop save you from checking location < 0 multiple times
|
Here you go :
```
first = str(input())
second = str(input())
x=len(first)
counter=0
for i in range(0,len(second)):
if first==second[i:(x+i)]:
counter=counter+1
print(counter)
```
|
53,844,589
|
I wrote the below python script in sublime text3 on executing it ( ctrl + B ) it is not giving any result.
Step 1:
Code:
```
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers()
avenger1.__init__(self)
```
Step 2:
```
ctrl + B
```
Step 3:
Result:
***Repl Closed***
|
2018/12/19
|
[
"https://Stackoverflow.com/questions/53844589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9983752/"
] |
That's because you're only declaring a class, not instantiating it.
Your variable avenger1 exists within the **init** function, therefore it isn't being called. Indentation matters in python.
Try this:
```
class Avengers(object):
def __init__(self):
print('hello')
if __name__ == "__main__":
avenger1 = Avengers()
```
|
You are not instantiating the class. Try something like:
```
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers()
avenger1.__init__(self)
avengers = Avengers() # Initiates the class
```
When you instantiate a class like this, it will execute the `__init__` function for that class.
|
53,844,589
|
I wrote the below python script in sublime text3 on executing it ( ctrl + B ) it is not giving any result.
Step 1:
Code:
```
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers()
avenger1.__init__(self)
```
Step 2:
```
ctrl + B
```
Step 3:
Result:
***Repl Closed***
|
2018/12/19
|
[
"https://Stackoverflow.com/questions/53844589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9983752/"
] |
You are not instantiating the class. Try something like:
```
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers()
avenger1.__init__(self)
avengers = Avengers() # Initiates the class
```
When you instantiate a class like this, it will execute the `__init__` function for that class.
|
The previous answers are correct, but also note that Avengers class in its constructor is initializing another instance of Avengers.
This means when an Avengers object is created, it is creating another Avengers object which is creating another Avengers object and so on.
The `__init__` function is falling into an infinite recursion.
```
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers() # this line triggers infinite recursion
avenger1.__init__(self)
avengers = Avengers() # Initiates the class
```
|
53,844,589
|
I wrote the below python script in sublime text3 on executing it ( ctrl + B ) it is not giving any result.
Step 1:
Code:
```
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers()
avenger1.__init__(self)
```
Step 2:
```
ctrl + B
```
Step 3:
Result:
***Repl Closed***
|
2018/12/19
|
[
"https://Stackoverflow.com/questions/53844589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9983752/"
] |
That's because you're only declaring a class, not instantiating it.
Your variable avenger1 exists within the **init** function, therefore it isn't being called. Indentation matters in python.
Try this:
```
class Avengers(object):
def __init__(self):
print('hello')
if __name__ == "__main__":
avenger1 = Avengers()
```
|
First, let me fix the code
```
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers()
avenger1.init(self)
```
okay, here you creating a class called Avengers. why its not produce anything? because you never initialize that class (creating an object).
so here we go:
```
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers()
avenger1.init(self)
Avengers()
```
it will printing hello, but, its recursive. never end printing "hello". because each time that class is initialized, its creating an object again again and again. **init** is special function so, each time the class is initialized, **init** function will executed.
maybe what you want is like this:
```
class Avengers(object):
def __init__(self):
print('hello')
Avengers()
```
additional reference that you can read: <https://www.sololearn.com/Play/Python>
|
53,844,589
|
I wrote the below python script in sublime text3 on executing it ( ctrl + B ) it is not giving any result.
Step 1:
Code:
```
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers()
avenger1.__init__(self)
```
Step 2:
```
ctrl + B
```
Step 3:
Result:
***Repl Closed***
|
2018/12/19
|
[
"https://Stackoverflow.com/questions/53844589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9983752/"
] |
That's because you're only declaring a class, not instantiating it.
Your variable avenger1 exists within the **init** function, therefore it isn't being called. Indentation matters in python.
Try this:
```
class Avengers(object):
def __init__(self):
print('hello')
if __name__ == "__main__":
avenger1 = Avengers()
```
|
The previous answers are correct, but also note that Avengers class in its constructor is initializing another instance of Avengers.
This means when an Avengers object is created, it is creating another Avengers object which is creating another Avengers object and so on.
The `__init__` function is falling into an infinite recursion.
```
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers() # this line triggers infinite recursion
avenger1.__init__(self)
avengers = Avengers() # Initiates the class
```
|
53,844,589
|
I wrote the below python script in sublime text3 on executing it ( ctrl + B ) it is not giving any result.
Step 1:
Code:
```
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers()
avenger1.__init__(self)
```
Step 2:
```
ctrl + B
```
Step 3:
Result:
***Repl Closed***
|
2018/12/19
|
[
"https://Stackoverflow.com/questions/53844589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9983752/"
] |
First, let me fix the code
```
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers()
avenger1.init(self)
```
okay, here you creating a class called Avengers. why its not produce anything? because you never initialize that class (creating an object).
so here we go:
```
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers()
avenger1.init(self)
Avengers()
```
it will printing hello, but, its recursive. never end printing "hello". because each time that class is initialized, its creating an object again again and again. **init** is special function so, each time the class is initialized, **init** function will executed.
maybe what you want is like this:
```
class Avengers(object):
def __init__(self):
print('hello')
Avengers()
```
additional reference that you can read: <https://www.sololearn.com/Play/Python>
|
The previous answers are correct, but also note that Avengers class in its constructor is initializing another instance of Avengers.
This means when an Avengers object is created, it is creating another Avengers object which is creating another Avengers object and so on.
The `__init__` function is falling into an infinite recursion.
```
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers() # this line triggers infinite recursion
avenger1.__init__(self)
avengers = Avengers() # Initiates the class
```
|
21,369,607
|
I am trying to convert the following python extract to C
```
tvip = "192.168.0.3"
myip = "192.168.0.7"
mymac = "00-0c-29-3e-b1-4f"
appstring = "iphone..iapp.samsung"
tvappstring = "iphone.UE55C8000.iapp.samsung"
remotename = "Python Samsung Remote"
ipencoded = base64.b64encode(myip)
macencoded = base64.b64encode(mymac)
messagepart1 = chr(0x64) + chr(0x00) + chr(len(ipencoded)) \
+ chr(0x00) + ipencoded + chr(len(macencoded)) + chr(0x00) \
+ macencoded + chr(len(base64.b64encode(remotename))) + chr(0x00) \
+ base64.b64encode(remotename)
part1 = chr(0x00) + chr(len(appstring)) + chr(0x00) + appstring \
+ chr(len(messagepart1)) + chr(0x00) + messagepart1
```
I don't actually know what `messagepart1` actually represents in terms of datastructure.
Here is my attempt:
```
var myip_e = myip.ToBase64();
var mymac_e = mymac.ToBase64();
var m1 = (char)0x64 + (char)0x00 + (char)myip_e.Length + (char)0x00 + myip_e +
(char)mymac_e.Length + (char)0x00 + mymac_e + (char)remotename.ToBase64().Length + (char)0x00 +remotename.ToBase64();
var p1 = (char)0x00 + (char)appstring.Length + (char)0x00 + appstring + (char)m1.Length + (char)0x00 + m1;
//var b1 = p1.GetBytes(); // this is to write to the socket.
public static string ToBase64(this string source)
{
return Convert.ToBase64String(source.GetBytes());
}
public static byte[] GetBytes(this string source)
{
byte[] bytes = new byte[source.Length * sizeof(char)];
System.Buffer.BlockCopy(source.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
```
The way I am comparing is that I am printing both to console, expecting them to be the same if correct - obviously I am doing something wrong.
|
2014/01/26
|
[
"https://Stackoverflow.com/questions/21369607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/126280/"
] |
`fragment` lexer rules can only be used by other lexer rules: these will never become a token on their own. Therefor, you cannot use `fragment` rules in parser rules.
|
The `fragment` is not the root cause.
First, try to reproduce your errors:
------------------------------------
When compiling your Test.g4, it will appear warnings below:
```
warning(156): Test.g4:11:21: invalid escape sequence \"
warning(156): Test.g4:123:59: invalid escape sequence \"
warning(146): Test.g4:11:0: non-fragment lexer rule QUOTE can match the empty string
warning(125): Test.g4:3:8: implicit definition of token NonZeroDigit in parser
warning(125): Test.g4:3:25: implicit definition of token Digit in parser
```
After removing unused rules:
```g4
grammar Test;
start : NonZeroDigit '.' Digit Digit? EOF
;
fragment
NonZeroDigit : [1-9]
;
fragment
Digit : '0' | NonZeroDigit
;
```
Then compile it again and test it:
```
warning(125): Test.g4:3:8: implicit definition of token NonZeroDigit in parser
warning(125): Test.g4:3:25: implicit definition of token Digit in parser
line 1:0 token recognition error at: '1'
line 1:2 token recognition error at: '1'
line 1:3 token recognition error at: '1'
line 1:1 missing NonZeroDigit at '.'
line 1:4 missing Digit at '<EOF>'
(start <missing NonZeroDigit> . <missing Digit> <EOF>)
```
(try to reproduce your errors)
When applying **'fragment'**
----------------------------
When applying **'fragment'** on `NonZeroDigit` and `Digit`, the g4 will be equivalent to :
replace `NonZeroDigit` with `[1-9]`
```
grammar Test;
start : [1-9] '.' Digit Digit? EOF
;
fragment
Digit : '0' | [1-9]
;
```
replace `Digit` with `('0' | [1-9])`
```
grammar Test;
start : [1-9] '.' ('0' | [1-9]) ('0' | [1-9])? EOF
;
```
but the parser rule `start`(the identifier starts with a lowercase alphabet) cannot be all letters.
Refer to `The Definitive ANTLR 4 Reference` Page73
>
> lexer rule names with uppercase letters and parser rule names with
> lowercase letters. For example, ID is a lexical rule name, and expr is
> a parser rule name.
>
>
>
After removing 'fragment'
-------------------------
After removing 'fragment' from g4, there is still an unexpected error.
```
line 1:3 extraneous input '3' expecting {<EOF>, Digit}
(start 1 . 0 3 <EOF>)
```
**Error study:**
for `NonZeroDigit`:
if naming as nonZeroDigit, we will get:
```
syntax error: '1-9' came as a complete surprise to me while matching alternative
```
Because `[1-9]` is a letter (constant token). We need to name it with an uppercase prefix. (=lexer rule)
`for Digit`:
it containing an identifier `NonZeroDigit`, so we need to name it with a lowercase prefix. (=parser rule)
The correct Test.g4 should be:
------------------------------
```g4
grammar Test;
start : NonZeroDigit '.' digit digit? EOF
;
NonZeroDigit : [1-9]
;
digit : '0' | NonZeroDigit
;
```
If you want to use `fragment`, you should create a lexer rule `Number` because the rule ONLY consists of letters (constant tokens). And the identifier should start with an uppercase prefix, `start` is not
```g4
grammar Test;
start : Number EOF
;
Number : NonZeroDigit '.' Digit Digit?
;
fragment
NonZeroDigit : [1-9]
;
fragment
Digit : '0' | NonZeroDigit
;
```
|
59,415,503
|
I am trying to run the object detection API in tensorflow following this tutorial / accompanying code: <https://gilberttanner.com/blog/creating-your-own-objectdetector>
When I type `python2 generate_tfrecord.py --csv_input=images_train.csv --image_dir=images\train --output_path=train.record` into the terminal, I see a file train.record is created in this directory, but I also get the following error message:
```
Traceback (most recent call last):
File "generate_tfrecord.py", line 107, in <module>
tf.app.run()
File "/usr/local/lib/python2.7/site-packages/tensorflow_core/python/platform/app.py", line 40, in run
_run(main=main, argv=argv, flags_parser=_parse_flags_tolerate_undef)
File "/usr/local/lib/python2.7/site-packages/absl/app.py", line 299, in run
_run_main(main, args)
File "/usr/local/lib/python2.7/site-packages/absl/app.py", line 250, in _run_main
sys.exit(main(argv))
File "generate_tfrecord.py", line 96, in main
grouped = split(examples, 'filename')
File "generate_tfrecord.py", line 47, in split
gb = df.groupby(group)
File "/Users/sofiatomov/Library/Python/2.7/lib/python/site-packages/pandas/core/generic.py", line 6665, in groupby
observed=observed, **kwargs)
File "/Users/sofiatomov/Library/Python/2.7/lib/python/site-packages/pandas/core/groupby/groupby.py", line 2152, in groupby
return klass(obj, by, **kwds)
File "/Users/sofiatomov/Library/Python/2.7/lib/python/site-packages/pandas/core/groupby/groupby.py", line 599, in __init__
mutated=self.mutated)
File "/Users/sofiatomov/Library/Python/2.7/lib/python/site-packages/pandas/core/groupby/groupby.py", line 3291, in _get_grouper
raise KeyError(gpr)
KeyError: 'filename'
```
How do I fix this?
Thanks.
|
2019/12/19
|
[
"https://Stackoverflow.com/questions/59415503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11756066/"
] |
What you have here is an async function that performs an async operation, where that operation does *not* use promises. This means that you need to setup a function that manages and returns a promise explicitly. You don't need the `async` keyword here, since you want to explicitly `return` a `Promise` that you create, and not a promise created for you by the async keyword (which you cannot directly manage).
```
function httpRequest() {
// Return a promise (this is what an async function does for you)
return new Promise(resolve => {
const oReq = new XMLHttpRequest();
oReq.addEventListener("load", function() {
// Resolve the promise when the async operation is complete.
resolve(this.responseText);
});
oReq.open("GET", "http://some.url.here");
oReq.send();
};
}
```
Now that the function explicitly returns a promise, it can be `await`ed just like an `async` function. Or used with `then()` like any promise.
```
async function someFunction() {
// await
const awaitedResponse = await httpRequest();
console.log(awaitedResponse);
// or promise chain
httpRequest().then(responseText => console.log(responseText));
};
```
|
Basically, you are trying to write an `async` function without having anything in that function to await. You use async/await when there is some asynchronous-ness in the code, while in yours, there isn't.
This is an example that might be useful:
```
const getItemsAsync = async () => {
const res = await DoSomethingAsync();
return res.items;
}
const items = await getItemsAsync();
```
As you can see, `DoSomethingAsync` is an asynchronous function I await the result for, which is `res`. At that point, the code will pause. Once the promise will be resolved, the code will resume and therefore will return `res.items`, which means that `items` will actually contain the result of the async function.
Also, async/await is just a spacial syntax that makes the code more readable, by giving it a more synchronous form (not substance).
If you really want to make it asynchronous, you can promisify your synchronous code in order to make it return a promise to await, that will then be either resolved or rejected.
|
63,664,484
|
I have to create a function called read\_data that takes a filename as its only parameter. This function must then open the file with the given name and return a dictionary where the keys are the location names in the file and the values are a list of the readings.
The result of the first function works and displays:
```
{'Monday': [67 , 43], 'Tuesday': [14, 26], 'Wednesday': [68, 44], ‘Thursday’:[15, 35],’Friday’:[70, 31],’Saturday’;[34, 39],’Sunday’:[22, 18]}
```
The second function named get\_average\_dictionary that takes a dictionary structured like the return value of read\_data as its only parameter and returns a dictionary with the same keys as the parameter, but with the average value of the readings rather than the list of individual readings. This has to return:
```
{'Monday': [55.00], 'Tuesday': [20.00], 'Wednesday': [56.00], ‘Thursday’:[25.00],’Friday’:[50.50],’Saturday’;[36.50],’Sunday’:[20.00]}
```
But I can not get it to work. I get the following errors:
```
line 25, in <module>
averages = get_average_dictionary(readings)
line 15, in get_average_dictionary
average = {key: sum(val)/len(val) for key, val in readings.items()}
AttributeError: 'NoneType' object has no attribute 'items'
```
Here is the code I have at the moment. Any help would be appreciated.
```
def read_data(filename):
readings = {}
with open("c:\\users\\jstew\\documents\\readings.txt") as f:
for line in f:
(key, val) = line.split(',')
if not key in readings.keys():
readings[key] = []
readings[key].append(int(val))
print(readings)
def get_average_dictionary(readings):
average = {key: sum(val)/len(val) for key, val in readings.items()}
print(average)
FILENAME = "readings.txt"
if __name__ == "__main__":
try:
readings = read_data(FILENAME)
averages = get_average_dictionary(readings)
# Loops through the keys in averages, sorted from that with the largest associated value in averages to the lowest - see https://docs.python.org/3.5/library/functions.html#sorted for details
for days in sorted(averages, key = averages.get, reverse = True):
print(days, averages[days])
```
|
2020/08/31
|
[
"https://Stackoverflow.com/questions/63664484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14001036/"
] |
Given:
```
di={'Monday': [67 , 43], 'Tuesday': [14, 26], 'Wednesday': [68, 44], 'Thursday':[15, 35],'Friday':[70, 31],'Saturday':[34, 39],'Sunday':[22, 18]}
```
You can do:
```
>>> {k:sum(v)/len(v) for k,v in di.items()}
{'Monday': 55.0, 'Tuesday': 20.0, 'Wednesday': 56.0, 'Thursday': 25.0, 'Friday': 50.5, 'Saturday': 36.5, 'Sunday': 20.0}
```
The error you have seems to be that you are returning nothing from your function. Just do:
```
def a_func(di):
return {k:sum(v)/len(v) for k,v in di.items()}
```
And you should be good to go...
|
You were close but had at least one problem. One was this:
`Friday’:[50.50],’Saturday’;[36.50],’Sunday’: [22, 18]`
Notice ’Saturday’ is followed by a semicolon, not a colon. That's in both examples. Also, notice your text changes color from red to blue. That usually (this case included) means that you switched from single quotes to something like smartquotes or a character that looks like a normal quote but isn't recognized as such.
```
{'Monday': [67 , 43], 'Tuesday': [14, 26], 'Wednesday': [68, 44], ‘Thursday’:[15, 35],’Friday’:[70, 31],’Saturday’;[34, 39],’Sunday’:[22, 18]}
```
Once those are cleared up you just have to deal with the last part, returning vs printing the result.
```
def get_average_dictionary(readings):
return {k:(sum(v)/len(v)) for (k,v) in vals.items()}
```
|
46,078,088
|
I want to upload an image on Google Cloud Storage from a python script. This is my code:
```
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient import discovery
scopes = ['https://www.googleapis.com/auth/devstorage.full_control']
credentials = ServiceAccountCredentials.from_json_keyfile_name('serviceAccount.json', scop
es)
service = discovery.build('storage','v1',credentials = credentials)
body = {'name':'my_image.jpg'}
req = service.objects().insert(
bucket='my_bucket', body=body,
media_body=googleapiclient.http.MediaIoBaseUpload(
gcs_image, 'application/octet-stream'))
resp = req.execute()
```
if `gcs_image = open('img.jpg', 'r')` the code works and correctly save my image on Cloud Storage. How can I directly upload a bytes image? (for example from an OpenCV/Numpy array: `gcs_image = cv2.imread('img.jpg')`)
|
2017/09/06
|
[
"https://Stackoverflow.com/questions/46078088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7219743/"
] |
If you want to upload your image from file.
```
import os
from google.cloud import storage
def upload_file_to_gcs(bucket_name, local_path, local_file_name, target_key):
try:
client = storage.Client()
bucket = client.bucket(bucket_name)
full_file_path = os.path.join(local_path, local_file_name)
bucket.blob(target_key).upload_from_filename(full_file_path)
return bucket.blob(target_key).public_url
except Exception as e:
print(e)
return None
```
but if you want to upload bytes directly:
```
import os
from google.cloud import storage
def upload_data_to_gcs(bucket_name, data, target_key):
try:
client = storage.Client()
bucket = client.bucket(bucket_name)
bucket.blob(target_key).upload_from_string(data)
return bucket.blob(target_key).public_url
except Exception as e:
print(e)
return None
```
note that `target_key` is prefix and the name of the uploaded file.
|
`MediaIoBaseUpload` expects an [`io.Base`](https://docs.python.org/3/library/io.html#io.IOBase)-like object and raises following error:
```
'numpy.ndarray' object has no attribute 'seek'
```
upon receiving a ndarray object. To solve it I am using `TemporaryFile` and `numpy.ndarray().tofile()`
```
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient import discovery
import googleapiclient
import numpy as np
import cv2
from tempfile import TemporaryFile
scopes = ['https://www.googleapis.com/auth/devstorage.full_control']
credentials = ServiceAccountCredentials.from_json_keyfile_name('serviceAccount.json', scopes)
service = discovery.build('storage','v1',credentials = credentials)
body = {'name':'my_image.jpg'}
with TemporaryFile() as gcs_image:
cv2.imread('img.jpg').tofile(gcs_image)
req = service.objects().insert(
bucket='my_bucket’, body=body,
media_body=googleapiclient.http.MediaIoBaseUpload(
gcs_image, 'application/octet-stream'))
resp = req.execute()
```
Be aware that googleapiclient is non-idiomatic and **maintenance only**(it’s not developed anymore). I would recommend using [idiomatic one](https://googlecloudplatform.github.io/google-cloud-python/latest/index.html).
|
46,078,088
|
I want to upload an image on Google Cloud Storage from a python script. This is my code:
```
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient import discovery
scopes = ['https://www.googleapis.com/auth/devstorage.full_control']
credentials = ServiceAccountCredentials.from_json_keyfile_name('serviceAccount.json', scop
es)
service = discovery.build('storage','v1',credentials = credentials)
body = {'name':'my_image.jpg'}
req = service.objects().insert(
bucket='my_bucket', body=body,
media_body=googleapiclient.http.MediaIoBaseUpload(
gcs_image, 'application/octet-stream'))
resp = req.execute()
```
if `gcs_image = open('img.jpg', 'r')` the code works and correctly save my image on Cloud Storage. How can I directly upload a bytes image? (for example from an OpenCV/Numpy array: `gcs_image = cv2.imread('img.jpg')`)
|
2017/09/06
|
[
"https://Stackoverflow.com/questions/46078088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7219743/"
] |
In my case, I wanted to upload a PDF document to Cloud Storage from bytes.
When I tried the below, it created a text file with my byte string in it.
```
blob.upload_from_string(bytedata)
```
In order to create an actual PDF file using the byte string I had to do:
```
blob.upload_from_string(bytedata, content_type='application/pdf')
```
My byte data was b64encoded, so I also had b64decode it first.
|
`MediaIoBaseUpload` expects an [`io.Base`](https://docs.python.org/3/library/io.html#io.IOBase)-like object and raises following error:
```
'numpy.ndarray' object has no attribute 'seek'
```
upon receiving a ndarray object. To solve it I am using `TemporaryFile` and `numpy.ndarray().tofile()`
```
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient import discovery
import googleapiclient
import numpy as np
import cv2
from tempfile import TemporaryFile
scopes = ['https://www.googleapis.com/auth/devstorage.full_control']
credentials = ServiceAccountCredentials.from_json_keyfile_name('serviceAccount.json', scopes)
service = discovery.build('storage','v1',credentials = credentials)
body = {'name':'my_image.jpg'}
with TemporaryFile() as gcs_image:
cv2.imread('img.jpg').tofile(gcs_image)
req = service.objects().insert(
bucket='my_bucket’, body=body,
media_body=googleapiclient.http.MediaIoBaseUpload(
gcs_image, 'application/octet-stream'))
resp = req.execute()
```
Be aware that googleapiclient is non-idiomatic and **maintenance only**(it’s not developed anymore). I would recommend using [idiomatic one](https://googlecloudplatform.github.io/google-cloud-python/latest/index.html).
|
46,078,088
|
I want to upload an image on Google Cloud Storage from a python script. This is my code:
```
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient import discovery
scopes = ['https://www.googleapis.com/auth/devstorage.full_control']
credentials = ServiceAccountCredentials.from_json_keyfile_name('serviceAccount.json', scop
es)
service = discovery.build('storage','v1',credentials = credentials)
body = {'name':'my_image.jpg'}
req = service.objects().insert(
bucket='my_bucket', body=body,
media_body=googleapiclient.http.MediaIoBaseUpload(
gcs_image, 'application/octet-stream'))
resp = req.execute()
```
if `gcs_image = open('img.jpg', 'r')` the code works and correctly save my image on Cloud Storage. How can I directly upload a bytes image? (for example from an OpenCV/Numpy array: `gcs_image = cv2.imread('img.jpg')`)
|
2017/09/06
|
[
"https://Stackoverflow.com/questions/46078088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7219743/"
] |
In my case, I wanted to upload a PDF document to Cloud Storage from bytes.
When I tried the below, it created a text file with my byte string in it.
```
blob.upload_from_string(bytedata)
```
In order to create an actual PDF file using the byte string I had to do:
```
blob.upload_from_string(bytedata, content_type='application/pdf')
```
My byte data was b64encoded, so I also had b64decode it first.
|
If you want to upload your image from file.
```
import os
from google.cloud import storage
def upload_file_to_gcs(bucket_name, local_path, local_file_name, target_key):
try:
client = storage.Client()
bucket = client.bucket(bucket_name)
full_file_path = os.path.join(local_path, local_file_name)
bucket.blob(target_key).upload_from_filename(full_file_path)
return bucket.blob(target_key).public_url
except Exception as e:
print(e)
return None
```
but if you want to upload bytes directly:
```
import os
from google.cloud import storage
def upload_data_to_gcs(bucket_name, data, target_key):
try:
client = storage.Client()
bucket = client.bucket(bucket_name)
bucket.blob(target_key).upload_from_string(data)
return bucket.blob(target_key).public_url
except Exception as e:
print(e)
return None
```
note that `target_key` is prefix and the name of the uploaded file.
|
46,078,088
|
I want to upload an image on Google Cloud Storage from a python script. This is my code:
```
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient import discovery
scopes = ['https://www.googleapis.com/auth/devstorage.full_control']
credentials = ServiceAccountCredentials.from_json_keyfile_name('serviceAccount.json', scop
es)
service = discovery.build('storage','v1',credentials = credentials)
body = {'name':'my_image.jpg'}
req = service.objects().insert(
bucket='my_bucket', body=body,
media_body=googleapiclient.http.MediaIoBaseUpload(
gcs_image, 'application/octet-stream'))
resp = req.execute()
```
if `gcs_image = open('img.jpg', 'r')` the code works and correctly save my image on Cloud Storage. How can I directly upload a bytes image? (for example from an OpenCV/Numpy array: `gcs_image = cv2.imread('img.jpg')`)
|
2017/09/06
|
[
"https://Stackoverflow.com/questions/46078088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7219743/"
] |
If you want to upload your image from file.
```
import os
from google.cloud import storage
def upload_file_to_gcs(bucket_name, local_path, local_file_name, target_key):
try:
client = storage.Client()
bucket = client.bucket(bucket_name)
full_file_path = os.path.join(local_path, local_file_name)
bucket.blob(target_key).upload_from_filename(full_file_path)
return bucket.blob(target_key).public_url
except Exception as e:
print(e)
return None
```
but if you want to upload bytes directly:
```
import os
from google.cloud import storage
def upload_data_to_gcs(bucket_name, data, target_key):
try:
client = storage.Client()
bucket = client.bucket(bucket_name)
bucket.blob(target_key).upload_from_string(data)
return bucket.blob(target_key).public_url
except Exception as e:
print(e)
return None
```
note that `target_key` is prefix and the name of the uploaded file.
|
Here is how to directly upload a PIL Image from memory:
```py
from google.cloud import storage
import io
from PIL import Image
# Define variables
bucket_name = XXXXX
destination_blob_filename = XXXXX
# Configure bucket and blob
client = storage.Client()
bucket = client.bucket(bucket_name)
im = Image.open("test.jpg")
bs = io.BytesIO()
im.save(bs, "jpeg")
blob.upload_from_string(bs.getvalue(), content_type="image/jpeg")
```
In addition to that, here is how to download blobfiles directly to memory as PIL Images:
```py
blob = bucket.blob(destination_blob_filename)
downloaded_im_data = blob.download_as_bytes()
downloaded_im = Image.open(io.BytesIO(downloaded_im_data))
```
|
46,078,088
|
I want to upload an image on Google Cloud Storage from a python script. This is my code:
```
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient import discovery
scopes = ['https://www.googleapis.com/auth/devstorage.full_control']
credentials = ServiceAccountCredentials.from_json_keyfile_name('serviceAccount.json', scop
es)
service = discovery.build('storage','v1',credentials = credentials)
body = {'name':'my_image.jpg'}
req = service.objects().insert(
bucket='my_bucket', body=body,
media_body=googleapiclient.http.MediaIoBaseUpload(
gcs_image, 'application/octet-stream'))
resp = req.execute()
```
if `gcs_image = open('img.jpg', 'r')` the code works and correctly save my image on Cloud Storage. How can I directly upload a bytes image? (for example from an OpenCV/Numpy array: `gcs_image = cv2.imread('img.jpg')`)
|
2017/09/06
|
[
"https://Stackoverflow.com/questions/46078088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7219743/"
] |
In my case, I wanted to upload a PDF document to Cloud Storage from bytes.
When I tried the below, it created a text file with my byte string in it.
```
blob.upload_from_string(bytedata)
```
In order to create an actual PDF file using the byte string I had to do:
```
blob.upload_from_string(bytedata, content_type='application/pdf')
```
My byte data was b64encoded, so I also had b64decode it first.
|
Here is how to directly upload a PIL Image from memory:
```py
from google.cloud import storage
import io
from PIL import Image
# Define variables
bucket_name = XXXXX
destination_blob_filename = XXXXX
# Configure bucket and blob
client = storage.Client()
bucket = client.bucket(bucket_name)
im = Image.open("test.jpg")
bs = io.BytesIO()
im.save(bs, "jpeg")
blob.upload_from_string(bs.getvalue(), content_type="image/jpeg")
```
In addition to that, here is how to download blobfiles directly to memory as PIL Images:
```py
blob = bucket.blob(destination_blob_filename)
downloaded_im_data = blob.download_as_bytes()
downloaded_im = Image.open(io.BytesIO(downloaded_im_data))
```
|
35,144,550
|
My ubuntu is 14.04 LTS.
When I install cryptography, the error is:
```
Installing egg-scripts.
uses namespace packages but the distribution does not require setuptools.
Getting distribution for 'cryptography==0.2.1'.
no previously-included directories found matching 'documentation/_build'
zip_safe flag not set; analyzing archive contents...
six: module references __path__
Installed /tmp/easy_install-oUz7ei/cryptography-0.2.1/.eggs/six-1.10.0-py2.7.egg
Searching for cffi>=0.8
Reading https://pypi.python.org/simple/cffi/
Best match: cffi 1.5.0
Downloading https://pypi.python.org/packages/source/c/cffi/cffi-1.5.0.tar.gz#md5=dec8441e67880494ee881305059af656
Processing cffi-1.5.0.tar.gz
Writing /tmp/easy_install-oUz7ei/cryptography-0.2.1/temp/easy_install-Yf2Yl3/cffi-1.5.0/setup.cfg
Running cffi-1.5.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-oUz7ei/cryptography-0.2.1/temp/easy_install-Yf2Yl3/cffi-1.5.0/egg-dist-tmp-A2kjMD
c/_cffi_backend.c:15:17: fatal error: ffi.h: No such file or directory
#include <ffi.h>
^
compilation terminated.
error: Setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
An error occurred when trying to install cryptography 0.2.1. Look above this message for any errors that were output by easy_install.
While:
Installing egg-scripts.
Getting distribution for 'cryptography==0.2.1'.
Error: Couldn't install: cryptography 0.2.1
```
I don't know why it was failed. What is the reason. Is there something necessary when install it on ubuntu system?
|
2016/02/02
|
[
"https://Stackoverflow.com/questions/35144550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2890633/"
] |
The answer is on the docs of `cryptography`'s [installation section](https://cryptography.io/en/latest/installation/#building-cryptography-on-linux) which pretty much reflects Angelos' answer:
Quoting it:
>
> For Debian and **Ubuntu**, the following command will ensure that the
> required dependencies are installed:
>
>
>
> ```
> $ sudo apt-get install build-essential libssl-dev libffi-dev python-dev
>
> ```
>
> For Fedora and RHEL-derivatives, the following command will ensure
> that the required dependencies are installed:
>
>
>
> ```
> $ sudo yum install gcc libffi-devel python-devel openssl-devel
>
> ```
>
> You should now be able to build and install cryptography with the
> usual
>
>
>
> ```
> $ pip install cryptography
>
> ```
>
>
If you're using Python 3, please use `python3-dev` instead of `python-dev` in the first command. (thanks to @chasmani)
If you're installing this on `Ubuntu 18.04`, please use `libssl1.0` instead of `libssl-dev` in the first command. (thanks to @pobe)
|
I had the same problem when pip installing the cryptography module on Ubuntu 14.04. I solved it by installing libffi-dev:
```
apt-get install -y libffi-dev
```
Then I got the following error:
```
build/temp.linux-x86_64-3.4/_openssl.c:431:25: fatal error: openssl/aes.h: No such file or directory
#include <openssl/aes.h>
^
compilation terminated.
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
```
Which I resolved by installing libssl-dev:
```
apt-get install -y libssl-dev
```
|
35,144,550
|
My ubuntu is 14.04 LTS.
When I install cryptography, the error is:
```
Installing egg-scripts.
uses namespace packages but the distribution does not require setuptools.
Getting distribution for 'cryptography==0.2.1'.
no previously-included directories found matching 'documentation/_build'
zip_safe flag not set; analyzing archive contents...
six: module references __path__
Installed /tmp/easy_install-oUz7ei/cryptography-0.2.1/.eggs/six-1.10.0-py2.7.egg
Searching for cffi>=0.8
Reading https://pypi.python.org/simple/cffi/
Best match: cffi 1.5.0
Downloading https://pypi.python.org/packages/source/c/cffi/cffi-1.5.0.tar.gz#md5=dec8441e67880494ee881305059af656
Processing cffi-1.5.0.tar.gz
Writing /tmp/easy_install-oUz7ei/cryptography-0.2.1/temp/easy_install-Yf2Yl3/cffi-1.5.0/setup.cfg
Running cffi-1.5.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-oUz7ei/cryptography-0.2.1/temp/easy_install-Yf2Yl3/cffi-1.5.0/egg-dist-tmp-A2kjMD
c/_cffi_backend.c:15:17: fatal error: ffi.h: No such file or directory
#include <ffi.h>
^
compilation terminated.
error: Setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
An error occurred when trying to install cryptography 0.2.1. Look above this message for any errors that were output by easy_install.
While:
Installing egg-scripts.
Getting distribution for 'cryptography==0.2.1'.
Error: Couldn't install: cryptography 0.2.1
```
I don't know why it was failed. What is the reason. Is there something necessary when install it on ubuntu system?
|
2016/02/02
|
[
"https://Stackoverflow.com/questions/35144550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2890633/"
] |
I had the same problem when pip installing the cryptography module on Ubuntu 14.04. I solved it by installing libffi-dev:
```
apt-get install -y libffi-dev
```
Then I got the following error:
```
build/temp.linux-x86_64-3.4/_openssl.c:431:25: fatal error: openssl/aes.h: No such file or directory
#include <openssl/aes.h>
^
compilation terminated.
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
```
Which I resolved by installing libssl-dev:
```
apt-get install -y libssl-dev
```
|
Installing libssl-dev and python-dev was enough for me on ubuntu 16.04.
|
35,144,550
|
My ubuntu is 14.04 LTS.
When I install cryptography, the error is:
```
Installing egg-scripts.
uses namespace packages but the distribution does not require setuptools.
Getting distribution for 'cryptography==0.2.1'.
no previously-included directories found matching 'documentation/_build'
zip_safe flag not set; analyzing archive contents...
six: module references __path__
Installed /tmp/easy_install-oUz7ei/cryptography-0.2.1/.eggs/six-1.10.0-py2.7.egg
Searching for cffi>=0.8
Reading https://pypi.python.org/simple/cffi/
Best match: cffi 1.5.0
Downloading https://pypi.python.org/packages/source/c/cffi/cffi-1.5.0.tar.gz#md5=dec8441e67880494ee881305059af656
Processing cffi-1.5.0.tar.gz
Writing /tmp/easy_install-oUz7ei/cryptography-0.2.1/temp/easy_install-Yf2Yl3/cffi-1.5.0/setup.cfg
Running cffi-1.5.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-oUz7ei/cryptography-0.2.1/temp/easy_install-Yf2Yl3/cffi-1.5.0/egg-dist-tmp-A2kjMD
c/_cffi_backend.c:15:17: fatal error: ffi.h: No such file or directory
#include <ffi.h>
^
compilation terminated.
error: Setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
An error occurred when trying to install cryptography 0.2.1. Look above this message for any errors that were output by easy_install.
While:
Installing egg-scripts.
Getting distribution for 'cryptography==0.2.1'.
Error: Couldn't install: cryptography 0.2.1
```
I don't know why it was failed. What is the reason. Is there something necessary when install it on ubuntu system?
|
2016/02/02
|
[
"https://Stackoverflow.com/questions/35144550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2890633/"
] |
The answer is on the docs of `cryptography`'s [installation section](https://cryptography.io/en/latest/installation/#building-cryptography-on-linux) which pretty much reflects Angelos' answer:
Quoting it:
>
> For Debian and **Ubuntu**, the following command will ensure that the
> required dependencies are installed:
>
>
>
> ```
> $ sudo apt-get install build-essential libssl-dev libffi-dev python-dev
>
> ```
>
> For Fedora and RHEL-derivatives, the following command will ensure
> that the required dependencies are installed:
>
>
>
> ```
> $ sudo yum install gcc libffi-devel python-devel openssl-devel
>
> ```
>
> You should now be able to build and install cryptography with the
> usual
>
>
>
> ```
> $ pip install cryptography
>
> ```
>
>
If you're using Python 3, please use `python3-dev` instead of `python-dev` in the first command. (thanks to @chasmani)
If you're installing this on `Ubuntu 18.04`, please use `libssl1.0` instead of `libssl-dev` in the first command. (thanks to @pobe)
|
Installing libssl-dev and python-dev was enough for me on ubuntu 16.04.
|
70,021,042
|
```
import spacy
nlp = spacy.load('en_core_web_sm')
from spacy.lemmatizer import Lemmatizer
from spacy.lang.en import LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES
lemmatizer = Lemmatizer(LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES)
lemmattizer('chunkles', 'NOUN')
```
Can anyone help me? I'm using Version 3 of python
|
2021/11/18
|
[
"https://Stackoverflow.com/questions/70021042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17447993/"
] |
The official document shows that after spacy 3.0, the lemmatizer has become a standalone pipeline component. Therefore, you should install the spacy whose version is smaller than 3.0. The link is as follow: <https://spacy.io/api/lemmatizer>
|
try:
doc = nlp('chuckles')
doc[0].lemma\_
|
9,345,250
|
I have tried:
```
>>> l = [1,2,3]
>>> x = 1
>>> x in l and lambda: print("Foo")
x in l && print "Horray"
^
SyntaxError: invalid syntax
```
A bit of googling revealed that `print` is a statement in `python2` whereas it's a function in `python3`. But, I have tried the above snipped in `python3` and it throws SyntaxError exception.
Any idea on how can I do it in **one line**? (Readability or google programming practice is not an issue here)
|
2012/02/18
|
[
"https://Stackoverflow.com/questions/9345250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1218583/"
] |
```
l = [1, 2, 3]
x = 1
if x in l: print "Foo"
```
I'm not being a smart ass, this is the way to do it in **one line**. Or, if you're using Python3:
```
if x in l: print("Foo")
```
|
Getting rid of the shortcomings of print as a statement in Python2.x using `from __future__ import print_function` is the first step. Then the following all work:
```
x in l and (lambda: print("yes"))() # what an overkill!
(x in l or print("no")) and print("yes") # note the order, print returns None
print("yes") if x in l else print("no") # typical A if Cond else Y
print("yes" if x in l else "no") # a more condensed form
```
For even more fun, if you're into this, you can consider this - prints and returns True or False, depending on the `x in l` condition (to get the False I used the double not):
```
def check_and_print(x, l):
return x in l and not print("yes") or not not print("no")
```
That was ugly. To make the print transparent, you could define 2 other version
of print, which return True or False. This could actually be useful for logging:
```
def trueprint(*args, **kwargs):
print(*args, **kwargs)
return True
def falseprint(*args, **kwargs):
return not trueprint(*args, **kwargs)
result = x in l and trueprint("yes") or falseprint("no")
```
|
9,345,250
|
I have tried:
```
>>> l = [1,2,3]
>>> x = 1
>>> x in l and lambda: print("Foo")
x in l && print "Horray"
^
SyntaxError: invalid syntax
```
A bit of googling revealed that `print` is a statement in `python2` whereas it's a function in `python3`. But, I have tried the above snipped in `python3` and it throws SyntaxError exception.
Any idea on how can I do it in **one line**? (Readability or google programming practice is not an issue here)
|
2012/02/18
|
[
"https://Stackoverflow.com/questions/9345250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1218583/"
] |
```
l = [1, 2, 3]
x = 1
if x in l: print "Foo"
```
I'm not being a smart ass, this is the way to do it in **one line**. Or, if you're using Python3:
```
if x in l: print("Foo")
```
|
1. If you want to print something different in both true and false cases, use a conditional **expression** to create the value to print: `print ('foo' if x in l else 'bar')`.
2. If you just want a function in Python 2 that outputs, you can try `sys.stdout.write` (after you first `import sys` of course), but keep in mind that this is nowhere near as flexible; here you're treating the standard output as a file-like object (which it is).
3. `lambda` almost certainly buys you nothing here.
4. Using and-or chaining tricks is incredibly un-Pythonic. The fact that people struggled with these hacks anyway, knowing how awful they were, was exactly why those conditional expressions from point 1 were added to the language. There was a **lot** of discussion regarding syntax.
|
9,345,250
|
I have tried:
```
>>> l = [1,2,3]
>>> x = 1
>>> x in l and lambda: print("Foo")
x in l && print "Horray"
^
SyntaxError: invalid syntax
```
A bit of googling revealed that `print` is a statement in `python2` whereas it's a function in `python3`. But, I have tried the above snipped in `python3` and it throws SyntaxError exception.
Any idea on how can I do it in **one line**? (Readability or google programming practice is not an issue here)
|
2012/02/18
|
[
"https://Stackoverflow.com/questions/9345250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1218583/"
] |
`lambda` creates, well a lambda. It needs to be *called* to execute it. You cannot do this that way, because Python doesn't allow statements in this context, only expressions (including function calls).
To make `print` a function in Python 2.x, try:
```
from __future__ import print_function
x in l and print('foo')
```
Be wary though. If you try:
```
x in l and print('foo') or print('bar')
```
it won't work, because print returns `None`, so the first `and` expression is False, so both `print`s will be executed. In Python 3.x you don't need the import.
If you won't have complex short-circuiting (i.e. just one `and` or `or`), or you know your functions or expressions won't surprise the short-circuiting logic, there's nothing wrong with the code. Otherwise, try the non-short-circuiting 1-liner:
```
print('foo') if x in l else print('bar')
```
This form is recommended only if the probability/expectation of the conditional to be True is *vastly* higher than being False. Otherwise, plain good-old `if-else` is the way to go.
|
Getting rid of the shortcomings of print as a statement in Python2.x using `from __future__ import print_function` is the first step. Then the following all work:
```
x in l and (lambda: print("yes"))() # what an overkill!
(x in l or print("no")) and print("yes") # note the order, print returns None
print("yes") if x in l else print("no") # typical A if Cond else Y
print("yes" if x in l else "no") # a more condensed form
```
For even more fun, if you're into this, you can consider this - prints and returns True or False, depending on the `x in l` condition (to get the False I used the double not):
```
def check_and_print(x, l):
return x in l and not print("yes") or not not print("no")
```
That was ugly. To make the print transparent, you could define 2 other version
of print, which return True or False. This could actually be useful for logging:
```
def trueprint(*args, **kwargs):
print(*args, **kwargs)
return True
def falseprint(*args, **kwargs):
return not trueprint(*args, **kwargs)
result = x in l and trueprint("yes") or falseprint("no")
```
|
9,345,250
|
I have tried:
```
>>> l = [1,2,3]
>>> x = 1
>>> x in l and lambda: print("Foo")
x in l && print "Horray"
^
SyntaxError: invalid syntax
```
A bit of googling revealed that `print` is a statement in `python2` whereas it's a function in `python3`. But, I have tried the above snipped in `python3` and it throws SyntaxError exception.
Any idea on how can I do it in **one line**? (Readability or google programming practice is not an issue here)
|
2012/02/18
|
[
"https://Stackoverflow.com/questions/9345250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1218583/"
] |
`lambda` creates, well a lambda. It needs to be *called* to execute it. You cannot do this that way, because Python doesn't allow statements in this context, only expressions (including function calls).
To make `print` a function in Python 2.x, try:
```
from __future__ import print_function
x in l and print('foo')
```
Be wary though. If you try:
```
x in l and print('foo') or print('bar')
```
it won't work, because print returns `None`, so the first `and` expression is False, so both `print`s will be executed. In Python 3.x you don't need the import.
If you won't have complex short-circuiting (i.e. just one `and` or `or`), or you know your functions or expressions won't surprise the short-circuiting logic, there's nothing wrong with the code. Otherwise, try the non-short-circuiting 1-liner:
```
print('foo') if x in l else print('bar')
```
This form is recommended only if the probability/expectation of the conditional to be True is *vastly* higher than being False. Otherwise, plain good-old `if-else` is the way to go.
|
1. If you want to print something different in both true and false cases, use a conditional **expression** to create the value to print: `print ('foo' if x in l else 'bar')`.
2. If you just want a function in Python 2 that outputs, you can try `sys.stdout.write` (after you first `import sys` of course), but keep in mind that this is nowhere near as flexible; here you're treating the standard output as a file-like object (which it is).
3. `lambda` almost certainly buys you nothing here.
4. Using and-or chaining tricks is incredibly un-Pythonic. The fact that people struggled with these hacks anyway, knowing how awful they were, was exactly why those conditional expressions from point 1 were added to the language. There was a **lot** of discussion regarding syntax.
|
61,642,246
|
What I want to make is angrybirds game.
There is a requirement
1.Draw a rectangle randomly between 100 and 200 in length and length 10 in length.
2. Receive the user inputting the launch speed and the launch angle.
3. Project shells square from origin (0,0).
4. If the shell is hit, we'll end it, or we'll continue from number two.
So this is what I wrote
```
import turtle as t
import math
import random
def square():
for i in range(4):
t.forward(10)
t.left(90)
def fire():
x = 0
y = 0
speed = int(input("속도:"))
angle = int(input("각도:"))
vx = speed * math.cos(angle * 3.14/180.0)
vy = speed * math.sin(angle * 3.14/180.0)
while t.ycor() >= 0:
vx = vx
vy = vy - 10
x = x + vx
y = y + by
t.goto(x,y)
d = t.distance(d1+5, 5)
if d < 10:
print("Game End")
else:
t.up()
t.goto(0,0)
t.down()
fire()
d1 = random.randint(100,200)
t.up()
t.forward(d1)
t.down()
square()
t.up()
t.goto(0,0)
t.down()
fire()
```
I want to get an answer to this problem.
The problem is I want to calculate a minimum distance between a point(target point is (d1+5,5)) and a parabola which turtle draw. so I try to find an answer searching in google, python book, but I can't find it.
please help me
|
2020/05/06
|
[
"https://Stackoverflow.com/questions/61642246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13483726/"
] |
the local declaration has to be like this way,
```
int (*localArr)[M][N]; //pointer to an MxN array
//int * localArr[m][N];//An MxN array of pointer to int
```
|
What do you want to achieve? If you just want to print your 2d array then why don't you use this approach?
```
void print(int localArr[M][N]) {
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
cout << localArr[i][j];
}
}
}
```
If there are some constraints then Nitheesh is right!
|
61,642,246
|
What I want to make is angrybirds game.
There is a requirement
1.Draw a rectangle randomly between 100 and 200 in length and length 10 in length.
2. Receive the user inputting the launch speed and the launch angle.
3. Project shells square from origin (0,0).
4. If the shell is hit, we'll end it, or we'll continue from number two.
So this is what I wrote
```
import turtle as t
import math
import random
def square():
for i in range(4):
t.forward(10)
t.left(90)
def fire():
x = 0
y = 0
speed = int(input("속도:"))
angle = int(input("각도:"))
vx = speed * math.cos(angle * 3.14/180.0)
vy = speed * math.sin(angle * 3.14/180.0)
while t.ycor() >= 0:
vx = vx
vy = vy - 10
x = x + vx
y = y + by
t.goto(x,y)
d = t.distance(d1+5, 5)
if d < 10:
print("Game End")
else:
t.up()
t.goto(0,0)
t.down()
fire()
d1 = random.randint(100,200)
t.up()
t.forward(d1)
t.down()
square()
t.up()
t.goto(0,0)
t.down()
fire()
```
I want to get an answer to this problem.
The problem is I want to calculate a minimum distance between a point(target point is (d1+5,5)) and a parabola which turtle draw. so I try to find an answer searching in google, python book, but I can't find it.
please help me
|
2020/05/06
|
[
"https://Stackoverflow.com/questions/61642246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13483726/"
] |
the local declaration has to be like this way,
```
int (*localArr)[M][N]; //pointer to an MxN array
//int * localArr[m][N];//An MxN array of pointer to int
```
|
If we change the sizes to make it easier to fit:
```
#define M 2
#define N 3
```
Then somewhat graphically the variable `arr` is something like this:
```
+-----+ +--------+--------+--------+--------+--------+--------+
| arr | ---> | [0][0] | [0][1] | [0][2] | [1][0] | [1][1] | [1][2] |
+-----+ +--------+--------+--------+--------+--------+--------+
```
`arr` is a pointer. It points to an array of arrays, where each element is an `int`.
That means you can dereference `arr` to get what it points to, and then use array indexing on that to get an `int` value:
```
int value = (*arr)[0][1];
```
Now if we take `localArr` instead, it's more like
```
+----------------+----------------+----------------+----------------+----------------+----------------+
| localArr[0][0] | localArr[0][1] | localArr[0][2] | localArr[1][0] | localArr[1][1] | localArr[1][2] |
+----------------+----------------+----------------+----------------+----------------+----------------+
```
`localArr` is an array of arrays, where each element is a `int *`.
So you need an `int *` to get a single element:
```
int *pointer = localArr[0][1];
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.