Share globals across multiple files - python-2.7

I'm extremely new to python, so I apologize if this is a simple question, I'm creating a program where I need to share a global variable across multiple files. I have a file called settings.py that looks like this:
def init():
global BACKPACK
global SURVIVAL_TOOLS
BACKPACK = {}
SURVIVAL_TOOLS = {}
I import those settings into another file called battle.py and prepare.py:
from settings import init
# battle.py #
def win_battle(animal):
print "You do one final slash and the {} goes limp." \
" You pick it up and start walking back to camp.".format(animal)
init.SURVIVAL_TOOLS['meat'] = 1
if 'camp' in init.SURVIVAL_TOOLS:
return_to_camp()
else:
options = ['create a fire', 'create a camp']
for opt in options:
print "TEST" # TODO: FINISH THIS METHOD
from settings import init
def gather_gear(player):
# prepare.py #
"""
Gather your gear from a set list of items you have available
:type player: String
"""
print formatter()
print "{}! Shouts Jack as he runs towards you." \
" Do you wanna go Hiking this weekend?" \
" You ponder this for a second." \
" What the hell, you think." \
" Can't be any worse then last time." \
" Sure, Jack! You say enthusiastically." \
" Just let me get some things prepared.\n".format(player)
options = { # All the items that are available to you before you leave
'fire starter': 1,
'matches': randint(1, 5), # Uses random integers as the value
'flash light': 1,
'sleeping bag': 1,
'canteen cup': 1,
'dried foods': randint(2, 6),
'shovel': 1,
'knife': 1,
'pair of socks': randint(2, 10),
'granola bars': randint(2, 5),
'machete': 1,
'bottle of whiskey': 1,
'heavy jacket': 1,
'tinder pieces': randint(3, 5)
}
for key in options:
print "You have {} {}".format(options[key], key) # Print out all your items and make it look pretty
count = 3
num_in_pack = 0
print '\n'
while count != 0:
item = raw_input("What would you like to take with you? Choose {} items one at a time: ".format(str(count))).lower()
if item in options and item not in init.BACKPACK: # As long as the item is available you can use it
init.BACKPACK[item] = options[item] # Add the item value to your backpack constant
count -= 1
print "You throw a {} in your backpack".format(item)
num_in_pack += 1
if num_in_pack == 3: # If you have three items, lets begin!
print "Your backpack is now full."
start_adventure(player)
else:
print "Can't bring that item."
return init.BACKPACK
However I get a warning in my IDE that:
Cannot find reference 'SURVIVAL_TOOLS' in 'function' less... (Ctrl+F1 Alt+T)
This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items.
And when this program is run I get:
Traceback (most recent call last):
File "game.py", line 1, in <module>
from prepare import *
File "C:\Users\thomas_j_perkins\bin\python\game\prepare.py", line 1, in <modul
e>
from game import *
File "C:\Users\thomas_j_perkins\bin\python\game\game.py", line 2, in <module>
from choices import *
File "C:\Users\thomas_j_perkins\bin\python\game\choices.py", line 3, in <modul
e>
from prepare import BACKPACK
ImportError: cannot import name BACKPACK
I got the idea of moving all my constants to a single file from this question
So my question is, why am I unable to use the constant variables that I have created in the settings.py file?
EDIT:
I attempted to do init().BACKPACK and am now getting the error:
Traceback (most recent call last):
File "game.py", line 94, in <module>
welcome_screen()
File "game.py", line 85, in welcome_screen
gather_gear(player_name)
File "C:\Users\thomas_j_perkins\bin\python\game\prepare.py", line 45, in gathe
r_gear
if item in options and item not in init().BACKPACK: # As long as the item i
s available you can use it
AttributeError: 'NoneType' object has no attribute 'BACKPACK'

When you do global BACKPACK; BACKPACK = {}, you are creating a module attribute called BACKPACK. To access it, change from settings import init to import settings. This will allow you to use all the module attributes of settings in your code:
settings.SURVIVAL_TOOLS['meat'] = 1
You also need to make sure that settings.init is called once in your program. You can either call it somewhere in your code, or better yet, modify settings.py to look like this:
BACKPACK = {}
SURVIVAL_TOOLS = {}
No function definitions, no globals. This code will get run the first time the module is imported anywhere. Next time is is imported, the dicts will not be modified.

Related

Type error: 'function' object is not subscriptable with tensor flow

