I have a small class:
import pickle
import shelve
class Base:
def __init__(self, userid, username, pic_list=[]):
self.userid=userid
self.pic_list=pic_list
self.username_list=[username]
self.username=self.username_list[-1]
def pic_add(self, pic):
self.pic_list.append(pic)
if __name__ == '__main__':
path="D:/"
db = shelve.open(path+'test_base')
db['111']=Base('111','111name',[4,5,6])
db['111'].pic_add('123dsf')
print (sorted(db['111'].pic_list))
db.close()
I want to append 123dsf to pic_list of class instance "111". But the result I get is:
[4, 5, 6]
[Finished in 0.3s]
I want to receive [4, 5, 6, 123dsf]. What am I doing wrong?
Thanx.
P.S. Hint - It is something with shelve module syntax, 'cos adding 'y' works fine:
db['111']=Base('111','111name',[4,5,6])
db['111'].pic_add('123dsf')
Base.pic_add(db['111'],'123dsf')
y=Base('222','222name',[7,8,9])
y.pic_add('pis')
print (y.pic_list)
print (sorted(db['111'].pic_list))
The result is:
[7, 8, 9, 'pis']
[4, 5, 6]
[Finished in 0.4s]
Two ways to do it - as proposed in the documentation: https://docs.python.org/2/library/shelve.html#shelve-example
1. set writeback flag:
db = shelve.open(path+'test_base', writeback=True)
allows you mutate objects in place:
db['111'].pic_add('123dsf')
2. Retrieve copy of stored object, then mutate copy, then store copy back:
cpy = db['111']
cpy.pic_add('123dsf')
db['111'] = cpy
Related
I have a list of type Person in scala like this:
Person("P1", "Person 1", List(WorkStation 1, WorkStation 2))
Person("P2", "Person 2", List(WorkStation 1, WorkStation 3, WorkStation 4, WorkStation 5))
Person("P3", "Person 3", List(WorkStation 3, WorkStation 5))
Person("P4", "Person 4", List(WorkStation 2, WorkStation 4))
I want to code a function that receives this list and a parameter ws: WorkStation.WorkStation (it is a case object) and then I want that function to return the first element Person which has ws in it's list.
For example, if ws was Workstation 3 I wanted to return the list entry with Person 2.
I thought about doing something like this:
def setPerson(ws: WorkStation.WorkStation, totalPersons: List[Person]): Person = {
totalPersons.map { p => if (p.workstations.contains(ws)) return p }
}
However, this doesn't compile, because it gives me an error and it is not the most functional approach for sure.
Can anyone help me?
You can use collectFirst:
totalPersons.collectFirst{ case p if p.workstations.contains(ws) => p }
Or find:
totalPersons.find(_.workstations.contains(ws))
See here for more information.
totalPersons.find(elem => elem.workstations.contains(ws))
or
totalPersons.find(_.workstations.contains(ws))
the 1st is more readable (specially for scala rookies), but the 2nd is common syntactic sugar used
i have following code in two files:
operation1.py
class App_Name():
def __init__(self):
self.type_option = ""
def Intro(self):
self.type_option = input("Chose one option: ")
...
start = App_Name()
start.Intro()
menu.py
from operation1 import App_name
aP = App_Name()
if aP.type_option == 1:
do smth
elif aP.type.type_option == 2:
do smth 2
If i type 1, i expect to run commands from first if condition. When i try to print App_name.type_option it seems to be empty. How can i pass value of aP.type_option to menu.py?
start and aP are 2 different instances. Since type_option is bound to one instance, start.type_option contains the input (as string), whereas aP.type_option contains the empty string you set in the __init__ method.
Remove start instanciation in your operation1 module or you'll be prompted when importing it!
Then fix menu.py as follows:
from operation1 import App_name
aP = App_Name()
aP.Intro()
if aP.type_option == "1":
do smth
elif aP.type.type_option == "2":
do smth 2
(note that comparison must be done against strings because Python 3 input returns strings, doesn't evaluate literals like python 2 input did)
Using xstream, how can I create a stream that only emits when it's input stream emits a new value
Here is a diagram
input -----1--1-1--2-3--3--3---5-|
output -----1-------2-3---------5-|
While the core xstream library is comprised of a few well chosen operators, additional operators are included as extras and can accessed by their path.
import xs from 'xstream';
import dropRepeats from 'xstream/extra/dropRepeats'
const stream = xs.of(1, 1, 1, 2, 3, 3, 3, 5)
.compose(dropRepeats())
stream.addListener({
next: i => console.log(i),
error: err => console.error(err),
complete: () => console.log('completed')
});
The .compose operator is used to drop the extra methods into the stream.
source:
https://github.com/staltz/xstream/blob/master/EXTRA_DOCS.md#dropRepeats
I've been working on a card game that gets your deck and picks 1 out of three powers cards but whenever I try to run it, it gives me an error
Error:
Error: In call to CPUser::addCards(), was given too many arguments; it expects 1 at Server/CPUser.pm line 427.
Line 427:
if($intItem == 821){ #Adds Card Jitsu Cards for Classic
$self->addCards($self->buildStarterDeck);
}
and this the buildStarterDeck Method
method buildStarterDeck {
sub get_cards;
my (#stackone, #stacktwo) = get_cards;
sub get_cards
{
my #start_cards = (1, 6, 9, 14, 17, 20, 22, 23, 26);
my #power_cards = (73, 81, 89);
#power_cards = $power_cards[rand #power_cards];
return (#start_cards, #power_cards);
}
}
The addCard method is empty since I've been trying to figure out this error and I couldn't get any luck.
The problem is in your definition of addCards which you persist in hiding from us despite multiple requests to see it. It must look something like this
method addCards($param) {
...;
}
But you are passing it a ten-element list in $self->addCards($self->buildStarterDeck) so the given too many arguments error is raised. You don't explain what you want it to do, but something like this is probably more appropriate
method addCards(#cards) {
...;
}
You really shouldn't declare subroutines inside other subroutines. It doesn't limit the scope of the inner subroutine, but you can create a closure over variables declared in the outer subroutine that doesn't work properly
Also bearing in mind zdim's warning from the comments, your code should look more like this
use strict;
use warnings 'all';
use Method::Signatures;
method buildStarterDeck {
my #stack = get_cards;
}
sub get_cards {
my #start_cards = (1, 6, 9, 14, 17, 20, 22, 23, 26);
my #power_cards = (73, 81, 89);
$power_card = $power_cards[rand #power_cards];
return (#start_cards, $power_card);
}
According to the documentation found in http://ask.github.com/celery/userguide/routing.html#manual-routing i can pass a queue parameter to apply_async in order to route a task to a particular queue. However when using TaskSet i get
TypeError at /some/path/
apply_async() got an unexpected keyword argument 'queue'
Which is undestandable given the following code in the TaskSet class https://github.com/ask/celery/blob/master/celery/task/sets.py#L122
def apply_async(self, connection=None, connect_timeout=None,
publisher=None, taskset_id=None):
"""Apply taskset."""
app = self.app
if app.conf.CELERY_ALWAYS_EAGER:
return self.apply(taskset_id=taskset_id)
with app.default_connection(connection, connect_timeout) as conn:
setid = taskset_id or uuid()
pub = publisher or self.Publisher(connection=conn)
try:
results = self._async_results(setid, pub)
finally:
if not publisher: # created by us.
pub.close()
return app.TaskSetResult(setid, results)
I have an undefined number of tasks to which i need to apply special routing on some situations, how should i handle this? not use a TaskSet?
You can use subtasks with options argument
>>> from celery.task.sets import TaskSet
>>> from tasks import add
>>>
>>> job = TaskSet(tasks=[add.subtask(args=(i, i),options={'queue':'celery'}) for i in range(10)])
>>> result = job.apply_async()
>>> result.ready()
True
>>> job
[tasks.add(0, 0), tasks.add(1, 1), tasks.add(2, 2), tasks.add(3, 3), tasks.add(4, 4), tasks.add(5, 5), tasks.add(6, 6), tasks.add(7, 7), tasks.add(8, 8), tasks.add(9, 9)]
>>>