I'm trying to execute the code from https://github.com/lucfra/RFHO, more specifically from RFHO starting example.ipynb. The only thing I want to change is doing it in forward mode instead of reverse mode. So this is the changed code:
import tensorflow as tf
import rfho as rf
from rfho.datasets import load_mnist
mnist = load_mnist(partitions=(.05, .01)) # 5% of data in training set, 1% in validation
# remaining in test set (change these percentages and see the effect on regularization hyperparameter)
x, y = tf.placeholder(tf.float32, name='x'), tf.placeholder(tf.float32, name='y')
# define the model (here use a linear model from rfho.models)
model = rf.LinearModel(x, mnist.train.dim_data, mnist.train.dim_target)
# vectorize the model, and build the state vector (augment by 1 since we are
# going to optimize the weights with momentum)
s, out, w_matrix = rf.vectorize_model(model.var_list, model.inp[-1], model.Ws[0],
augment=0)
# (this function will print also some tensorflow infos and warnings about variables
# collections... we'll solve this)
# define error
error = tf.reduce_mean(rf.cross_entropy_loss(labels=y, logits=out), name='error')
constraints = []
# define training error by error + L2 weights penalty
rho = tf.Variable(0., name='rho') # regularization hyperparameter
training_error = error + rho*tf.reduce_sum(tf.pow(w_matrix, 2))
constraints.append(rf.positivity(rho)) # regularization coefficient should be positive
accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(out, 1), tf.argmax(y, 1)),
"float"), name='accuracy')
# define learning rates and momentum factor as variables, to be optimized
eta = tf.Variable(.01, name='eta')
#mu = tf.Variable(.5, name='mu')
# now define the training dynamics (similar to tf.train.Optimizer)
optimizer = rf.GradientDescentOptimizer.create(s, eta, loss=training_error)
# add constraints for learning rate and momentum factor
constraints += optimizer.get_natural_hyperparameter_constraints()
# we want to optimize the weights w.r.t. training_error
# and hyperparameters w.r.t. validation error (that in this case is
# error evaluated on the validation set)
# we are going to use ReverseMode
hyper_dict = {error: [rho, eta]}
hyper_opt = rf.HyperOptimizer(optimizer, hyper_dict, method=rf.ForwardHG)
# define helper for stochastic descent
ev_data = rf.ExampleVisiting(mnist.train, batch_size=2**8, epochs=200)
tr_suppl = ev_data.create_supplier(x, y)
val_supplier = mnist.validation.create_supplier(x, y)
test_supplier = mnist.test.create_supplier(x, y)
# Run all for some hyper-iterations and print progresses
def run(hyper_iterations):
with tf.Session().as_default() as ss:
ev_data.generate_visiting_scheme() # needed for remembering the example visited in forward pass
for hyper_step in range(hyper_iterations):
hyper_opt.initialize() # initializes all variables or reset weights to initial state
hyper_opt.run(ev_data.T, train_feed_dict_supplier=tr_suppl,
val_feed_dict_suppliers=val_supplier,
hyper_constraints_ops=constraints)
#
# print('Concluded hyper-iteration', hyper_step)
# print('Test accuracy:', ss.run(accuracy, feed_dict=test_supplier()))
# print('Validation error:', ss.run(error, feed_dict=val_supplier()))
saver = rf.Saver('Staring example', collect_data=False)
with saver.record(rf.Records.tensors('error', fd=('x', 'y', mnist.validation), rec_name='valid'),
rf.Records.tensors('error', fd=('x', 'y', mnist.test), rec_name='test'),
rf.Records.tensors('accuracy', fd=('x', 'y', mnist.validation), rec_name='valid'),
rf.Records.tensors('accuracy', fd=('x', 'y', mnist.test), rec_name='test'),
rf.Records.hyperparameters(),
rf.Records.hypergradients(),
): # a context to print some statistics.
# If you execute again any cell containing the model construction,
# restart the notebook or reset tensorflow graph in order to prevent errors
# due to tensor namings
run(20) # this will take some time... run it for less hyper-iterations for a quicker look
The problem is I get a Type error: 'function' object is not subscriptable back after the first iteration:
Traceback (most recent call last):
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydev_run_in_console.py", line 52, in run_file
pydev_imports.execfile(file, globals, locals) # execute the script
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/Users/repierau/Documents/FSHO/RFHO-master/rfho/examples/simply_example.py", line 80, in <module>
run(20) # this will take some time... run it for less hyper-iterations for a quicker look
File "/Users/repierau/Documents/FSHO/RFHO-master/rfho/examples/simply_example.py", line 63, in run
hyper_constraints_ops=constraints)
File "/Users/repierau/Documents/FSHO/RFHO-master/rfho/save_and_load.py", line 624, in _saver_wrapped
res = f(*args, **kwargs)
File "/Users/repierau/Documents/FSHO/RFHO-master/rfho/hyper_gradients.py", line 689, in run
hyper_batch_step=self.hyper_batch_step.eval())
File "/Users/repierau/Documents/FSHO/RFHO-master/rfho/hyper_gradients.py", line 581, in run_all
return self.hyper_gradients(val_feed_dict_suppliers, hyper_batch_step)
File "/Users/repierau/Documents/FSHO/RFHO-master/rfho/hyper_gradients.py", line 551, in hyper_gradients
val_sup_lst.append(val_feed_dict_supplier[k])
TypeError: 'function' object is not subscriptable

How to solve AttributeError in python active_directory?

Running the below script works for 60% of the entries from the MasterGroupList however suddenly fails with the below error. although my questions seem to be poor ou guys have been able to help me before. Any idea how I can avoid getting this error? or what is trhoughing off the script? The masterGroupList looks like:
Groups Pulled from AD
SET00 POWERUSER
SET00 USERS
SEF00 CREATORS
SEF00 USERS
...another 300 entries...
Error:
Traceback (most recent call last):
File "C:\Users\ks185278\OneDrive - NCR Corporation\Active Directory Access Scr
ipt\test.py", line 44, in <module>
print group.member
File "C:\Python27\lib\site-packages\active_directory.py", line 805, in __getat
tr__
raise AttributeError
AttributeError
Code:
from active_directory import *
import os
file = open("C:\Users\NAME\Active Directory Access Script\MasterGroupList.txt", "r")
fileAsList = file.readlines()
indexOfTitle = fileAsList.index("Groups Pulled from AD\n")
i = indexOfTitle + 1
while i <= len(fileAsList):
fileLocation = 'C:\\AD Access\\%s\\%s.txt' % (fileAsList[i][:5], fileAsList[i][:fileAsList[i].find("\n")])
#Creates the dir if it does not exist already
if not os.path.isdir(os.path.dirname(fileLocation)):
os.makedirs(os.path.dirname(fileLocation))
fileGroup = open(fileLocation, "w+")
#writes group members to the open file
group = find_group(fileAsList[i][:fileAsList[i].find("\n")])
print group.member
for group_member in group.member: #this is line 44
fileGroup.write(group_member.cn + "\n")
fileGroup.close()
i+=1
Disclaimer: I don't know python, but I know Active Directory fairly well.
If it's failing on this:
for group_member in group.member:
It could possibly mean that the group has no members.
Depending on how phython handles this, it could also mean that the group has only one member and group.member is a plain string rather than an array.
What does print group.member show?
The source code of active_directory.py is here: https://github.com/tjguk/active_directory/blob/master/active_directory.py
These are the relevant lines:
if name not in self._delegate_map:
try:
attr = getattr(self.com_object, name)
except AttributeError:
try:
attr = self.com_object.Get(name)
except:
raise AttributeError
So it looks like it just can't find the attribute you're looking up, which in this case looks like the 'member' attribute.

django:ValueError need more than 1 value to unpack

I'm using ajax and django for dynamically populate a combo box. ajax component works really fine and it parse the data to the view but int the view, when i'm using the spiting function it gives me a exception called "Value Error:need more than 1 value to unpack ". can anyone helps me to figure out the error :) :)
code:
def dropdownPopulate(request):
if request.method=='POST' :
key = request.POST['id']
else:
key=""
level, tree_id=key.split(",")
next_nodes=Structure.objects.filter(tree_id=key[tree_id]).filter(level=key[level])
context={'name':next_nodes}
return render_to_response('renderAjax.html',context)
This is because s.split(',') is returning list of length 1:
level, tree_id = key.split(',')
Make sure it return list of length 2:
parts = key.split(',')
if len(parts) == 2:
level, tree_id = parts
elif len(parts) == 1:
level = parts[0]
tree_id = None
else:
# do something
level = tree_id = None
pass
The apply filter like this:
next_nodes = Structure.objects.all()
if level:
next_nodes = next_nodes.filter(level=level)
if tree_id:
next_nodes = next_nodes.filter(tree_id=tree_id)
Probably error occurs at this line:
level, tree_id=key.split(",")
It is needed to handle the situation, when key will not have ",". Or maybe it will have more than one ",".
Look at your code:
if request.method=='POST' :
key = request.POST['id']
else:
key=""
It is possible, that key will be a blank string.
Here are examples, when error can occur:
1.
>>> key = ""
>>> level, tree_id=key.split(",")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack
2.
>>> key = "a,b,c"
>>> level, tree_id=key.split(",")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
Only this will be fine (when it is only one ","):
>>> key = "a,b"
>>> level, tree_id=key.split(",")
>>>
You have multiple problems.
level, tree_id=key.split(",")
This will fail, as key may not have ,, so split will not return 2 values.
next_nodes=Structure.objects.filter(tree_id=key[tree_id]).filter(level=key[level])
Here you are accessing key as dict, which is incorrect as it is string.

Why can't an object use a method as an attribute in the Python package ComplexNetworkSim?

I'm trying to use the Python package ComplexNetworkSim, which inherits from networkx and SimPy, to simulate an agent-based model of how messages propagate within networks.
Here is my code:
from ComplexNetworkSim import NetworkSimulation, NetworkAgent, Sim
import networkx as nx
#define constants for our example of states
NO_MESSAGE = 0
MESSAGE = 1
class Message(object):
def __init__(self,topic_pref):
self.relevance = topic_pref
class myAgent(NetworkAgent):
def __init__(self, state, initialiser):
NetworkAgent.__init__(self, state, initialiser)
self.state = MESSAGE
self.topic_pref = 0.5
def Run(self):
while True:
if self.state == MESSAGE:
self.message = self.Message(topic_pref, self, TIMESTEP)
yield Sim.hold, self, NetworkAgent.TIMESTEP_DEFAULT
elif self.state == NO_MESSAGE:
yield Sim.hold, self, NetworkAgent.TIMESTEP_DEFAULT
# Network and initial states of agents
nodes = 30
G = nx.scale_free_graph(nodes)
states = [MESSAGE for n in G.nodes()]
# Simulation constants
MAX_SIMULATION_TIME = 25.0
TRIALS = 2
def main():
directory = 'test' #output directory
# run simulation with parameters
# - complex network structure
# - initial state list
# - agent behaviour class
# - output directory
# - maximum simulation time
# - number of trials
simulation = NetworkSimulation(G,
states,
myAgent,
directory,
MAX_SIMULATION_TIME,
TRIALS)
simulation.runSimulation()
if __name__ == '__main__':
main()
(There may be other problems downstream with this code and it is not fully tested.)
My problem is that the myAgent object is not properly calling the method Run as an attribute. Specifically, this is the error message that I get when I try to run the above code:
Starting simulations...
---Trial 0 ---
set up agents...
Traceback (most recent call last):
File "simmessage.py", line 55, in <module>
main()
File "simmessage.py", line 52, in main
simulation.runSimulation()
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/ComplexNetworkSim-0.1.2-py2.7.egg/ComplexNetworkSim/simulation.py", line 71, in runSimulation
self.runTrial(i)
File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/ComplexNetworkSim-0.1.2-py2.7.egg/ComplexNetworkSim/simulation.py", line 88, in runTrial
self.activate(agent, agent.Run())
AttributeError: 'myAgent' object has no attribute 'Run'
Does anybody know why this is? I can't figure how my code differs substantially from the example in ComplexNetworkSim.
I've run your code on my machine and there the Run method gets called.
My best guess is what Paulo Scardine wrote, but since i can't reproduce the problem i can't actually debug it.

What is the error in following python code

import sys
def Hello(name):
name = name + '!!!'
print 'Hello' , name
def main():
Hello(sys.argv[1])
if __name__ == '__main__':
main()
Here is the error
Traceback (most recent call last):
File "D:\pythonPractice\firstPython.py", line 13, in <module>
main()
File "D:\pythonPractice\firstPython.py", line 9, in main
Hello(sys.argv[1])
IndexError: list index out of range
I have also tried sys.argv[2] but error remains
First things first, I think the code you originally posted (with Hello(sys.argv[0])) is not what you actually have. It doesn't match the error, which states sys.argv[1], so what you probably have is:
def main():
Hello(sys.argv[1])
As to the error then, it's because you haven't provided an argument when running. You need to do so, such that sys.argv[1] exists:
python helloprog Pax
You would find a more robust main as:
def main():
if len(sys.argv) < 2:
Hello("whoever you are")
else:
Hello(sys.argv[1])
which will detect when you haven't provided an argument, and use a suitable default rather than raising an exception.
Have you used
sys.argv[0]
Since this returns a list , you may not have elements >1